Hiding WLAN password when pushing to GitHub I have started to use GitHub to store Arduino code. However some of my code uses the SSID and password for my WLAN which I don’t want published.

A common way of handling this in non-embedded programming is to use a configuration file, but that doesn’t seem to be a viable approach in programming the Arduino. I’m currently just commenting out the sensitive information before pushing it to GitHub, but one day I’m sure I’ll forget.

Is there another – better - way of handling this?

You could commit the following file into your project, named
credentials.h:

// Replace with your actual SSID and password:

#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

Near the beginning of your sketch, you add:

#include "credentials.h"

const char ssid[] = WIFI_SSID;
const char password[] = WIFI_PASSWD;

Now, you can edit credentials.h to add your real SSID and password, and
go on with your normal git workflow, with one exception: never
git add credentials.h again, nor git commit -a.

Now, git will always remind you that credentials.h has been modified and
is not staged for commit. It will do so even if you add the file to your
.gitignore. If you always review your changes before committing, this is
only a minor inconvenience. If, on the other hand, you tend to
git commit -a without reviewing what you are committing, then this
solution is likely not for you.

Edit: An idea I got from reading Chris Stratton's comments. If
you use a Makefile in your own workflow (this has already been discussed
in this site a few times), you could commit this credentials.h to your
repo:

#ifndef CREDENTIALS_H
#define CREDENTIALS_H

// Replace with your actual SSID and password:
#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

#endif

Make a copy of this file named true-credentials.h and put the real
credentials there (but do not rename the include guard). Then add to
your Makefile

CFLAGS += -include true-credentials.h

Keep true-credentials.h and the Makefile out of the repo. You can add
them to your .gitignore or, better yet, to .git/info/exclude.

Now you have a compilable version with dummy credentials in the
repository, you have the true credentials when you compile on your own
machine, and git does not bother you about credentials.h being changed.


Building a digital camera? Does anyone know of a way to DIY a digital camera by buying a sensor and lens and processing the image using an Arduino?

You can buy a camera module for the Arduino, and you can interface it fairly simply.  There are numerous modules around - ask Google, it knows more than me.

But I have yet to work out why people do it.  All you can do with an Uno is to pass the data through to something else like a PC to process the image - so why wouldn't you just use a simple webcam?

The Arduino UNO has 2KB of RAM.  A 24-bit 640x480 image (VGA) requires (640*480*3)/1024 = 900KB to store it in memory.  If you really wanted to process an image on an Uno then you would be limited to (say 8-bit grayscale) 48x32 pixels (1.5KB) which is pretty pointless really.

Even a Due would only allow (again grayscale) around 320x240 (which is better) but nothing colour unless you want to start messing with CLUTs which aren't fun when receiving a truecolour (24-bit) image from a camera.

For this kind of task you are better off with an embedded computer with plenty of RAM such as a Raspberry Pi or maybe a Galileo or something.


Neopixel led strip stops responding after change in brightness I have an arduino UNO hooked up to a neopixel LED strip with 148 lights.  Most of the time it works fine, but when I upload a program that changes the brightness frequently, particularly when I increase brightness, only the first 8 LEDs continue responding.  The rest get stuck.

Here's an example of the kind of code that sets this issue off.  To fix it, I usually have to restart the lights and the arduino and sometimes upload a blank program to the arduino.

I'm pretty new to arduino programming so and help would be really appreciated.  Thank you.

#include "FastLED.h"

FASTLED_USING_NAMESPACE

// FAST LED definitions
#define DATA_PIN    3
#define LED_TYPE    WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS    148

CRGB leds[NUM_LEDS];
#define DATA_PIN 3 // Output Pin to Data Line on Strip

int fadeAmount = 5;
int brightness = 0;

void setup()
{
   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
}

void loop()
{
   for(int i = 0; i < NUM_LEDS; i++ )
   {
   leds[i].setRGB(0,255,0);
   leds[i].fadeLightBy(brightness);
  }
  FastLED.show();
  brightness = brightness + fadeAmount;
  // reverse the direction of the fading at the ends of the fade:
  if(brightness == 0 || brightness == 255)
  {
    fadeAmount = -fadeAmount ;
  }
  delay(20);
}

It is almost certainly a power issue. The Adafruit page about one of those types of Neopixels says:

  Don't forget, with 256 LEDs, you could use over 15A of current if you turn on all the LEDs on to white (which we really do not recommend because we don't think the flex PCB can handle that much current). Try to keep the current draw at under 5A ...

Increasing the brightness increases the current drawn. Do you have a heavy-duty power supply? Are the connecting leads sufficient for (say) 8 amps of current?

New information based on comments made

Based on comments by Lorenz I now think it is more likely to be that they are overheating.

  I have the strip embedded in a picture frame with epoxy resin over it.

That makes it difficult for the ICs to cool down, and LEDs generate heat. If you search for "neopixels heat" you find quite a few matches. Some suggestions made are to use a heat sink or a fan. If this isn't practical for you, then running at a lower PWM rate (ie. not as bright) and not as saturated colour, could help keep the heat down.

You don't want to "cook" one of the early pixels, because each one has to pass the data on to the next one in sequence, so if you lose an early one, you lose everything after it, particularly if you can't get at it to replace one.

Postscript regarding heat

I have been testing a NeoPixel with a temperature sensor. Displaying full white (255/255/255) it has reached about 44°C. So clearly it warms up. However this is in the open air with just some sticky-tape holding the sensor onto the LED. According to the spec the chip can operate at up to 80°C, so this is within range.

However if the whole thing was sealed in epoxy, then the heat being generated would have much less chance of escaping into the ambient air, and thus would be likely to get a lot hotter.


Are all the pins on Arduino shields available for use? Basically, if I put a shield on my Arduino (mine is Uno, but I'm asking generally), can I freely use all the pins that are there on the shield?

I have an Ethernet shield and almost all of the pins that the original Uno has, are available on the Ethernet too.

The best results that I could get from googling are this and this which describe that if a shield uses a certain pin, putting another shield that uses the same pin causes conflict.

But what about using them myself? Can I use all the pins on a shield as Input/Output?

If some pins are unusable, then why are they available on the board? For example why doesn't the Ethernet have pins 10-13 blocked so you can't put any jumper wires in them?

Additional info:

There was also this article which didn't seem very credible to me.
Also I've tried using pins 10-13 to light an LED while the Ethernet was busy transferring data. The result was the LED connected to pin 10 was very dim, 11 was less dim and so on. So my guess is yes, they are unavailable. But the fact that this was so rarely mentioned on the internet and that the pins aren't physically blocked made me doubtful.

Short answer: NO.

Each shield adds some feature to the base Arduino Uno board and to do that it's more than probably going to use some of the PINs.
I say more than probably because Arduino do have support for certain protocols which can share the same pins (I2C and OneWire just from the top of my mind), but they are not the most commonly used approaches for shields.

The only reason the shields expose the same set of pins is for stackability, but not every shield is compatible with any other: it depends on the used PINs.

Some shields provide some level of configuration, usually via jumpers, in order to make them usable in more contexts they would usually be.

Documentation regarding the pins used by each shield is generally available along with the shield, but if you buy cheap clones it's no surprise you might have difficulties finding documentation...

The article you were pointing is somewhat creditable because most of what the author says is actually true and real, including the risk of short circuits.

As an example, the test you run with LEDs connected to the Arduino SPI interface (pins from 10 to 13 are used by SPI) could have damaged your board if you didn't use current limiting resistors.


This error is shown continuosly after first time it compiles successfully I got this error:

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

Multiple libraries were found for "LiquidCrystal.h"  Used: C:\Program
Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal
Not used:
C:\Users\siddh\OneDrive\Documents\Arduino\libraries\libraries readlink
C:\Users\siddh\OneDrive\Documents\Arduino\libraries\SimpleDHT\SimpleDHT.cpp:
The system cannot find the file specified. Error compiling for board
Arduino/Genuino Uno.

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

This is the code i use:

//We'll start by adding our libraries

 #include <LiquidCrystal.h>

 #include <SimpleDHT.h>

//Declaring digital pin no 6 as the dht11 data pin

int pinDHT11 = 6;
SimpleDHT11 dht11;

//Declaring the lcd pins

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
// Don't forget to choose 9600 at the port screen

  Serial.begin(9600);

//Telling our lcd to start up

  lcd.begin(16, 2);

}

void loop() {

  //These serial codes are for getting readings on the port screen aswell as the LCD display, since they'll offer us a more detailed interface

  Serial.println("=================================");
  Serial.println("DHT11 readings...");
  delay(2000);

  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  //This bit will tell our Arduino what to do if there is some sort of an error at getting readings from our sensor
  if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("No reading , err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("temp: ");
  Serial.print((int)temperature); Serial.print(" Celcius, ");
  Serial.print("humidity:");
  Serial.print((int)humidity); Serial.println(" %");

  //Telling our lcd to refresh itself every 0.75 seconds
  lcd.clear();

 //Choosing the first line and row

 lcd.setCursor(0,0);

//Typing Temp: to the first line starting from the first row
  lcd.print("Temp: ");

//Typing the temperature readings after "Temp: "
  lcd.print((int)temperature);

//Choosing the second line and first row
  lcd.setCursor(0,1);

//Typing Humidity(%): to the second line starting from the first row
  lcd.print("Humidity(%): ");

//Typing the humidity readings after "Humidity(%): "
  lcd.print((int)humidity);

  delay(750);
}

There is a bug that causes this error when you use the Arduino IDE with files located under OneDrive.

The simplest solution is to move any files that will be used with the Arduino IDE out of OneDrive to any other convenient location on your computer. It looks like you have your sketchbook folder located in the OneDrive so you will want to change that via the Arduino IDE's File > Preferences > Sketchbook location. The Arduino IDE does not automatically move the files from the previous sketchbook folder to the new folder so you will need to either move any files to the new sketchbook folder or else reinstall them.

There are some possible workarounds if you want to to continue using the Arduino IDE with OneDrive listed in the issue report:
https://github.com/arduino/arduino-builder/issues/254


Atmel Studio and Arduino IDE compiles the same code different Before going in details I need to say I am trying to program Arduino Nano board with atmega328p.
Here is my code in Atmel Studio;

#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;

ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}

int main(void)
{
    //DDRB |= (1 << PORTB3);
    //DDRD |= (1 << PORTD3);

    DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
        while(1)
    {

    }
    return 0;
}

And here is the code in Arduino IDE;

#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;
ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}
void setup() {
 DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
}

void loop() {
           // wait for a second
}

As you can see these codes are exactly the same (except the setup-loop format)
Now I am using exact same parameters for AVRdude;

-CF:\arduino-1.0.6\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P\.\COM9 -b57600 -D -Uflash:w: and following the hex file that is created after compile. But when I examine the verbose output of avrdude.exe they are different.

Arduino program works but the program uploaded using Atmel Studio does not. For more information everything about avrdude and parameters are working and it uploads and doesnt give any errors.

I chose atmega328p in Atmel Studio which is correct because I am using arduino nano board.

I found the solution (or what the problem is). Avrdude not only requires MCU model but also programmer parameter. If you are using any of Arduino based boards you need to add -c programmer id do avrdude input parameters.


Using Browser window to display sensor values in realtime The title pretty much says it all:

What would be the most obvious way to setup the Arduino (shields?), the Sketch (libraries?) and PC (webserver, ajax, plain html?) so that I get the following system working:

I open some page in a browser. The page has some labels/fields/values;
I power up Arduino, which is connected to some sensors (or even potentiometers);
The sensor values display keep being constantly updated in the page, with a sensible refresh rate (the fastest as possible, as to control some browser-based game for example);

The fundamental idea here is to use the Browser, and not some other GUI toolkit, or Processing, or the command line.

The most obvious way? Not what is the best way? It is a subjective question. The most obvious way would be to do it in a way you know how to. I am sure there are at least 20 ways to do this.

The way I know, and that I would do it is write a PC service that establishes serial communications with the Arduino, transfers data using JSON, and presents a web server I could connect TCP to.  Knowing C# and using existing code I have, it would take less than 15 minutes.


How does use an arduino like a A/D converter for convert 3 analogue signal from 3 poteciometer to a raspberry? I am developing a control system in my raspberry, but i have the problem that it doesn't have any analogue port, so if i use an arduino to convert de signal from analogue to digital and after send this signal into a I/o digital port from anduino to raspberry, thas is posible?

my plan was receive the analog signal in arduino and transforms here in a digital signal and after send it by Digital port to rasberry

It is not clear what you mean by “digital port”. The simplest mean to
communicate from the Arduino to the Raspberry is to use the Arduino's
serial port, which gets into the Raspberry Pi through USB. Just like you
would do if you had a PC instead of the Raspberry:

/*
 * Continuously report the analog readings on pins A0 through A2.
 */

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

void loop() {
    Serial.print("0 "); Serial.println(analogRead(A0));
    Serial.print("1 "); Serial.println(analogRead(A1));
    Serial.print("2 "); Serial.println(analogRead(A2));
}

This program will continuously output a text stream like this:

0 145
1 220
2 865
0 142
1 223
...

where the first column is the analog channel number and the second
column is the ADC value. How you handle this stream on the Raspberry
side is up to you.


Writing Libraries that use libraries that are being used in the sketch I know the title is a little obtuse, let me try to explain:
I am trying to create a library of simple functions for use with my TFT Panel.

The Panel has an include file (#include "SSD1306Wire.h")

I have a sketch and I have the above #include file referenced in the sketch
I also want to use my library tftHelper.h but that library needs to reference SSD1306Wire.h as well to get the helper functions to work.

Is there a way to reference SSD1306Wire.h one time and be able to use the reference in the functions in my helper library?

I guess, more importantly, what is the proper way to handle a situation like this?

The proper way to handle this is to have an #include guard in the header file to prevent the content from being included more than once.

In your header file filename.h you would add something like this:

#ifndef _FILENAME_H_
#define _FILENAME_H_

// Your header code here

#endif /* _FILENAME_H_ */

The #ifndef block will prevent the code from being included more than once. Best practice is to always put include guards in header files.


LCD displays bad character while counting rotation I have been practicing RPM and rotation counter in arduino using infrared optocoupler. I try to implement number of rotation for drill machine but whenever drill starts to rotate, LCD prints bad characters instead of displaying rotation.
Here is my code:

#include<LiquidCrystal.h>

 LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);
             int SensorPin=      13;

             int Counter = 0;
void setup() {
  lcd.begin(16,2);
  pinMode(SensorPin,INPUT);
    lcd.setCursor(0,0);

}

void loop() {

           lcd .setCursor(0,0);

          if(digitalRead(SensorPin))
  {
    Counter = Counter+1;
    while(digitalRead(SensorPin));

  }
  lcd.setCursor(0,1);
     lcd.print(Counter);
  // put your main code here, to run repeatedly:

}

Here is my lcd at initial step:

When I start my drill, LCD changes to this:

I suspect you get electrical noise on the leads from the optocoupler. A few test to help find cause:
1) Does the counter work if you rotate it by hand?
2) Does the LCD go funnny if you just have the optocoupler approximatly in the same position, but not count anything.


Reading names of files on sd card returning odd file names When trying to read the file names from an sd card some are being returned with a ~1 and cutting off the full file name.

Initializing SD card...initialization done.
TEST.TXT        402
UNTITL~1        0
HELLOT~1        49
DATALOG.TXT     562288
ALONGN~1        0
done!

Is there any way I get the full file name of each file?

The code for this is from here: https://www.arduino.cc/en/Tutorial/Listfiles

That's the way the FAT filesystem works.

On the page you link to there's a link to a page on SDCardNotes.

  FAT file systems have a limitation when it comes to naming conventions. You must use the 8.3 format, so that file names look like “NAME001.EXT”, where “NAME001” is an 8 character or fewer string, and “EXT” is a 3 character extension. People commonly use the extensions .TXT and .LOG. It is possible to have a shorter file name (for example, mydata.txt, or time.log), but you cannot use longer file names.

When you wrote the files to the file system you were on an OS that supports longer filenames. When filenames are too long there's an 8.3 name created automatically with chunks of characters removed and replaced with ~.


Removing and using programmed Atmega 328 of Arduino UNO on customised PCB I am a newbie. I would like to kno whether the original Atmega328 on Arduino Uno, programmed with my own sketch, can be removed from an Arduino Uno board and used  on my customised PCB?

Yes, it can. Your board will need to provide +5v and ground, a reset signal, and a crystal for the chip's programmed clock frequency (unless you reprogrammed it to use its internal clock). The power and clock signals will need filter capacitors. You can even re-program it on the board with an FTDI (USB-TTL Serial) cable.

There are lots do-it-yourself instructions to build an Arduino board, which is a good place to start, even if what you eventually want is a larger system board with an Arduino integrated into it. This is one I can vouch for; I built Mr. Alves' Version-1 as my only Uno-like board and have been using it for several years.


RFID-RC522 Cannot read from MIFARE Ultralight I tried many ways to get and print UID and other data from MIFARE Ultralight but it always ends with error. I am using RFID-RC522 reader with Arduino UNO and MFRC522 Library.
I can normally get and print the PICC type of chip, but that's the only thing that works.
That's how I have connected my RC522 reader:

This is my code:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9
#define SS_PIN 10

MFRC522 rfid(SS_PIN, RST_PIN);

unsigned long noSignal = 0;

bool lastState = true;
bool read = true;

void setup()
{
    pinMode(2, OUTPUT); //Red led
    pinMode(3, OUTPUT); //Green led

    Serial.begin(9600);
    SPI.begin();
    while (!Serial);

    rfid.PCD_Init();
    Serial.println("RFID ctecka byla uspesne spustena."); //Prints "RFID Reader succesfully started"
    Serial.println();

    changeLed(true);
}

void changeLed(bool red)
{
    digitalWrite(2, red);
    digitalWrite(3, !red);
}

void loop()
{
    if (millis() - noSignal >= 300)
    {
        changeLed(true);
        read = true;
    }

    bool state = !rfid.PICC_IsNewCardPresent() && !rfid.PICC_ReadCardSerial();

    if (state != lastState)
        if (state)
            noSignal = millis();
        else if (read)
        {
            read = false;

            changeLed(false);
            noSignal = millis();

            Serial.println("---------Cip detekovan----------"); //Prints "Chip detected"
            Serial.println();

            MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

            Serial.print("Znacka cipu: ");//Prints chip type
            Serial.println(rfid.PICC_GetTypeName(piccType));

            rfid.PICC_DumpToSerial(&rfid.uid); //Here is the error

            Serial.println();
            Serial.println("---------Cteni skoncilo----------");//prints "Read ended"
            Serial.println();

            rfid.PICC_HaltA();
            rfid.PCD_StopCrypto1();
        }

    lastState = state;
}

Serial monitor snapshot:

Maybe important thing is that when i call PCD_DumpVersionToSerial() i get:
Firmware Version: 0x12 = (unknown)

Somewere I read that my Arduino isn't compatibile with MIFARE Ultralight and I need MIFARE Classic cards. Is that true? Can I solve this problem by using other library or it's hardware problem? Thanks
Btw. Sorry for my english, it's not my native language.
EDIT:
I asked my friend, which have arduino too from same shop like me, if he can read MIFARE Ultralight cards. He said that it's working for him. So my problem will be probably on hardware side. We both have unoficial arduino from aliexpress.

In the first lines of code there are two lines that say:

#define RST_PIN 9
#define SS_PIN 10

They define the RESET pin to be on the D9 pin and the SDA on the D10 pin.
So you have an connection error try connecting like shown and you should be good to go.


[Arduino UNO]Receive Serial Data from multiple sources I have the following system:

As a master, I have an Arduino UNO Chip, more specifically an Atmel MEGA328P. The important thing is that this microcontroller has only one hardware Serial port, and that port is used to communicate with a WiFi adapter.

The problem I'm facing with is that I want to receive data from a Compass and a GPS modules. Booth send data via Serial protocol. The 328p Chip have only one serial which is busy!

I can't use SoftwareSerial as I don't want any delay on master board!
I can't also use Arduino Mega2560 which have 3 Serial ports as its sizes are too big.

So there are are my approaches:

Using MCP4725 I2C DAC for Compass, but what we do with GPS?
Using and intermediate Arduino UNO Chip?
On that chip I could use Software serial but how to transfer data to MASTER using only digital and analogic pins? Maybe using 10 pins to implement a parallel transfer?
Perhaps there is possible to convert Compass and GPS data to analogic then transfer to MASTER?

Anyway, what possibilities would I have to play around?

This answer summarizes the possibilities:

1) HardwareSerial is always best.  You are using that for WiFi.

2) AltSoftSerial is the best software serial library, but it requires pins 8 & 9.  Very efficient and non-blocking!  Strongly recommended for the GPS connection.

3) NeoSWSerial is next best, but it supports only 9600, 19200 and 38400.  It is non-blocking on receive, so it could be used for the GPS connection.

4) SoftwareSerial is the worst.  :P  Not suitable for the GPS connection, as you have discovered.

I'll also mention my GPS library, NeoGPS.  It is smaller and faster than other libraries, and there are examples that show how to make it run during the RX character interrupt, saving even more time.  It can also be configured for just the messages and fields that you actually use, saving RAM, program space and execution time.


How to make "IF "Temperature exceeds" logic to work in same arduino code I have the below code working from https://www.youtube.com/watch?v=Y30iEOxl1To - to receive temperature & humidity as an sms when i give a missed call to a specific number (sim on the gsm shield)

The above code is like on demand sms. I also want to alter this code so it can automatically send me another sms if the temperature exceeds a threshold.

Please help.

Below is the code...

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

void loop()
{
    float humidity, temperature;
    String smsText ="";
    if(temperature>29)
    {
        switch (call.CallStatus())
        {
            case CALL_NONE: // Nothing is happening
                break;

            case CALL_INCOM_VOICE : // Yes! Someone is calling us
                Serial.println("RECEIVING CALL");
                call.HangUp();
                delay(1000);
                humidity = dht.readHumidity();
                temperature = dht.readTemperature();
                delay(1000);
                smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
                smsText.toCharArray(sms_text,160);
                //Serial.println(smsText);
                sms.SendSMS("+91**********",sms_text);
                break;

            case CALL_COMM_LINE_BUSY:  // In this case the call would be established
                Serial.println("TALKING. Line busy.");
                break;
        }
        delay(1000);
    }
}

The code below will check if the temperature goes above 29 degrees. It also check whether the temperature was below 29 previously, to prevent it from sending an SMS every second, for as long as it's above 29 degrees C.

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

float previousTemperature = 0;
void loop()
{
    float humidity, temperature;
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();
    delay(1000);

    // check if temperature has raised to above 29 degrees
    if(temperature>29 && previousTemperature<=29)
    {
        sendSMS(temperature, humidity);
    }
    previousTemperature = temperature;

    // check for incomming call
    switch (call.CallStatus())
    {
        case CALL_NONE: // Nothing is happening
            break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us
            Serial.println("RECEIVING CALL");
            call.HangUp();
            delay(1000);
            sendSMS(temperature, humidity);
            break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established
            Serial.println("TALKING. Line busy.");
            break;
    }

    delay(1000);
}

void sendSMS(float temperature, float humidity)
{
    String smsText ="";
    smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
    smsText.toCharArray(sms_text,160);
    //Serial.println(smsText);
    sms.SendSMS("+91**********",sms_text);
}


How to use any module that has no library for arduino? I am 2 years old in this Arduino world.
I am currently working on a project where I am about to make use of a fingerprint sensor. Now my question is that could we be able to make use of a sensor that we usually find in our mobile phones with ATmega328p microcontroller chip. And what if that there were no libraries written for Arduino so that will make my life easier. And I wonder how these tech companies make use of any sensor they would like to use without any trouble while there is no existing textbook that taught these employees while pursuing a degree in CSE or ECE about how to write code for a particular sensor. Now I know that there are certain protocols like SPI, I2C, UART, etc. But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course? I always scratch my head while looking at the consumer electronics, and the IC's and Chips that they have on their PCB board were never found on google, And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language. I hope someone could help me understand how all this happens.

About the fingerprint sensors from mobile phones: You might find the answers to this question useful. They explain in detail, why it is not really worth the effort to try interfacing such a fingerprint sensor with Arduino.

  How to use any module that has no library for arduino?

You need to read the datasheet of the module. It should explain in detail, how the module is used. When you understood, how it works, (and understanding it is really really important) you can start implementing it in code, for example by writing your own library. A library is just a wrapper around the interfacing code for that module. If the module uses common used interfaces or is even a commonly used component, you can often stand on the shoulders of giants by making use of other libraries in your library (for example using the Wire library in a library for a specific I2C sensor). That makes it easier.

  But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course?

The engineers don't get taught to use specific controllers or ICs. They get taught the fundamental principles, including common interfaces like I2C, SPI, UART, I2S ... . In the end it all comes down to the datasheet of a component. It should explain all details, that are needed to use the component correctly, or at least reference to further documents. For example most microcontroller datasheets directly explain, how I2C is implemented in these microcontrollers. You can use that to implement I2C communication, even without a preexisting library. Yes, that can be a tedious and complex task, but it is totally possible. Keep in mind, that most Arduino libraries are not written by the manufacturer of the used component, but by third party people (sometimes the community, sometimes resellers like Adafruit, e.g.).

I would say "it is not rocket sience", but yes, it can be rather difficult to dig into the very detail of interfacing a component. Without considering myself an especially smart guy, I'm writing a library for multi-master I2C communication on Attiny's (without having any degree in that field). I could start with code from others, which made the entry easier. But it also involves much time, to dig into it, write the code and test it correctly. It is difficult, but it is possible.

  And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language.

Good manufacturers and resellers provide a datasheet in english for their products. That cannot be said for every product, that you can purchase. Writing documentation takes time and thus costs money. Chips directly from China (where most electronics is produced these days) might have less good or no documentation at all, though these chips are often way cheaper. As a hobbyist you should stick to the good documentated components, if you don't want to really dig into it.

  the IC's and Chips that they have on their PCB board were never found on google

PCB designs are only found in the internet, if they are published under some open source license (or if they were illegally leaked by someone). If a company doesn't want to publish it's product designs, that is totally ok.

About the components in consumer electronics: I think you refer to that the chips often don't have a googleable product number/marking to find a datasheet. That is because often these chips are custom chips, made maybe only for this company or even this specific product. Why would they want to publish a datasheet for it? They are not meant for public use for all. The design of components is often a good kept secret, that the companies are not willing to share, since it generates their revenue.

Hobbyists and small companies use publicly available, good and publicly documented parts to make their life and investment in the project easier. Big companies can easily hire people to design a custom chip, that will only contain the needed features. (With mass produced products you can save money this way, by not always needing to buy even the unused resources of a standard controller). Another reason to use a custom (maybe even a not programmable) chip is to keep the code in it secret.

All in all keep in mind, that the hobbyist world of Arduino and the world of consumer electronics like smart phones are rather different. Sure, they rely on the same principles, but the way, how things are done and created, is very different.


DHT11 sensor providing -999 outputs I'm new here, trying to learn Arduino by hacking, that is plugging stuff in, looking for code and then trying to understand it bit by bit so I can move on to bigger and better projects.

My issue is that I am getting a periodic readout of -999.0 from a 3 pin DHT11 temperature and humidity sensor in between actual readouts. I can't find anything online explaining this but maybe I haven't looked hard enough. Attached is a screenshot containing both the code and serial monitor readout. Mechanical engineering background, so no electronic knowledge but feel free to get techy with your response.

if the image doesn't load this is the code;

#include <dht.h>

dht DHT;

#define DHT11_PIN 7

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

void loop()
{
  int chk = DHT.read11(DHT11_PIN);
  constrain (DHT.temperature, -25, 70);
  constrain (DHT.humidity, 0, 90);

  if((DHT.temperature || DHT.humidity) > -25)
  {
  Serial.print("Temperature, Humidity = ");
  Serial.print(DHT.temperature);
  Serial.print(", ");
  Serial.println(DHT.humidity);
  delay(1000);
  }
}

Thanks in advance for help or direction to help.

-999 means that it didn't get a result from the DHT.  You need to filter them out - which you are attempting to do, but wrongly.

Your line of code:

if((DHT.temperature || DHT.humidity) > -25) {

is not doing what you thing it is.

If you start from the inner most brackets and "reduce", you get:

Is DHT.temperature or DHT.humidity?

That makes no real sense - except in C any number that isn't 0 is "true" and 0 is "false", so that really means:

Is DHT.temperature not 0 or DHT.humidity not 0?

And of course that will be "true" in 99.99999% of situations.  So insert that into the if again:

if (true > -25) {

Is true more than -25? Well, the reverse of what I stated above is also true: "true" is 1 and "false" is 0.  So is 1 greater than -25? Yes. It is.

Instead you should be testing each value separately:

if ((DHT.temperature > -25) && (DHT.humidity > -25)) {

Also your constraints are doing nothing.  constrain() doesn't modify (limit) the variable you pass to it. Instead it takes the value in that variable, constrains it, and returns the new constrained value to you for you to assign to a new variable.  So you should:

float temperature = constrain (DHT.temperature, -25, 70);

And then you can use the temperature variable instead of DHT.temperature, and you can guarantee that it will be between -25 and +70.


Can the atmega328 return remainder during integer division? When I write code like this:
int a = 7
int b = 2
int c = a/b
int r = a%b

Does the chip use the remainder while calculating c or does it redo the entire calculation?

If using optimization, the compiler is smart enough to recognize this.
Since your example is so short, it could be optimized away entirely.
To ensure that doesn't happen, the results in c and r have to be used in some way.
Also, if a and b could never change, the values of c and r would be calculated during compilation.
Therefore, I put the calculation in its own function.
From godbolt.com, using AVR-GCC 9.2.0:
#include<stdint.h>
#include<stdio.h>

uint8_t a = 0;
uint8_t b = 2;
uint8_t c = 0;
uint8_t r = 0;

void calculate() {
    c = a / b;
    r = a % b;
}

int main() {
    a = 7;
    b = 2;

    calculate();

    printf("%d %d", c, r);
}

compiles the calculate() function into
calculate():
        lds r24,a
        lds r22,b
        rcall __udivmodqi4
        sts c,r24
        sts r,r25
        ret

The results, stored in r24 and r25 respectively, are re-used from the same division operation.


From Arduino to a miniaturized circuit I have a project made with Arduino, and I want to replace it by a miniaturized circuit with just a microcontroller. Is there any tutorial that can guide me in doing this? Any reference is wellcome. Thank you!

You can use an Arduino on a breadboard to get you going. From the breadboard, you can then develop a circuit on a pre-made PCB like this:

Then to a custom PCB, if you so desire.


Send data to a pc localhost with ESP-01 wifi module i use a linux machine with a localhost php server installed. Wifi machine is connected to the ESP-01 module (access point mode) and i can send several datas to the Arduino via the ESP-01 set as:

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
  sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

The php server can send data by GET method and Arduino receives pin=11:

 http://192.168.4.1:80/?pin=11

But, now, i would like to send to the php server datas from the Arduino. I tried this configuration but in my sketch but, it returns, error.

sendData("AT+CIPSTART=0,'TCP','http://localhost',80\r\n",1000,DEBUG);

Serial monitor:

   ERROR
   AT+CIPSTART=0,'TCP','http://localhost/test_php',80

   Link type ERROR

So please, how can i send and receive data with my ESP-01 module?

"localhost" is a name associated with the loopback interface of your computer. That is, 127.0.0.1.

It is not the address of your computer on the network. The only computer that can talk to "localhost" is the computer itself.

Instead of "localhost" you must use the IP address of your computer (or a FQDN that resolves to the IP address of your computer).

And you cannot open a TCP connection to a URL.  You open a TCP connection to an IP or FQDN.

You really should learn the basics of IP networks before trying to write software for them.

Since your PC can communicate with the ESP8266 on 192.168.4.1 I assume that you are running the ESP8266 in SOFTAP mode and you have a WiFi interface connected to that access point. If so that WiFi interface will have a 192.168.4.x address assigned to it.  That is the address you must open with a TCP connection on port 80 to connect to your apache server.

For example:

sendData("AT+CIPSTART=0,'TCP','192.168.4.3',80\r\n",1000,DEBUG);

Then you can craft a suitable HTTP request to send the data.


Transistor as switch for signal and high current buzzer I'm a newbie in transistor switching.

I have PIR sensors with C and NC onboard. NC is 12 V signal that I need to switch transistor (bipolar?) to emit 3.3 V (collector connected to 3.3 V).

VCC equals 3.3 V. PIR is pin on ESP32.

Can you tell me if this circuit is okay or does it need additional edits?

Note: Q3, Q4 transistor number is random, if you can offer me suitable transistor I would be glad.

Next circuit:

ESP32 pin "ALARM" is connected to transistor (MOSFET N channel) base.

ALARM as device is connected to 12 V, required 300 mA to run and I need transistor to switch circuit. Relay is awful.

Is this circuit correct?
Do I need any additional edits?
Can you suggest me suitable transistor?
I don't know much about MOSFET shortcuts.

Third circuit I need is same as this but instead 12 V I need to switch 5 V.

I guess just to change MOSFET transistor?
Or use same as for 12 V?

Combined circuit schematic:

I'll try to answer your post with "just words" and we will see how it goes. If it is not clear to you, i will post small schematic.

I do not recommend the first schematic that you posted.
You will likely reverse bias the BE (base emitter) junction with 12v. Most bipolar transistors have a maximum reverse BE bias of 5 v.

I do recommend using bipolar so that you dont have to study, understand the range of turn on voltages for a MOS transistor.

The bipolar is always 0.6v
and a Darlington bipolar is twice that.

Also, i dont know why you have the 100nF caps in there. They will guarantee a surge, everytime you turn the circuit on and hence put noise on your supply bus.

When I design a driver for a similar application i frequently use a TIP100 (https://www.digikey.com/product-detail/en/on-semiconductor/TIP100G/TIP100GOS-ND/1485300)

So use the basic design of your second circuit but use the TIP100.

ALWAYS have a resistor (10k ohms or so) to keep the leakage current (Icbo) from turning on the transistor when you dont want it on !

I would put all the loads into the Collector circuit in your second schematic, rather than make the uP drive your LED.

If your load is at all inductive (a coil) then ALWAYS put a reverse-biased diode across the load to catch any inductive kick back.

If this is all Greek to you, then just say so and I will draw a simple universal circuit that will work for 3.3v drive or 12v drive.

All the Best to you.
RP


Fade in UV lights connected to mains I have a PIR motion sensor and would like some ultra bright UV led lights to fade in when this is triggered. It is one unit, consisting of 225 led lights connected to 240v mains (Australia). I bought a relay for the basic on/off function but was wondering if fading on and off can be done relatively easily - this is my first arduino project. I would value any suggestions.

Most LED lights can't be dimmed from the mains supply.

In order to dim LEDs you have 2 choices: Limit the current through each LED or series string of LEDs, or pulse them very rapidly with a varying ratio of on/off times (known as a variable "duty cycle")

It's usually easiest to pulse them. To do that you need to be able to control the flow of DC to the LED array. If you were to take apart your IR array you would very likely find an AC to DC power supply that then feeds the LEDs through current limiting resistors.

If you can figure out the voltage and current that comes out of the DC power supply, you can select a power transistor (almost certainly a logic level power MOSFET) to wire in as an electronic switch that enables you to pulse the power to the LEDs using a logic signal from your Arduino.

This is actually a lot simpler than it sounds. You would cut 1 wire inside your LED array, solder in a single transistor to the 2 ends of the cut wire, and run the third wire from the transistor out to your Arduino.

Arduinos have several I/O lines that can be configured for PWM (Pulse Width Modulation) which is designed for this very purpose. You'd connect a PWM line to the gate of a logic level power MOSFET, and then send it a signal from 0 to 255, which would effectively dim the LED array in 255 brightness steps.

There are beginner sample projects that let you dim single visible light LEDs using this very approach. (For a single LED you don't need a transistor though, so they are really easy to wire up. All you need is a current limiting resistor.) I suggest you find and build one of those projects to get a feel for how (and how well) it works.


Detect power interruption on NodeMCU Im using a 5v 1A power supply and connected to VIN pin on the NodeMCU. I also use 18650 battery to keep NodeMCU running in case the power supply shuts off due to power interruption.

I'm planning to use the 5V from power supply, convert it to 3.3V with voltage divider and connect it to the gpio to detect power interruption.

Is it possible? Can the NodeMCU handle the current from the power supply?

Yes, you can.  You need to convert the 5V down to 3.3V with a voltage divider. You also need to consider how you are going to operate the ESP8266 when there is no power.


Why atmega168/328p starts to reset? First we set fuse bits:

avrdude -c usbasp -p atmega328p -U lfuse:w:0xFF:m -U hfuse:w:0xDF:m -U efuse:w:0x07:m # same for atmega168

In the following examples we use the following commands to compile and burn all the programs:

avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

Let us burn the following program:

#define F_CPU 16000000UL
#include <avr/io.h>
void main (void) {
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while (1);
}

It makes the led to be on constantly. And it stays so for infinite period of time.

Then we burn the following program:

#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data = 0;
void main(void) {
  // Initialize USART:
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE; // set the speed (Higher bit)
  UBRR0L = UBRRL_VALUE; // set the speed (Lower bit)
  UCSR0B |= (1<<RXEN0); // enable receiver
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00); // set mode (8N1)
  DDRB |= (1<<PB5); // enable output on pin PB5 (default led on arduino)
  while(1) {
    while(!(UCSR0A&(1<<RXC0))); // wait until a byte is received
    data = UDR0; // read it
    if (data) PORTB |= (1<<PB5); // set the led on
  }
}

Then we open a terminal (9600,8N1) and press several keys, until the led turns off.
Now we burn the first program again and the led is constantly blinking. The reason for this is that watchdog times gets started when we press the keys in terminal. But why and when WDT gets started? How to make so that it will not start?

It should be noted also that we can disable the blinking only with complete poweroff/poweron - only after that the led lights constantly without blinking, as necessary.

This happens on atmega168 and atmega328p, 100% reproducible.

avr-gcc version 4.8.1 avrdude version 6.1

NOTE: bootloader is not used at all.

WDT settings will remain unchanged, even after a reset. So the timer will keep running and therefore keep resetting the device. Which causes the blinking. Power cycling will clear the WDT settings.

PS I didn't read the code, as uncommented register writes are pretty much unreadable.


Leonardo: disable TX- and RX-LED I have the (more or less) Leonardo-compatible board Olimexino-32u4. Both, the TX- and RX-LED are permanently on. To reduce power-consumption, I want to disable them by software. What is the reliable way to do it?

Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.

Compare:
http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf

The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):

In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:

olimexino32u4.name=Olimexino-32U4
olimexino32u4.upload.protocol=avr109
olimexino32u4.upload.maximum_size=28672
olimexino32u4.upload.speed=57600
olimexino32u4.upload.disable_flushing=true
olimexino32u4.bootloader.low_fuses=0xff
olimexino32u4.bootloader.high_fuses=0xd8
olimexino32u4.bootloader.extended_fuses=0xcb
olimexino32u4.bootloader.path=caterina
olimexino32u4.bootloader.file=Caterina-Leonardo.hex
olimexino32u4.bootloader.unlock_bits=0x3F
olimexino32u4.bootloader.lock_bits=0x2F
olimexino32u4.build.mcu=atmega32u4
olimexino32u4.build.f_cpu=16000000L
olimexino32u4.build.vid=0x2341
olimexino32u4.build.pid=0x8036
olimexino32u4.build.core=arduino:arduino
olimexino32u4.build.variant=olimexino32u4

Create another folder 'variants' inside the olimexino folder.
Inside that, create the folder 'olimexino32u4'.
Now copy 'arduino/hardware/arduino/variants/leonardo/pins_arduino.h' to that folder
Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins_arduino.h'.
Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:

#define TX_RX_LED_INIT  DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED1          PORTD |= (1<<5)
#define TXLED0          PORTD &= ~(1<<5)
#define RXLED1          PORTB |= (1<<0)
#define RXLED0          PORTB &= ~(1<<0)

I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools->Board menu.


Wanted to control 2 servos with serial read I want to use 2nd servo only when 1st is in up state by asking user whether he wants to fire or not.(code in bold is not working )

#include <Servo.h>

    Servo myservo;
    Servo trigervo;
    int pos = 0;
    int u = 0, p = 0, t = 0;
    int incomingByte = 0; // for incoming serial data

    void setup() {
      Serial.begin(9600);
      myservo.attach(9);
      trigervo.attach(10);
      pinMode(13, OUTPUT);
      myservo.write(0);
    }

    void loop() {
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();
        Serial.print("I received: ");
        if (incomingByte == 111 && u == 0) {
          for (pos = 0; pos <= 80; pos += 1) {
            myservo.write(pos);
            delay(5); //
            digitalWrite(13, HIGH);
          }
          u = 1;
          p = 0;
          Serial.println(incomingByte, DEC);
          Serial.print("Want to Shoot? \n");
          Serial.print("1\n");
          ***t = Serial.read(); // from here
          if (t == 107) {
            Serial.print("2\n");
            trigervo.write(60);
            trigervo.write(0);
          } // to here, it is not working***
        } else if (incomingByte == 102 && p == 0) {

          for (pos = 100; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(7);
            digitalWrite(13, HIGH);
          }
          u = 0;
          p = 1;
          Serial.println(incomingByte, DEC);
        }
        Serial.println(incomingByte, DEC);

      }
    }

Without knowing, what exactly you want it to do (since you didn't tell us), I see 2 problems in your code:

The code around the line marked with "from here" will ask the user over Serial, if he wants to shoot, but directly after it, it will read a value, without waiting for the user to input something. Serial.read() will not wait for data to arrive, it will just return -1 if nothing is in the buffer. You have to check, if there is actually something in the buffer with Serial.available() and only proceed, if there is actually data to read.
In the following if-statement, you first write the value 60 to the servo and directly after it, without any delay, the value 0. The servo doesn't have enough time to get to 60 - or to even start to move - before you tell him to go to 0. The servo needs time for movements.

Apart from the specific problems with your code, I would use a finite state machine (FSM), to implement it, instead. You declare a global state variable, which represents the possible states, in which your machine can be. If I assume some type of gun/shooting device, these states could be ASK_USER_TO_POSITION_GUN' and 'ASK_USER_TO_SHOOT'. In each state you check the Serial interface (first withSerial.available()then reading withSerial.read()` if it returns something greater than 0) and based on that input you first take the appropriate action and then do the state transition, by changing the state variable.

As example of the general structure:

int state = 0;

void loop(){
    switch(state){
        case 0:
            if(Serial.available()>0){
                int input = Serial.read();
                //take appropriate action
                state = 1; //do state transistion
            }
            break;
        case 1:
            if(Serial.available()>0){
                int input = Serial.read();
                //take appropriate action
                state = 0; //do state transition
            break;
    }
}

Depending on the exact actions to do, you can also tune this, by reading Serial outside of the switch statement and in the case statement only check the input variable. In this case reset the input variable after every interaction.

EDIT: For giving a better explanation about finite state machines, I've drawn a graphical representation of the states. Mostly it is way easier to code, when you first have drawn such a graph to visualize the codes functionality. Note, that this is the logic from your code. You may want it to work another way, but this is beyond the scope and only for understanding. Also note the different numbers of the states than I used above, which I only change, because I needed more states.

See first this graph:

We begin in state 0, where we are waiting for user input through serial. If we go some input, we make a decision: If the value is 111, we will transition to the next state (state 1) to position the gun, else we will wait again for more input. In stage 1, we are positioning the gun and go directly to state 2. There we are again waiting for user input. If we received something, we will again make a decision: On the value 107 we will do the transition to state 3 to shoot, else we will go to state 0, to ask again for positioning, like we did before. In state 3 we are shooting and directly go to state 0 again. This is rather strict division into states.

Since in state 1 and 3 we are only doing a short action and then going directly to another state, we might cut those states away, implementing the corresponding code in the transition from state 0 to 2 and vice versa. This is the logic from my FSM code example above (action together with transition). The graph would look like this:

Which version you should implement depends on other factors. If you are OK with the action code to be blocking, you can implement version 2, since it has less states. If you want to write the action in a non-blocking style, you might find version 1 easier to implement.


teensyduino with teensy LC: cannot include multiple files in sketch I'm trying to get a rather large sketch working with a teensy LC.  I'd like to break it into headers and C files, but the multi-file sketch fails to compile.  When I put everything into a single, monolithic sketch, it runs fine.  I've #included the h files where they are needed, using single quotes, and have confirmed that my h files are in the same folder as my sketch.  Is there an additional step to go through specific to teensy?  I've managed to do this tons of times using a standard arduino.

Here is a basic sketch:

This is the main sketch file:

   #include "tst.h"
void setup() {
  // put your setup code here, to run once:

}

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

This is tst.h

void doNothing();

This is tst.c

#include "tst.h"
void doNothing()
{
  int i = 0;
}

I get the  error "undefined reference to doNothing() in function loop"

I get the error "undefined reference to doNothing() in function loop"

The C++ compiler cannot find doNothing(). This is mainly due to the incomplete header file and mix of C and C++.

Two things are needed to avoid this type of problem; 1) protect the file from multiple includes (in the same compile), 2) make the function visible to the C++ compiler as a C function (without name mangling).

tst.h:

#ifndef TST_H
#define TST_H

#ifdef __cplusplus
extern "C"{
#endif

void doNothing();

#ifdef __cplusplus
} // extern "C"
#endif
#endif

Cheers!


Anyone have example code for ESP32 as media controller for Android/iPhone Media Apps There's actually another post with this very same topic but no answers on that post. Back in January of 2020, the last commenter said he had sample code and then he went dark without posting the actually code. The thread is here:
Want to create bluetooth audio control (volume up/down, play, pause, etc.) for smartphone
My problem is the exactly the same as the original post. Amazon and Aliexpress have literally hundreds of these "media buttons" that you can buy and pair via bluetooth with your Android or iOS. You can then playback media on iOS/Android and the "media buttons" can control the playback. Pretty common controls are volume up/down, next, previous, play and pause.
I've written a lot of Arduino code for Nano, Uno and even MKR. I've written a bunch of ESP8266 and ESP32 code as well. Usually when I try and learn something, a few google searches will find an example that I can figure out. For this, I've been able to find nothing.
Every tutorial or sample code is about how to send commands to the ESP32 via Bluetooth or pair an ESP32 with a bluetooth joystick, etc. None of those examples help me understand what's needed for an ESP32 to pair with my Android and act as media buttons, sending volume up, down and play/pause commands via bluetooth.
Can anyone help with example code for doing this with an ESP32? (by the way, this forum would not let me comment on the original post or I would have. it said I didn't have enough karma points or something)

Well after I posted this question, I kept googling. Literally hours of googling at this point. Then I stumbled across this example:
https://github.com/T-vK/ESP32-BLE-Keyboard
I wrote that sketch to my ESP32, paired my iPhone and it immediately starting controlling music playback on my phone. After looking at the code, it's so simple that I'm embarrassed I couldn't figure this out on my own. In case the link goes dead, I'll paste the code here:

#include

BleKeyboard bleKeyboard;

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");
  bleKeyboard.begin();
}

void loop() {
  if(bleKeyboard.isConnected()) {
    Serial.println("Sending 'Hello world'...");
    bleKeyboard.print("Hello world");

    delay(1000);

    Serial.println("Sending Enter key...");
    bleKeyboard.write(KEY_RETURN);

    delay(1000);

    Serial.println("Sending Play/Pause media key...");
    bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE);

    delay(1000);

    Serial.println("Sending Ctrl+Alt+Delete...");
    bleKeyboard.press(KEY_LEFT_CTRL);
    bleKeyboard.press(KEY_LEFT_ALT);
    bleKeyboard.press(KEY_DELETE);
    delay(100);
    bleKeyboard.releaseAll();

  }
  Serial.println("Waiting 5 seconds...");
  delay(5000);
}


How to set the sampling frequency in Arduino without using a delay I am reading an ECG signal using a single lead heart rate monitor. What I know is that when I use delay(15) it means that I am getting 66.67 readings in a second which corresponds to the sampling frequency. I want to set the sampling frequency to 250. This can be done by introducing delay(4).

What I really need is to set the sampling frequency to 250 Hz without introducing a delay in the code because I am acquiring ECG data in real time. Also, I am sending the data to python for processing and the delay will affect the sampling frequency in the time domain analysis.

any detailed solution or code ??

PS. I am using Arduino UNO

Code:

#define SERIAL_BUFFER_SIZE 8192
#include <SoftwareSerial.h>
unsigned long Time;
void setup() {

  // initialize the serial communication:

  pinMode(10, INPUT); // Setup for leads off detection LO +
  pinMode(11, INPUT); // Setup for leads off detection LO -
  Serial.println("CLEARDATA"); //clears up

  Serial.println("RESETTIMER"); //resets timer to 0

  Serial.begin(115200);

}

void loop() {
  if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
   Serial.println('!');
  //  continue;
  }
  else{
   /*
     // send the value of analog input 0:
     int idata = analogRead(A0);
  //  float data = (idata*3.3)/1023;
      Serial.println(idata);
*/
  int sensorValue = analogRead(A0);
  float voltage = sensorValue * (3.3/1023.0);
  Serial.println(voltage);
  }
  //Wait for a bit
    delay(4);
}

Use the concept of blink without delay.

Instead of using delay() to set the timeout you use a timestamp and check micros() against that to see whether your interval has passed:

const unsigned long READ_PERIOD = 4000;  // 4000 us: 250 Hz

void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        if (digitalRead(10) == 1 || digitalRead(11) == 1)
            Serial.println('!');
        else
            Serial.println(analogRead(A0) * (3.3/1024));
    }
}


SoftwareSerial returns garbage when powered externally I'm currently working on a project with the ESP8266 and Arduino Nano, and when I power the device via USB they talk to each other via SoftwareSerial just fine. I use the Arduino IDE Serial Monitor to monitor this communication. But when I power it with a 15 V wall wart to Vin it returns mostly garbage, again I can tell this with the Arduino IDE Serial Monitor (I know I shouldn't connect two power supplies at a time). When powered over 5 V USB everything is great. Why would I have a problem only when connected to an external power supply?

If you check the specifications they stat 12VDC is the max.  Your on board regulator is probably very hot and either shutting down or allowing the voltage to sag.  You can get a 9V wall Wart for under $5.  the 9V will keep the on-board regulator much cooler and add reliability.


Arduino Driving Pump via MOSFET I want to turn on a pump that is running 12V and draws a current of max 1.7A with my Arduino Uno.

To do this, I bought the RFP30N06LE MOSFET and followed these instructions to wire it all up.

I connected the red wire from the pump to VIN of the Arduino and plugged a 12V 2A power brick into the Arduino. However, when I put the output pin to HIGH, the pump only pumps weakly and the MOSFET gets very hot.

When I connect the pump straight to VIN and GND, it works as expected, so the Arduino is able to provide the required current. I'm thinking that there is something to the MOSFET that I am not understanding correctly. I measured VGS at 4.5V, so the MOSFET should be able to handle the current. Is there anything I am missing?

This is the wiring:

This is the (very simple) sketch I'm using to test it all:

#define PIN_PUMP_ON 7

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

void loop() {
  digitalWrite(PIN_PUMP_ON, HIGH);
  delay(1000);
}

Vin is only rated to supply at most 1A due to the reverse polarity protection diode in series from the barrel jack to the Vin pin.  You try and draw 1.7A thru that and you may smoke it.
The Vin header is also only rated for 1A.

Connect the motor to the supply directly. The Arduino Gnd must also connect to the supply.
R2 limits Arduino IO pin current to a safe level. R1 keeps the MOSFET off while the Arduino boots up. Diode dissipates motor generated current when the MOSFET goes from On to Off. The RFP30N06LE looks to be rated for full turn on with Vgs of 5V, and Rds of 47milliohm, that part should be ok to use.

Powering the Arduino from the same source as the motor may cause issues. If you can power the Arduino from USB or a seperate battery pack and not the same 12V that powers the motor, that will probably yield better results, especially if the 12V droops at all under heavy loads from the motor. That could cause Arduino resets.

simulate this circuit – Schematic created using CircuitLab


How can I program a ATmega328 au tqfp32 ( SMD ) chip? I have some experience with the Arduino UNO , Nano , mega etc .. But today I want to upgrade my skills and knowledge to next level . So I am about to design my own PCB for ATmega328 au ( SMD ) but this time I want to use a tqfp32 programmer to get the job done .. I have searched the internet and I have found that people use Universal programmers ( ISP ) such as Top2013 universal programmer or TL86ii but I have no idea how to use them and I don't even know what  software that the youtubers are using ... They are actually uploading some *.hex files it seems I am not sure but they aren't using Arduino IDE . According to my knowledge they are using a tqfp32 to dip28 programming module ( I have attached a pic ) . And then the Module is mounted on top of the ISP . Then they have uploaded code using some unknown software. And few people are using USBasp , can any explain me the scenario and what they have done ..  https://youtu.be/GFyr9tVEHzQ
The link is a reference video .

To upload compiled code (.hex) to a bare atmega which doesn't have a bootloader installed you can use ISP. As this stands for in-system-programming you don't have to flash the chip before assembly, but you can flash it in-system, so when already soldered onto your pcb. There actually is no need for those adapters like shown in your first picture, which often are a bit expensive. Also, both pictures stand in contrast to the idea of ISP, they seem to show firmware upload via serial connection, which as far as I know only works with a bootloader already installed...
ISP is based on SPI (serial peripheral interface) and you need to break out the corresponding pins to fit this connector. This obviously has the advantage of being able to update a firmware afterwards without the need of a bootloader.

Atmel provides a tool for flashing firmware via ISP which is called avrdude (tutorial) or you can use the atmel studio. To compile your code, you can use avr-gcc.


Send newline through serial monitor I know I can send a newline using the option in the bottom right:

But why doesnt it work to use the option 'No line ending', and send a '\n' or '\r\n' after the text using the arduino serial monitor?

The backslash escape encoding for special characters is a feature of double quotes in some programming languages, shells, and other parsers.  It is not normally a feature of live text input - an "end user" human typing a backslash is assumed to mean it literally.

"Live" input of a carriage return or newline is more traditionally done with the return/enter key, or with the corresponding control codes - CTRL-J for newline and/or CTRL-M for return.  I don't know that the Arduino IDE's Serial Monitor supports either of these, at least once you select "no line ending"


Delay function not working as intended int j;
void setup()
{
   for(j=2 ; j<=9 ; j++)
      pinMode( j , OUTPUT );
   digitalWrite( 2, HIGH );
}
void one()
{
   digitalWrite( 3, HIGH );
   digitalWrite( 4, HIGH );
}
void all_off()
{
   for(j=3 ; j<9 ; j++)
      digitalWrite( j,LOW);
}
void loop()
{
   one();
   delay(1000);
   all_off();
   delay(3000);
}

Trying to do a blinking "1" (stopped at 1 before continuing other numbers because of this problem ) with a single-digit 7 segment display. Where pin 2 is comnected to the com pins of the display.

Expected: display 1 for a second , then turn off for 3 seconds.

Reality: display1 for 3 seconds then turn off for a second.

Tried putting the delay functions in the one and all_off functions but no use.

Tried changing the delay(1000) to delay(7000) , the off time increased.

Tried changing the delay(3000) to delay(1000) , the turn on time changed to 1 second.

The code should work in order, should it not?  What is happening? How to fix it?

Without circuit information and part numbers, one can't say for sure what the problem is.  However, the symptoms suggest that your LEDs turn on when you pull some pin low, rather than when it goes high.  This can happen if, for example, the LED anodes are wired (through a resistor) to V+ and the cathodes are connected to a drive pin.  If, however, the cathodes are connected to  ground through a transistor, positive-logic should apply, rather than negative logic.


Cannot program two arduinos at the same time because they both use the same COM port I am not able to program my second arduino because they both use the same com port. In other words this picture says it all:

In order to upload my sketch I have to disconnect one arduino. How can I tell windows to use a different COM port?
It will be nice if I do not have to disconnect one arduino evey time I want to upload a sketch. I already restarted my computer and I get the same problem.

I did not knew I could change the port on windows. This is how I did it thanks to @Majenko's comment.


Strange behavior on 74HC595 Shift Register IC when its GND pin is used I was following a tutorial similar to this:
https://www.arduino.cc/en/Tutorial/ShiftOut

That is, an array of 8 LEDs that lit up accordingly to the binary representation of a number, which was given in a loop from 0 to 255.

The problem is that when invoked shiftOut() over certain numbers (such as 5, 9 or 13), the LEDs didn't lit as expected.

I even tried replacing the IC, but what finally solved this issue was to disconnect IC's pin 8 (GND) and let only pin 13 (OE) connected to Arduino's ground pin.

Does anyone know the reason this strange behavior happens on 595 IC?

Here's a video showing the circuit finally working (without IC's GND pin connected): https://www.youtube.com/watch?v=NGfpk-kjemo

Disconnecting the ground pin was not a solution.

It is hard to be certain from video but the resistor values are likely too small because I can't see any color on the bands.  They are 100?

Look closely at the driver data sheet.  It may say an output pin maximum current is +/-35 mA which would suggest that the 100 ohm resistor is okay.

For example, a red LED has a of around 1.6 V.  You are using Vcc=3.3, so a 100 ohm resistor limits the current to <17 mA ((3.3-1.6)/100).  The actual current will be a somewhat smaller as the Vf increases with current..

But you also stay within the maximum Icc and Ignd on the data sheet.  These limits are not necessarily 8 x 35 mA.  For example an NXP max Icc is 70 mA.  That means you cannot drive all the outputs at maximum current, just 2.  This is a logic chip, not a driver.

There is other hint that you should not using all the outputs at the max current spec in the section where the Voh and Vol are described.  The current at which the voltage is specified is 6 mA, which is the maximum you should use if all output are going to source or sink at the same time.

A common LED current is 5 mA, so this chip could drive 8 simultaneously.  If you want high brightness, you need to add a driver such as ULN2003.

Note that the schematic shows red LED's.  The color is important.  Different LED's have different forward voltage.  The blue LED have the highest in the range of 3.3 V and higher.  So with a Vcc=3.3 there is barely enough voltage to light the blue LED.  The red and yellow have much lower forward voltage.  When the chip tries to light the red and blue at same time, the output voltage is dropping enough that the blue is not visible, but the red is easily lit.

From the video, it looks that you have the same resistor on all the LED's.  On different color LED's this will not achieve the same brightness on all LED's.  You need different resistors for each color if you want them the same brightness.

The solution is

Up the Vcc to 5V so that you can reliably light the blue LED's.
Increase the resistor values start with 510 for red and 220 for blue.  This should be about 6 mA for both.


Arduino "Phantom Powering" I am using an Arduino Uno in my project. I recently found that if I disconnect the power from my Arduino (I am powering it by USB port, from a 5V regulator - 7805), then it remains under power from the input pins. I also found that if I disconnect the 3 digit 7 segment common anode display (which is also powered from same 7805) and if I remove the LM358 (which is again powered from the same 7805) from the socket, then my Arduino is not powered anymore.
My questions are:

Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?
My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Please find attached 2 schematics, one is the main PCB (the one with Arduino) and the other schematic is the one with the display, which is placed on the front panel. The J2 connector from first schematic is connected pin to pin to the J2 from second schematic.

https://ibb.co/QnLHsM0

https://ibb.co/KxLFKsQ

When you disconnect the arduino from 5V you must also remove either

disconnect any other device that is connected to the arduino and has its own power supply
or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).


Is it possible to connect a camera to an arduino? I working on a project that requires a small camera to be covering a (insect) nest entrance. The video needs to be transmitted to a computer to be processed. I am interfacing with Java using the RXTX library and will then be tracking objects using OpenCV.

This is the camera

My question is, it it possible to connect this camera to an Arduino (Uno or Yun) and transmit the data back to a computer?

Yes. Check out ArduCam. Do a google search. http://www.arducam.com


What happens if I don't open the USB serial port of Arduino Pro Micro / Leonardo? My question is related to this one. My sketch seems to stop responding after some time if I run it with debug enabled and I don't open the serial port/monitor on the computer.

Does the UART buffer fill up and block or something? Or, does it discard the excess data and keep working?

I can't find information about it.

As far as I can see from CDC.cpp it attempts to see if the USB is available and if not, do not write anything but set the "write error" flag.

size_t Serial_::write(const uint8_t *buffer, size_t size)
{
    /* only try to send bytes if the high-level CDC connection itself
     is open (not just the pipe) - the OS should set lineState when the port
     is opened and clear lineState when the port is closed.
     bytes sent before the user opens the connection or after
     the connection is closed are lost - just like with a UART. */

    // TODO - ZE - check behavior on different OSes and test what happens if an
    // open connection isn't broken cleanly (cable is yanked out, host dies
    // or locks up, or host virtual serial port hangs)
    if (_usbLineInfo.lineState > 0) {
        int r = USB_Send(CDC_TX,buffer,size);
        if (r > 0) {
            return r;
        } else {
            setWriteError();
            return 0;
        }
    }
    setWriteError();
    return 0;
}

This is the same test as is done in operator bool() without the 10 ms delay.

// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

Judging by the comments above, this may not be the most reliable thing in the world.


Trouble using a TSSP77038 with an Arduino I have a Vishay TSSP77038 IR receiver that I would like to read the output of. It is connected as shown in the picture - Vs to 5V, GND to GND and the output to a pin on the Arduino.

My problem is that the reading is constantly low (it is active low so says it is receiving a IR signal), even when i completely cover the sensor or I am in a dark room. Can someone please tell help? Thanks a lot in advance :)

Gerben is correct it looks like you need a pull up resistor so that the pin is high unless the receiver drives it low.

I found this, which was the closest to useful information I found. Have a look at the proximity sensor section, it is similar to what you are using.

You'll want to know a value, I haven't got a clue.  I use 4.7K for I2C pull ups. It's probably easier to start high (weaker) and work your way down, because if you put a 100K resistor in and the signal is low, then the resistor is too strong and you need a smaller one.


How to represent -1 as a byte I want to initialize the value of byte to -1. When I just use byte num = -1 the value ends up being a decimal 255. I've also tried int8_t number = -1 and then byte num = number but this didn't work either.

A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.

Depending on the range of your numbers you could use a char (-128 to +127) or an int (-32768 to +32767).


Looking for a sensor that measures heart/pulse rate I am looking for a sensor which is able to measure heart/pulse rate. Apart from the common pulse sensor from here, are there any others?

I have seen people recommending this as well, and it seems more accurate. Should I get the piezo vibration sensor or are there better sensors? Hoping for something that is easy to use (Like the pulse sensor where you can just place your finger onto the sensor)

Cross-post from: https://www.reddit.com/r/arduino/comments/8f051k/looking_for_a_sensor_which_measures_heartpulse/ and https://forum.arduino.cc/index.php?topic=543857.0

The commonly used approach is to use an infrared source and sensor pressed against the skin.  Usually the finger tip is all that is needed. In addition to pulse, many have also incorporated an Oxygen measurement feature.

The 1st sensor you linked to appears to use this approach.  But instead of buying a ready made sensor, many have made a project of building their own...

This project has been done and published many times on the Internet.  There are well documented projects such as this one from Rutgeurs.  As well as this complex one from a journal called EDN.  And this one and this one from various independent hackers.


Method to iterate over the bits in a byte sent over serial In my current project which integrates Arduino/avr IC with Raspberry-Pi, and each communicating via serial, I'm looking to send a byte of data to the Arduino from the RPi, which then would be iterated over, bit by bit.

Each bit represents a setting. If a bit is 0, then the Arduino would turn that respective device off, if a bit is 1, then Arduino would turn that respective device on. For example, a byte such as: 01100110, would mean the Arduino would have to turn four devices off, and four devices on.

I'm looking for information on how to take a byte over serial, and iterate over that byte bit by bit, and have the Arduino make decisions based on the value of each bit.

Excuse my post for lacking much technical detail, I'm refraining from using terms that are still very vague to me.

Regards.

In all the examples below, value is the value of the byte

LSB -> MSB - so 00001111 would turn ON the first 4 devices and turn OFF the last 4

for(int i = 0, mask = 1; i < 8; i++, mask = mask << 1)
{
    if (value & mask)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Alternatively, you can do the following, but value will be altered

for(int i = 0; i < 8; i++, value = value >> 1)
{
    if (value & 1)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}

Working the other way around in each byte:
MSB -> LSB - so 00001111 would turn OFF the first 4 devices and turn ON the last 4

for(int i = 0, mask = 128; i < 8; i++, mask = mask >> 1)
{
    if (value & mask)
    {
        // bit "i" is on
    }
    else
    {
        // bit "i" is off
    }
}

Alternatively, you can do the following, but value will be altered

for(int i = 0; i < 8; i++, value = value << 1)
{
    if (value & 128)
    {
        // bit is on
    }
    else
    {
        // bit is off
    }
}


How to connect 10 coin vibration motors to UNO? I am new to arduino and anything related to electricals and electronics. I need info on how to connect 10 vibration motors to arduino uno without damaging the board. Do I need an external circuit to regulate and control power supply or can I directly plug in all 10 motors to the board directly?

I would suggest a pair of ULN2003 chips.  These are 6 darlington transistors in a single chip.   Two chips will give you the ability to connect 12 motors.
Each one needs an IO pin to control it - if you want speed control then you will have to look into adding extra PWM channels. For just ON/OFF control any IO pin will do (even analog ones).
10 motors running at the same time will be up near the limit of the Arduino's 5V pin current supply, so you really should consider a separate external 5V power supply (maybe a USB phone charger) of 1A or more to power everything (connect the power supply to the motors and the 5V pin of the Arduino).


Button Relay Control How can I fix this sketch to make it so that once the button is pressed, it performs some action for a certain amount of time and then returns back to a low state until it is pressed again. For example, I need to run a pump for 5 seconds when the button is pressed and then turn off automatically. And then, when I press the button again it will repeat, etc. I am not trying to use a relay module if it is not necessary. Here is my current sketch and a Lab View of the components:

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

int switchPin = 8;
int ledPin = 13;
int buttonPresses = 0;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
}

boolean debounce(boolean last) //just a debounce function
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop()
{
  {currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;

    buttonPresses++;
    lcd.clear();
    lcd.print("Number of Button ");
    lcd.setCursor(0,1);
    lcd.print("Presses = ");
    lcd.print(buttonPresses);
  }
   lastButton = currentButton;
   digitalWrite(ledPin, ledOn);
  }
}

THANK YOU!

This code should work. You will need to declare the following variables:

lastPress   // The last time the button was pressed
outputState  // The state of the timed output
outputPin  // The pin number for the timed output
PERIOD  // The amount of time that the outptu remains on

The code:

void loop()
{
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH)
    {
        ledOn = !ledOn;

        buttonPresses++;
        lcd.clear();
        lcd.print("Number of Button ");
        lcd.setCursor(0,1);
        lcd.print("Presses = ");
        lcd.print(buttonPresses);

        outputState = HIGH;
        lastPress = millis();
    }

    if (outputState && ((millis() - lastPress) > PERIOD))
    {
        outputState = LOW;
    }

    digitalWrite(outputPin, outputState);

    lastButton = currentButton;
    digitalWrite(ledPin, ledOn);
}

A relay should be used to drive a pump etc.. The Arduino Uno can only drive 5V at maximum 20mA.


Watchdog timer/deep sleep loop for Atmega 328 Pro Mini 5v 16 mhz I have been struggling to get my Adafruit 5v pro mini to loop in deep sleep mode several times, then awake to perform something then return to the deep sleep mode loop. While it is out of deep sleep mode I want the watchdog timer to be active to protect against system hangups. Although I can get in and out of deep sleep mode easy enough, and I can also use a loop that performs one deep sleep/awake cycle. I want to maximize the power savings by having a prolonged deep sleep period of several minutes. I have read many posts related to this subject, but have not yet found a response works for me.  Attached is my code, which loops through the sleep cycle twice, but not if ISR(WDT_vect) on row 85 calls my hardwareReset() function. If my call to hardwareReset is used, my test loop on rows 25-30 times out as expected, but my waitSleep function no longer loops twice. Can anyone please offer guidance? Many thanks
// thanks to KeyChainino for basic code. I added ADC disable to further reduce power from 0.67mA to 0.54mA
//
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
const int ledPin = 13;
const int resetPin = 9;

// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin,HIGH);
  Serial.begin(9600);
  Serial.println("Resetting..");
  delay(100);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  for(int i=0; i<9; i++){; //set up loop to force timeout of WDT
  delay(1000);
  Serial.print("Loop ");
  Serial.println(i);
  delay(100);
}
  waitSleep(2); //go sleep for x loops of WDT settings (8 sec max per loop)
}

void waitSleep(int sleep_cycles) {
  while (sleep_cycles) {
    goSleep();
    sleep_cycles--;
  }
}

void goSleep() {
  watchdogSetup(); //enable watchDog
  // disable ADC (analog to digital conversion)
  byte old_ADCSRA = ADCSRA;
  ADCSRA = 0;
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_mode();
  //disable watchdog after sleep
  wdt_disable();
  ADCSRA = old_ADCSRA;
}

void watchdogSetup() {

  //WDP3 - WDP2 - WPD1 - WDP0 - time
  // 0      0      0      0      16 ms
  // 0      0      0      1      32 ms
  // 0      0      1      0      64 ms
  // 0      0      1      1      0.125 s
  // 0      1      0      0      0.25 s
  // 0      1      0      1      0.5 s
  // 0      1      1      0      1.0 s
  // 0      1      1      1      2.0 s
  // 1      0      0      0      4.0 s
  // 1      0      0      1      8.0 s

  // Reset the watchdog reset flag
  bitClear(MCUSR, WDRF);

 //The following bit have to be set at the same time otherwise the system doesn't set the right value

 /* Start timed equence */
 //Watchdog Change Enable to clear WD (by setting the WDCE bit) and Enable WD (by setting the WDE bit)
 WDTCSR |= (1 << WDCE) | (1 << WDE);

 //Set new watchdog timeout value to 8 seconds (WDP3 and WDP0 to 1) and enable interrupts instead of reset (WDIE to 1)
 WDTCSR = (1 << WDIE) | (1 << WDP3) | (1 << WDP0) ;
}
void hardwareReset(){;
  digitalWrite(resetPin,LOW);
}

ISR(WDT_vect) {
  //hardwareReset();
}

I don't know if this is the best solution, but I found a workaround. In the ISR(WDT_vect) function I added a while statement where I added a boolean variable set to true when running the basic program, and false when I enter looping deep sleep mode. I'd appreciate if someone out there can provide a better solution, but for now this one works for me. Below is the revised code in case anyone's interested.
// thanks to KeyChainino for basic code. I added ADC disable to further reduce power from 0.67mA to 0.54mA
//revised by John Bedford 01/12/2020
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
const int ledPin = 13;
const int resetPin = 9;
volatile boolean wdtInterrupt;    //watchdog timer interrupt flag

// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin,HIGH);
  Serial.begin(9600);
  Serial.println("Resetting..");
  delay(100);
  watchdogSetup();
}

// the loop function runs over and over again forever
void loop() {
  wdtInterrupt= true;
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  for(int i=0; i<9; i++){; //set up loop to force timeout of WDT
    delay(1500);
    Serial.print("Loop ");
    Serial.println(i);
    delay(100);
  }
  wdt_reset();

  waitSleep(2); //go sleep for x loops of WDT settings (8 sec max per loop)
}

void waitSleep(int sleep_cycles) {
  wdtInterrupt=false;
  while (sleep_cycles) {
    goSleep();
    sleep_cycles--;
  }
}

void goSleep() {
  watchdogSetup(); //enable watchDog
  // disable ADC (analog to digital conversion)
  byte old_ADCSRA = ADCSRA;
  ADCSRA = 0;
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_mode();
  //disable watchdog after sleep
  wdt_disable();
  ADCSRA = old_ADCSRA;
}

void watchdogSetup() {

  //WDP3 - WDP2 - WPD1 - WDP0 - time
  // 0      0      0      0      16 ms
  // 0      0      0      1      32 ms
  // 0      0      1      0      64 ms
  // 0      0      1      1      0.125 s
  // 0      1      0      0      0.25 s
  // 0      1      0      1      0.5 s
  // 0      1      1      0      1.0 s
  // 0      1      1      1      2.0 s
  // 1      0      0      0      4.0 s
  // 1      0      0      1      8.0 s

  // Reset the watchdog reset flag
  bitClear(MCUSR, WDRF);

 //The following bit have to be set at the same time otherwise the system doesn't set the right value

 /* Start timed equence */
 //Watchdog Change Enable to clear WD (by setting the WDCE bit) and Enable WD (by setting the WDE bit)
 WDTCSR |= (1 << WDCE) | (1 << WDE);

 //Set new watchdog timeout value to 8 seconds (WDP3 and WDP0 to 1) and enable interrupts instead of reset (WDIE to 1)
 WDTCSR = (1 << WDIE) | (1 << WDP3) | (1 << WDP0) ;
}
void hardwareReset(){;
  digitalWrite(resetPin,LOW);
}

ISR(WDT_vect) {
  while (wdtInterrupt){
   hardwareReset();
  }
}


Reading Multiple MPU 9250 Sensors using TCA9548A Multiplexer I am trying to read multiple MPU 9250 sensors using TCA9548A multiplexer in ESP 32 and Arduino IDE. Has anyone done that successfully?
I am new to the  area of Arduino coding. I am trying to edit the code in this tutorial for MPU 9250 (https://www.bluedot.space/tutorials/connect-multiple-sensors-using-i2c-multiplexer/). I am facing issues with libraries and commands while shifting from BME 280 to MPU 9250.  Once  I am changing to MPU 9250 and trying to call instance MPU9250 IMU_0, I am getting error "no matching function for call to 'MPU9250", which I understand is because the library I've used doesn't support the call. I am unable to find alternate library or command. How can this be sorted out?
#include <Wire.h>
#include <MPU9250.h>
MPU9250 mpu_0;
MPU9250 mpu_1;
MPU9250 mpu_2;
MPU9250 mpu_3;

#define TCAADDR 0x70
void tcaselect(uint8_t i) {
  if (i > 7) return;

  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}
void setup() {
  Serial.begin(9600);
  Wire.begin();
  Serial.println(F("##############################"));
  Serial.println(F("Starting Initialization"));
  Serial.println(F("##############################"));

  //*************INITIALIZING FIRST SENSOR*******************************
  tcaselect(0);

  if (mpu_0.begin() != 0x68)
  { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("No"));}
  else
  { Serial.print(F("MPU.1 detected?\t")); Serial.println(F("Yes"));}
  //**********************************************************************
  //*************INITIALIZING SECOND SENSOR*******************************
  tcaselect(1);

  if (mpu_1.begin() != 0x68)
  { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("No"));}
  else
  { Serial.print(F("MPU Nr.2 detected?\t")); Serial.println(F("Yes"));}
  //*********************************************************************
  //**********************************************************************
  Serial.println();
  Serial.println(F("##############################"));
  Serial.println(F("Initialization Finished"));
  Serial.println(F("##############################"));
  Serial.println();
  Serial.println();
}

You need to adapt the example you're following to follow how the MPU library does its construction and setup.
Looking at the documentation for the MPU library you are using, you should change the definitions to:

MPU9250 mpu_0(Wire, 0x68);  // 0x69 if you pulled AD0 high

Then if you read further to the "Common Setup Functions" section, you'll see that this library's setup function has this behavior:

This function returns a positive value on a successful initialization and returns a negative value on an unsuccesful initialization

So you need to adapt that too:
Serial.print(F("MPU.1 detected?\t"));
if (mpu_0.begin() < 0) { // the examples assume zero is ok too
  Serial.println(F("No"));
} else {
  Serial.println(F("Yes"));
}

You'll save yourself some trouble if you use an array for your sensors too.
MPU9250 mpus[] = { MPU9250(Wire, 0x68), MPU9250(Wire, 0x68) };
const int num_mpus = sizeof(mpus)/sizeof(mpus[0]);

Then your initialization can be done with a loop:
for (int i = 0; i < num_mpus; ++i) {
   tcaselect(i);
   if (mpus[i].begin() < 0) {
     // ...
   }
 }

And you can do similar things for interacting with the sensor. e.g.:
for (int i = 0; i < num_mpus; ++i) {
   tcaselect(i);
   mpus[i].readSensor();
   Serial.println(mpus[i].getAccelX_mss());
   // ...
 }


What is Serial.begin(9600)? I know that this is to initialize something:

Serial.begin(9600);

But I want to know what it really means?

Serial.begin(9600) doesn't actually print anything. For that you'd want to use Serial.print("Hello world!") to print the text "Hello world!" to the serial console. Rather it initializes the serial connection at 9600 bits per second.

Both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Arduino to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Arduino IDE's serial monitor) to the same speed in order to see the data being sent.