Arduino Yun not showing anything on the serial monitor I am having issues with the ArduinoYun. It's not showing any data in the serial monitor. The sensor lights up when I plug it in but that's about it and the code seems to compile but nothing is coming through. I am using the Adafruit color sensor. I have SDA/SCL connected to pins 4 and 5. The servo is connected to pin 3. The rest is just on Vin and GND.

#include "Servo.h"
#include "Wire.h"
#include "Adafruit_TCS34725.h"

const int redPos = 160;
const int orangePos = 130;
const int yellowPos = 100;
const int greenPos = 70;
const int bluePos = 30;
const int nonePos = 0; // Kein Objekt erkannt

Servo myservo;

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X);

void setup() {
  Serial.begin(9600);
  Serial.println("Makerblog.at - MuMs Color Sensor");
  if (tcs.begin()) {
    Serial.println("Sensor gefunden");
  } else {
    Serial.println("TCS34725 nicht gefunden ... Ablauf gestoppt!");
  while (1);
  }
  // Der Servo hängt am PWM-Pin 3
  myservo.attach(3);
  // Servo in Grundstellung fahren
  myservo.write(0);
  delay(1000);
}

void loop() {
  uint16_t clearcol, red, green, blue;
  float average, r, g, b;
  delay(100); // Farbmessung dauert c. 50ms
  tcs.getRawData(&red, &green, &blue, &clearcol);
  average = (red+green+blue)/3;
  r = red/average;
  g = green/average;
  b = blue/average;

  // Clear-Wert und r,g,b seriell ausgeben zur Kontrolle
  // r,g und b sollten sich ca. zwischen 0,5 und 1,5
  // bewegen. Sieht der Sensor rot, dann sollte r deutlich über 1.0
  // liegen, g und b zwischen 0.5 und 1.0 usw.
  Serial.print("\tClear:"); Serial.print(clearcol);
  Serial.print("\tRed:"); Serial.print(r);
  Serial.print("\tGreen:"); Serial.print(g);
  Serial.print("\tBlue:"); Serial.print(b);

  if ((r > 1.4) && (g < 0.9) && (b < 0.9)) {
    Serial.print("\tROT");
    myservo.write(redPos);
  } else if ((r < 0.95) && (g > 1.4) && (b < 0.9)) {
    Serial.print("\tGRUEN");
    myservo.write(greenPos);
  } else if ((r < 0.8) && (g < 1.2) && (b > 1.2)) {
    Serial.print("\tBLAU");
    myservo.write(bluePos);
  } else if ((r > 1.15) && (g > 1.15) && (b < 0.7)) {
    Serial.print("\tGELB");
    myservo.write(yellowPos);
  } else if ((r > 1.4) && (g < 1.0) && (b < 0.7)) {
    Serial.print("\tORANGE");
    myservo.write(orangePos);
  } else {
    Serial.print("\tNICHT ERKANNT");
    myservo.write(nonePos);
  }
  Serial.println("");
  delay(100);

Assuming the code works, you should be able to change the position of the servo by altering the initialized color values.  Currently they are:

 const int redPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int greenPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

If, for example, the positions of Red and green are to be swapped all that is needed is to alter the code like this:

 const int greenPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int redPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

The numbers, according to the Arduino's servo driver web page, are the angle in degrees the servo will be moved to after executing the call to the Arduino servo driver.

Given the above, if a new color violet were to be added to the original set of colors the first change would be to move the servo positions slightly higher to make room for the new color.

 const int redPos = 160;
 const int orangePos = 135;
 const int yellowPos = 110;
 const int greenPos = 85;
 const int bluePos = 60;
 const int violetPos = 35;
 const int nonePos = 0;

The next change would be to alter the ranges of the color test code.  As you did not specify what hardware you are using to detect colors, you will have to experiment to find the combination of red, green & blue which matches the new color violet.  The code used for detecting blue is:

 else if ((r < 0.8) && (g < 1.2) && (b > 1.2))

Likely violet contains more red and may be detectable with a line of code like this:

 else if ((r > 1.0) && (g < 1.2) && (b > 1.2))

The position of this test may be important depending on how the detector works.  It may be best to place it after testing for orange.  Remember to use the new initialized variable such that you code may look like this:

else if ((r > 1.0) && (g < 1.2) && (b > 1.2)){
  Serial.print("\tVIOLET");
  myservo.write(violetPos);
}


How To Activate H-Bridge? My understanding of the H-bridge is, that activating in1 or in2 will direct the 12V current to the motor, so it either spins right/left. Not that in1 or in2 is the actual current passing through to the 12V motor.

These are the schematics.

I am trying to activate the H-bridge and the 12V motor by powering In1 with digital 2 from my Arduino.

The power outlet is an universal adapter connected to my wall outlet, which then goes to a breadboard power supply.

I don't have a functioning multimeter, so I cannot measure the exact current going through, but I do know, that if I place in1 in the power outlet's Vout the 12V motor spins.

Other than that, I do not have much information, and I would like to ask you guys for help as to why, the 12V motor doesn't spin when I power in1?

There was no common GND between the H-Bridge and the Arduino.

The question has been solved.


Arduino Uno Issue: No output power I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.

I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

simulate this circuit – Schematic created using CircuitLab

I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.

I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.

The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.

Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you think you have built.


Use LED on pin 13 again after using the SD library The question in short:
On an Arduino UNO or Nano using the SD library, is it somehow possible to use the LED on pin 13 (or any other pin that is used by the library) again after finishing all SD operations?

Detailed explanation:
In my sketch, during setup() I need to read some data from a file on the SD card, which is being closed again before leaving setup().

Now, I wanted to use the LED on pin 13 during loop() as a status indicator for the user, but it seems that after SD.begin(), pin 13 (and its LED) cannot be used as an OUTPUT anymore.

Here is a minimum sketch to show the behavior. It doesn't matter if I try to turn on the LED right after the call to SD.begin() in setup() or in loop():

#include <SD.h>
#include <SPI.h>

#define SD_CS  4
#define LED    13

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

  // This still works:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  SD.begin(SD_CS);

  // This does not work anymore:
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);
}

void loop() {}

It is possible to use the LED on pin 13 again by disabling the SPI bus that is used by the SD library to read/write data to/from the SD card. To disable the SPI bus, simply call SPI.end() after closing the file on the SD card.


Arduino + motor driver (L293D) power consumption Please help me on this question.

Original question :
My chip consists of 1 arduino nano and  3 L293D motor driver. This chip is for controlling motors and other equipments. My question is about how to calculate power consumption of my chip. I searched for about voltage settings of arduiono nano and L293D motor driver, but there are many phusical thinks that i cannot understand. How many hours 2000 mah battery enough for.

Note :
Motors and other equipments will have own power supply. That i say it is just for Arduino Nano, Bluetoot adapter for arduino (HC-05) and 3 motor driver (L293D).

To calculate L293D power usage, you need to lookup the datasheet and check the Voh and Vol. These are the High level voltage and Low level voltage.

On Texas Instruments datasheet, we have:

So you will lose about 1.4V when your output is -0.6A, and 1.2V when your output is 0.6A. If your motor uses 2 outputs (bi-directional) then you have to add the losses.

Then, to get the power dissipated on the power side of the L293D, you take this voltage drop and multiply by the motor´s current.

Example:
Lets say your motor is using 0.6Amps and your power source is 5V + 24V @ 25°C (just like in the datasheet).

The power loss in the L293D is aprox.: (1.4V + 1.2V) x 0.6A = 1,56W.
Since you´ve lost 2.6V in the L293D, your motor will use: (24V - 2.6V) x 0.6A = 12,84W.

To measure this directly on your real circuit, use a multimeter in Ampere mode to measure current, and Volt mode to measure the voltage on the motor terminals when it is on.

As for the arduino, your battery has 2000mAh and I assume it is a 7,4V battery. So it has 2000mAh x 7,4V = 14800mWh of energy stored in it.

If you are running your arduino at 5V, then: 14800mWh / 5V = 2960mAh at 5V.
Now let´s say your arduino and it´s modules, the L293D´s and the motors are using 500mA average, then your battery will last: 2960mAh / 500mA = 5.92 hours in theory.
Why "in theory"? because in real life it is impossible to extract all the energy from inside a battery. A minimum ammount of energy has to remain inside it and some power is lost when you extract it´s energy.

Of course, this is a very raw calculation. In reality, you have to calculate power used in every component. But by calculating the "big guns" first you can get an idea of where you stand.

Basic power loss calculation is done by multiplying voltage drop by the current in each circuit. Voltage drop is the difference between your volts before and after the component.


How to write a more compact ANDed conditions with if statement? I'm working on the rfid module and found an example that do it well. But it has a long testing the 5 bytes of the rfid received bytes, and I've tried to write it in a more compact way.

I did it with a for loop, but how to AND the conditions of the if statement?

How to change this:

if(bt0[cnt-1] == rfid.serNum[0] &&
   bt1[cnt-1] == rfid.serNum[1] &&
   bt2[cnt-1] == rfid.serNum[2] &&
   bt3[cnt-1] == rfid.serNum[3] &&
   bt4[cnt-1] == rfid.serNum[4]){
   lcd.clear();
   lcd.print("card accepted");
   digitalWrite(green_led,HIGH);
   digitalWrite(red_led,LOW);
 }
 else{
    lcd.clear();
    lcd.print("card denied");
    digitalWrite(green_led,LOW);
    digitalWrite(red_led,HIGH);
}

To something like this:

    for(byte i=0;i<MXCD;i++){
      if(bt[i] == rfid.serNum[i%5]){
        cnt++;
      }
    }
    if(cnt==5){
      lcd.clear();
      lcd.print("card accepted");
      digitalWrite(green_led,HIGH);
      digitalWrite(red_led,LOW);
      cnt = 0;
    }
    else{
      lcd.clear();
      lcd.print("card denied");
      digitalWrite(green_led,LOW);
      digitalWrite(red_led,HIGH);
      cnt = 0;
    }

In this way, I did it with 'cnt' variable to count the number of successful matched bytes then test of the number is equal to 5.

Is there a better way than this one ?

Thanks for any comments or suggestions :)

There is a standard C function for this, memcmp(). It performs a memory block compare and can be used like this:

if (!memcmp(bt, rfid.serNum, sizeof(bt))) {
  lcd.clear();
  lcd.print("card accepted");
  digitalWrite(green_led,HIGH);
  digitalWrite(red_led,LOW);
}
else {
  ...
}

Ref. http://www.cplusplus.com/reference/cstring/memcmp/


OTA updates for Arduino using nRF24L01+ Is it possible to send OTA updates to Arduino via nRF24L01+ module?

Here are my findings:

Here is an instructable explaining how to program Arduino wirelessly but this thing uses a BT module which shows up on PC as a COM port.

Here is something similar using Xbees.

However, these use another arduino attached to a PC on the other end. In my case, I am planning to use rPi hooked to another nRF24L01+ rather than PC.

This is an excerpt from the datasheet of Atmega chip:

  In ATmega88A/88PA/168A/168PA/328/328P the Boot LoaderSupport provides
  a real Read-While-Write SelfProgramming mechanism for downloading and
  uploading program code by the MCU itself. This feature allows flexible
  application software updates controlled by the MCU using a
  Flash-resident Boot Loader program. The Boot Loader program can use
  any available data interface and associated protocol to read code and
  write (program) that code into the Flash memory, or readthe code from
  the program memory.

Here is what I planned as a strategy.

Master programmer = Raspberry Pi + nRF module.

Slave arduino = Arduino + nRF24L01 + external EEPROM

Once I have to upload a new code, I can transmit the compiled code to the arduino (I can do that, right?) and Arduino will save it in the external EEPROM for the time being.

When the transfer is complete, I will send a signal which will make the arduino reset and copy the code from EEPROM to its flash memory.

My questions:

Is the strategy correct and feasible?

How should I proceed to achieve it?

Any other suggestions which you might have are welcome.

Your best strategy would be to write your own bootloader.

The existing bootloader receives data through the serial port and writes it, a page at a time, to the flash.  Your custom bootloader, instead, would receive the data through the nRF module and write it to flash, a page at a time.

You could use the source code for the existing bootloader (maybe use optiboot?) as a starting point and remove the UART code, replacing it with nRF code.

Of course, you still need a way to enter the bootloader when you want to program it - the easiest way is to ensure that is added into any sketch you upload so you can send an instruction to that sketch to enter the bootloader.

You would also need to create a program on the Pi to do the programming over the air - or modify an existing one like avrdude.

It may, in the long run, be simpler to have a pair of other Arduinos (maybe something small like an ATTiny based board) to act as bridges between UART and the nRF modules so they become a transparent wireless serial link.


How to integrate ESP8266 Just, to make sure how it works:

I will connect the module to Arduino
it will create AP to which I can connect and send commands via HTTP

So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID (the PC will just communicate over regular network)?
Is it possible to communicate bidirectional somehow?

So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?

If you set the ESP8266 in AP you can connect to it with every wifi capable device.

You can control an ESP8266 with just an Arduino, but you I would not recommend using your Arduino as the power supply. If I remember correctly the mega's VCC pins are rated for 200mA which may or may not be enough for your ESP8266 I'm not sure, but I would recommend using another power supply for the ESP8266.

  Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID

Yes that is possible.

  Is it possible to communicate bidirectional somehow?

I am not exactly sure what you want, but it is possible to communicate in both directions. Assuming you know the local IP address of your ESP8266, you could for example send an HTTP request to it using any browser to which the ESP8266 can reply with anything.

Your ESP8266 can also send data to your computer, but it would require some program on your computer listening for incoming connections. Also possible, but more difficult.

At last I would like to tell you that driving an ESP8266 with an Arduino is like driving a Ferrari with the engine from a tuk tuk. It will move, but you will never use all of it's features. I don't know which version of the ESP8266 you have, but there are versions out there that can be programmed via USB just as your Arduino and you can just use the Arduino IDE and all of it's features like the Arduino language.


i2c slave write to ARM powered device master I want to communicate to an ARM microprocessor via I2C protocol (Multitech mDot, which uses Mbed platform). I successfully receive data from it (and got it displayed on Arduino's serial monitor), but when I want to send data from the Arduino I don't receive nothing on the other end. This is my sketch:

#include <DHT.h>
#include <Wire.h>

// Sensor temperatura, humedad DHT11 (test).
#define DHTPIN 10
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Comunicacion i2c con nodo lora. 7bitaddress 010 1001 (r/w)
#define SLAVE_ADDRESS 0x29

// Variables globales de sensores
float h;
float t;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);
  h = dht.readHumidity();
  t = dht.readTemperature();

  // Comprobamos si ha habido algún error en la lectura
  if (isnan(h) || isnan(t)) {
    Serial.println("Error obteniendo los datos del sensor DHT11");
    return;
  }

  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.println(" *C ");

  Wire.onReceive(receiveEvent);
}

// Total de bytes del arreglo de datos a transmitir: 28 bytes.
void receiveEvent(int howMany) {
  Serial.print("Mensaje recibido por i2c desde MDOT LoRa Node: ");
  while (Wire.available() > 0) {
    Serial.print(char(Wire.read()));
  }
  Serial.println();
  char enviar = "Cacatua";
  Wire.write(enviar);
  return;
}

I wanted to know if this schematic is correct and if the wire write as it is written is performed. If so, I will need to see what is wrong with the code on my ARM device.

It is important to understand, that Wire.write() will not actually send data over the I2C bus. It will only put the data bytes into the send buffer of the library.

The normal way of the Wire library to send data as a slave is to implement the onRequest callback function. It will be called from an I2C ISR when a master on the I2C bus requests data from this slave. In the callback, you use Wire.write() to fill the buffer with data, which then get's send out to the master.

I'm not quite sure about the following: My guess regarding your previous code is, that the Wire library clears the send buffer at some time during the send or read code. That would mean, that the data written in the onReceive callback will simply be lost, instead of used for transmission of requested data. That might be meant that way, so that the users will stick to implementing the onRequest callback, which is the correct way of doing it.

Note: In your code, you call Wire.onReceive(receiveEvent) on every void loop() iteration. That isn't necessary. The Wire.onReceive() method only set's a function pointer to the callback function. It does NOT execute this callback function, which only will be called by the corresponding I2C ISR, when data is actually received. You should use this line only once in setup() to setup the callback function. Though using it multiple times does not break things here. It's just useless.


ESP8266 Bootloader Firmware (on the ESP8266) It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.  If that firmware is corrupted, the ESP8266 is dead.  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.  Does anybody know how to do that?  Thank you.

It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.

Indeed there is.

  If that firmware is corrupted, the ESP8266 is dead.

Well, if that firmware gets corrupted, then yes indeed the chip is dead. That's because the firmware is in ROM, not flash - and the only way it can get corrupted is for the chip to be physically damaged internally.

  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.

No. They are SPI. SPI has nothing to do with flashing firmware. It just happens that AVR chips share the same pins as SPI for their debug protocol.

You cannot replace the bootloader on an ESP8266. It is in ROM. It's unchangeable - except as mentioned earlier by physical trauma to the silicon itself.


Usbasp Arduino Uno Bootloader Flash Error - Win 10 I'm trying to flash an Arduino Uno using usbasp but i'm getting the following error,I have checked all the connection and voltage using multimeter but still this error:

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

C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/bin/avrdude -CC:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cusbasp -Pusb -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

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

I have tried different three other Usbasp but still same error

The problem was with the Arduinos i have received from AliExpress All of them are using WAVGAT AVGA 328P-AU chips. I flasthed other Atmel MEGA 328P chip based Arduinos using USbasp and it's working fine. But i dont know how to flash those WAVGAT AVGA 328P-AU chips.


How to indicate an End of a stream on USB I am making a Lora-USB passthrough device using arduino and somehow I want to indicate that a stream over some data has ended.

So far I have done:

void onLoRaReceive(int packetSize) {
  if (packetSize == 0) return;          // if there's no packet, return

  byte[packetSize] buffer=[];

  while (LoRa.available()) {
    site_t recievedData=LoRa.readBytes(buffer,packetSize);
    Serial.write(buffer,recievedData);
  }
}

So what I want to know is how the software reading from the serial interface will know that a packet has ended; One way I thought is by sending an EOF byte but I am afraid of "rogue" EOF values in packet data.

An another way is to send the packet size through the Serial interface as well but how I will make it understand that what I am sending now is the size and expect X size of data?

LoRa has a moderate data rate and typically substantial gaps between packets, so a simple thing you can do is send the data as printable ASCII hex with newlines or other terminators.

This will just short of double the amount of data you have to move, but do so in a very simple and deterministic way, and you can crank up the serial baud rate to handle it, especially as the baud rate only actually "exists" between two ATmega chips within the Uno.

Another plus is that the data becomes human readable, which is handy for debugging, especially if you might want to intermix advisory messages and data.


Speed up the Arduino I wrote a code that controls a stepper motor using the AccelStepper library. When it receives a serial signal from Visual Basic that contains a coordinate value, the Arduino will control the stepper motor by this value. The code works very well but it runs 1 second after receiving the value over the serial port. I want the code to run faster. Here is the code:

#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper(1, 9, 8);

int pos = 0;

void setup()
{
  Serial.begin(115200);
  stepper.setMaxSpeed(90);
  stepper.setAcceleration(90);
}

void loop()
{
  if (Serial.available()) {
    int steps = Serial.parseInt();
    stepper.moveTo(steps);

    if (stepper.distanceToGo() == 0) {
      stepper.moveTo(stepper.currentPosition());
      stepper.setSpeed(100);
    }
  }
  stepper.run();
}

As others have said, this issue is created because the parseInt function reads in characters until it receives a non numeric character or until it reaches the timeout value, which is set at 1000 ms (1 second). There are a couple of ways to fix this, order most difficult to least:

Instead of just sending a number, send a number and then a letter at the end. So instead of sending "123", you would send "123x".  parseInt() will immediately return when it hits the x.  However, you'll still have the x in the stream so you'll need to manually read it and discard it.
Make the value that is sent a set number of digits - say 4 for example.  Since you know it will be four digits, use a for loop to read in four characters and build it into a number by multiplying.  If you read in digit1, digit2, digit3, digit4 then the number is 1000 * digit1 + 100 * digit2 + 10 * digit3 + digit4.
Make the timeout value for parseInt() smaller.  parseInt() inherits from the Stream class so you would use Serial.setTimeout(50) in the setup function to change it to a 50 ms timeout.


Home made drum kit - How can I speed up the response time after my sensor gets triggered? I am trying to make a psudo drum kit with my Arduino Due and a couple Force Sensitive Resistors (activated with my fingers, no drum sticks). So far in my testing I'm only using one FSR. I've attached an SD Card reader and put a WAV File on there (44100 Hz, 16-bit, stereo). In my 'Loop', I read in the resistance of the FSR to know if it's been triggered, then I play the WAV file accordingly. It works but its not that fast. If this project is going to work, the response time needs to be much faster.

Here's my code:

#include "SD.h" //Lib to read SD card
#include "SPI.h" //SPI lib for SD card
#include <Audio.h>

#define SD_ChipSelectPin 2

const int FSR_PIN = A0; // Pin connected to FSR/resistor divider

const float VCC = 4.875;
const float R_DIV = 10000.0;

void setup()
{
  Serial.println("Starting Drum Kit!");
  Serial.begin(9600);
  while (!Serial) {}

  pinMode(FSR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  Serial.print("Initializing SD Card...");
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("FAILED!");
    while(true);
  }
  Serial.println("done");

  // 44100kHz stereo => 88200 sample rate
  // 100 mSec of prebuffering.
  Audio.begin(88200, 100);

  void loop()
{
  File snare_file;
  short snare_buffer[1024];
  int fsrADC = analogRead(FSR_PIN);
  if (fsrADC > 20) // If the analog reading is non-zero
  {
    Serial.println(String(fsrADC));

    snare_file = SD.open("606snare.wav");
    while (snare_file.available()) {
      snare_file.read(snare_buffer, 1024);
      Audio.prepare(snare_buffer, 1024, 1024);
      Audio.write(snare_buffer, 1024);
    }
    snare_file.close();
  }
}

If I hold down the sensor (constant triggering), the fastest that the file plays is about every half second. Here's the Serial output:

15:12:28.453 -> Initializing SD Card...done
15:12:28.487 -> 1023
15:12:28.930 -> 1023
15:12:29.510 -> 1023
15:12:30.050 -> 1023
15:12:30.628 -> 1023
15:12:31.136 -> 1023
15:12:31.744 -> 1023
15:12:32.328 -> 1023
15:12:32.834 -> 1023
15:12:33.411 -> 1023
15:12:33.955 -> 1023

I've tried playing around with loading the file and buffer in the setup section but I can't get it to work properly. There's not a whole lot of documentation on the Audio library either.

If you know of a better way to speed this up, or if I should be using a different library, please let me know.

This is not really a 'solution', but it might help you in finding out where the real problem is.

Check out which of the statements in the loop function uses up the most time, probably;

int fsrADC = analogRead(FSR_PIN);
Serial.println(String(fsrADC));
snare_file = SD.open("606snare.wav");
while (snare_file.available()) {
snare_file.read(snare_buffer, 1024);
Audio.prepare(snare_buffer, 1024, 1024);
Audio.write(snare_buffer, 1024);
snare_file.close()

Try improving the most time consuming item if possible.

Some possibilities you can try in the steps above:

Do not use AnalogRead but direct port commands
Remove this completely or at least remove the String instance.
Not much you can do here, except not using a file system but raw SD read (you might have problems getting the files on your SD) without a dedicated program on your PC
Not sure about improving this one
Read less bytes, although it might even worsen things. Or read the bytes BEFORE waiting on the trigger (if you know which sample will be played).
Execute the prepare as before the trigger as 5 if possible.
Not sure about this... High likely you cannot keep too many files open at the same time.

Afaik in my synthesizer (Korg Kronos), it reads from all samples the initial part, meaning it can startup the data from RAM, while the rest is read through SSD (in your case SD). However, you might not have enough memory in an Arduino for that.


I am facing a problem of firing multiple interrupts on nodemcu 1.0 on single rising edge pulse.what is problem and what are the solutions? I am working on a project which involves counting the drops falling in a drip chamber of a IV fluid gravity based therapy bottle(saline bottle).I am using IR trans-receiver at the drip chamber to detect a drop falling. I am using a comparator to generate a pulse when ir voltage drops below a certain threshold. The output of comparator is connected to D1 of nodemcu. The ISR is called at rising pulse of comparator .But the nodemcu calls the ISR 3 to 5 times on a single drop.what should I do?plz help.

The signal is probably "bouncing" between HIGH and LOW instead of performing a clean edge, just like it happens with buttons.

Two simple solutions:

Hardware solution: use a schmidt-trigger instead of a comparator
Software solution: define a dead-time for the signal aquisition (disable the interrupt when the desired edge has been detected and enable it again after "dead-time")


How does serial communications work on the Arduino? With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

How does serial communications work?
How fast is serial?
How do I connect between a sender and receiver?

Please note: This is intended as a reference question.

Asynchronous serial (usually referred to as serial) communications is used to send bytes from one device to another. A device could be one or more of the following:

Arduino
PC
GPS
RFID card reader
LCD display
Modem
Other

Clock rate and sampling of data

Unlike SPI / USB / I2C serial communications does not have a clock signal. The sampling clock is an agreed-upon sample rate (known as the baud rate). Both sender and receiver must be configured to be using the same rate or the receiver will receive meaningless data (due to the bits not being sampled at the same rate that they were sent).

The transmission is asynchronous which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:

The graphic above shows the letter 'F' being transmitted. In ASCII this is 0x46 (in hex) or 0b01000110 (in binary). The least significant (low-order) bit is transmitted first, thus in the above graphic you see the bits arriving in the order: 01100010.

The "idle" time between bytes is transmitted as continuous "1" bits (effectively, the transmit line is held high continuously).

To indicate the start of a byte, the Start Bit is always indicated by pulling the line low as shown on the graphic. Once the receiver sees the start bit, it waits for 1.5 times the sample time, and then samples the data bits. It waits 1.5 times so that it:

Skips the start bit
Samples half-way through the next bit

If the baud rate is 9600 baud, for example, then the sample rate will be 1/9600 = 0.00010416 seconds (104.16 µs).

Thus, at 9600 baud, after receiving a start bit the receiver waits for 156.25 µs, and then samples every 104.16 µs.

The purpose of the Stop Bit is to ensure that there definitely is a 1-bit between each byte. Without the stop bit, if a byte ended in a zero, then it would be impossible for the hardware to tell the difference between that and the start bit of the next byte.

To produce the above output on an Uno you could write this code:

void setup()
  {
      Serial.begin(9600);
      Serial.print("F");
  }

void loop ()
  {
  }

Number of data bits

In order to save transmission time (in the olden days, heh) you were allowed to specify different numbers of data bits. The AtMega hardware supports data bits numbering from 5 to 9. Clearly the less data bits the less information you can send, but the faster it will be.

Parity bits

You can optionally have a parity bit. This is calculated, if required, by counting the number of 1's in the character, and then making sure that this number is odd or even by setting the parity bit to 0 or 1 as required.

For example, for the letter "F" (or 0x46 or 0b01000110) you can see that there are 3 ones there (in 01000110). Thus we already have odd parity. So, the parity bit would be as follows:

No parity: omitted
Even parity: a 1 (3 + 1 is even)
Odd parity: a 0 (3 + 0 is odd)

The parity bit, if present, appears after the last data bit but before the stop bit.

If the receiver does not get the correct parity bit, that is called a "parity error". It indicates that there is some problem. Possibly the sender and receiver are configured to use different baud (bit) rates, or there was noise on the line which turned a zero to a one or vice-versa.

Some early systems also used "mark" parity (where the parity bit was always 1 regardless of the data), or "space" parity (where the parity bit was always 0 regardless of the data).

9-bit transmission

Some communication equipment uses 9-bit data, so in these cases the parity bit is turned into the 9th bit. There are special techniques for sending this 9th bit (the registers are 8-bit registers so the 9th bit has to be put somewhere else).

Number of stop bits

Early equipment tended to be somewhat slower electronically, so to give the receiver time to process the incoming byte, it was sometimes specified that the sender would send two stop bits. This basically adds more time where the data line is held high (one more bit time) before the next start bit can appear. This extra bit time gives the receiver time to process the last incoming byte.

If the receiver does not get a logical 1 when the stop bit is supposed to be, that is called a "framing error". It indicates that there is some problem. Quite possibly the sender and receiver are configured to use different baud (bit) rates.

Notation

Commonly, serial communication is indicated by telling you the speed, number of data bits, type of parity, and number of stop bits, like this:

9600/8-N-1

This is telling us:

9600 bits per second
8 data bits
No parity (you might see instead: E=even, O=odd)
1 stop bit

It is important that the sender and receiver agree on the above, otherwise communication is unlikely to be successful.

Pin-outs

The Arduino Uno has digital pins 0 and 1 available for hardware serial:

To connect two Arduinos you swap Tx and Rx like this:

Speed

A wide range of speeds is supported (see graphic below). "Standard" speeds are usually a multiple of 300 baud (eg. 300/600/1200/2400 etc.).

Other "non-standard" speeds can be handled by setting the appropriate registers. The HardwareSerial class does this for you. eg.

Serial.begin (115200);  // set speed to 115200 baud

As a rule-of-thumb, assuming you are using 8-bit data, then you can estimate the number of bytes you can transmit per second by dividing the baud rate by 10 (because of the start bit and stop bit).

Thus, at 9600 baud you can transmit 960 bytes (9600 / 10 = 960) per second.

Baud rate errors

The baud rate on the Atmega is generated by dividing down the system clock, and then counting up to a pre-set number. This table from the datasheet shows the register values, and error percentages, for a 16 MHz clock (such as the one on the Arduino Uno).

The U2Xn bit affects the clock rate divisor (0 = divide by 16, 1 = divide by 8). The UBRRn register contains the number the processor counts up to.

So from the table above, we see that we get 9600 baud from a 16 MHz clock as follows:

16000000 / 16 / 104 = 9615

We divide by 104 and not 103 because the counter is zero-relative. Thus the error here is 15 / 9600 = 0.0016 which is close to what the table above says (0.02%).

You will notice that some baud rates have a higher error amount than others.

According to the datasheet the maximum error percentage for 8 data bits is in the range of 1.5% to 2.0% (see the datasheet for more details).

Arduino Leonardo

The Arduino Leonardo and Micro have a different approach to serial communications, as they connect directly via USB to the host computer, not via the serial port.

Because of this, you must wait for Serial to become "ready" (as the software establishes an USB connection), with an extra couple of lines, like this:

void setup()
  {
      Serial.begin(115200);
      while (!Serial)
      {}  // wait for Serial comms to become ready
      Serial.print("Fab");
  }

void loop ()
  {
  }

However, if you want to actually communicate via pins D0 and D1, (rather than by the USB cable) then you need to use Serial1 rather than Serial. You do so like this:

void setup()
  {
      Serial1.begin(115200);
      Serial1.print("Fab");
  }

void loop ()
  {
  }

Voltage levels

Note that the Arduino uses TTL levels for serial communications. This means that it expects:

A "zero" bit is 0V
A "one" bit is +5V

Older serial equipment designed to plug into a PC's serial port probably uses RS232 voltage levels, namely:

A "zero" bit is +3 to +15 volts
A "one" bit is −3 to −15 volts

Not only is this "inverted" with respect to TTL levels (a "one" is more negative than a "zero"), the Arduino cannot handle negative voltages on its input pins (nor positive ones greater than 5V).

Thus you need an interface circuit for communicating with such devices. For input (to the Arduino) only, a simple transistor, diode, and a couple of resistors will do it:

For two-way communication you need to be able to generate negative voltages, so a more complex circuit is required. For example the MAX232 chip will do that, in conjunction with four 1 µF capacitors to act as charge-pump circuits.

Software Serial

There is a library called SoftwareSerial that lets you do serial communications (up to a point) in software rather than hardware. This has the advantage that you can use different pin configurations for serial communications. The disadvantage is that doing serial in software is more processor-intensive and more prone to error. See Software Serial for more details.

Mega2560

The Arduino "Mega" has 3 additional hardware serial ports. They are marked on the board as Tx1/Rx1, Tx2/Rx2, Tx3/Rx3. They should be used in preference to SoftwareSerial if possible. To open those other ports you use the names Serial1, Serial2, Serial3, like this:

Serial1.begin (115200);  // start hardware serial port Tx1/Rx1
Serial2.begin (115200);  // start hardware serial port Tx2/Rx2
Serial3.begin (115200);  // start hardware serial port Tx3/Rx3

Interrupts

Both sending and receiving, using the HardwareSerial library, use interrupts.

Sending

When you do a Serial.print, the data you are trying to print is placed in an internal "transmit" buffer. If you have 1024 bytes or more of RAM (such as on the Uno) you get a 64-byte buffer, otherwise you get a 16-byte buffer. If the buffer has room, then the Serial.print returns immediately, thus not delaying your code. If there is no room, then it "blocks" waiting for the buffer to be emptied enough for there to be room.

Then, as each byte is transmitted by the hardware an interrupt is called (the "USART, Data Register Empty" interrupt) and the interrupt routine sends the next byte from the buffer out of the serial port.

Receiving

As incoming data is received an interrupt routine is called (the "USART Rx Complete" interrupt) and the incoming byte is placed into a "receive" buffer (the same size as the transmit buffer mentioned above).

When you call Serial.available you find out how many bytes are available in that "receive" buffer. When you call Serial.read a byte is removed from the receive buffer and returned to your code.

On Arduinos with 1000 bytes or more of RAM, there is no rush to remove data from the receive buffer, provided you don't let it fill up. If it fills up then any further incoming data is discarded.

Note that because of the size of this buffer there is no point in waiting for a very large number of bytes to arrive, for example:

while (Serial.available () < 200)
  { }  // wait for 200 bytes to arrive

This will never work because the buffer cannot hold that much.

Tips

Before reading, always make sure data is available. For example, this is wrong:

if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.
Be aware of how long it takes to send data. As mentioned above, at 9600 baud you an only transmit 960 bytes per second, so trying to send 1000 readings from an analog port, at 9600 baud, won't be very successful.

References

Async (Serial) peripheral interface - for Arduino
How to process incoming serial data without blocking
RS-232 - Wikipedia
Arduino Reference - Serial


How to change input pin of FreqCounter Arduino Uno/Dumilanove library? The following link to the library defines arduino pin 5 for input pin for signal.
 https://www.pjrc.com/teensy/td_libs_FreqCount.html

But the problem is I'm using an 16x2 LCD display with the arduino pin 5. The display needs pin 5 to work. So the question can solved in two ways,to both of which I don't know the answer.
1. Change LCD pin number to other pin. (Tried it was a failure. I've probably done it wrong)
2. Change the input pin for the freqcount library.

Any idea how to get past this bottleneck?

The library makes use of the hardware peripheral Timer 1 which has its input on pin 5 of the Uno.

It can't be changed.  You have no choice in that.

You will have to move the LCD to another pin instead.


Is there a variable type of half byte? Is there a workaround? I have this long array of 64 values going from 0 to 15, values which only cost 8 bits, for a pulse width modulation.
So I made a test to see its cost in space, commenting one of the two arrays.
const byte wave[64] = {8,9,9,10,11,11,12,12,13,13,14,14,14,15,15,15,15,15,15,15,14,14,14,13,13,12,12,11,11,10,9,9,8,7,7,6,5,5,4,4,3,3,2,2,2,1,1,1,1,1,1,1,2,2,2,3,3,4,4,5,5,6,7,7};
//const byte wave[2] = {8,9};
byte i = 0;
void setup() {pinMode(1,OUTPUT);}
void loop() {            //(Don't worry about the code in here,
  analogWrite(1,wave[i]);//it's just to get the program
  i++;delay(1);          //to hold on to the data)
}

The compiler said Sketch uses 1112 and 1050 bytes (3%) of program storage space. or a difference of 62 bytes.
This tells me that one could save a lot of memory by keeping them in a 4-bit or what I'd like to call half byte, going from 0 to f rather than from 00 to ff.
How could I do so without turning the code to unreadable bit mush?

If the point is to save program storage space, you're probably going to have to live with some unreadable bit mush or do bit-swapping in your head. Here's a code example that encodes your same array as a 32-byte array, but you have to combine pairs of your original numbers into bytes. It's not especially difficult because each hex digit represents one of your original numbers.
I.e., 8,9 becomes 0x89. Likewise, A is 10, B is 11, etc. Then you can iterate 1 thru 64 and do some division and bit-shifting to pull out the original value you wanted. This will iterate through your 32-byte array and pull out 64 half-byte values.
    const byte wave[32] = {0x89,0x9A,0xBB,0xCC,0xDD,0xEE,0xEF,0xFF,0xFF,0xFF,0xEE,0xED,0xDC,0xCB,0xBA,0x99,0x87,0x76,0x55,0x44,0x33,0x22,0x21,0x11,0x11,0x11,0x22,0x23,0x34,0x45,0x56,0x77};
    for(int i=0; i<64; i++) {
        byte val;
        if (i % 2) {
            // the little byte is first (LITTLE ENDIAN)
            val = wave[i/2] & 0x0F;
        } else {
            // the BIG byte is second
            val = (wave[i/2] >> 4) & 0x0F;
        }
        Serial.printf("%i=%i\n", i, val);
    }

NOTE: that the Endianness if your system may be different than mine. Most systems are little-endian these days, but you never know.


How to display float variables on oled display (0.96'') I have a similar problem than the discussed here : How to display variables on 0.96" OLED with u8glib library?

I'd like to know how can I show float variables in place of int variables. What should i modify in this part of my code ?

char buf[9];
sprintf (buf, "%d", a);
u8g.drawStr(18, 3, buf);

} while( u8g.nextPage() );

delay(200);

}

Thanks in advance =D

The printf group of functions in the Arduino library don't implement float and double conversions. For those, you need the function

char *dtostrf(double dval, int8_t width, uint8_t prec, char *buf);
  Convert the double value passed in dval into an ASCII string stored in
  buf. Conversion is done as "[-]d.ddd". The minimum field width of the output
  string (including the '.' and the possible sign for negative values) is given
  in width, and prec determines the number of digits after the decimal. width
  is signed, negative for left adjustment.
  Returns buf.

, which you'll need to call for each float you want to convert.

Note that you could convert several floats into strings, upfront, each into its own character buffer, then use sprintf to format the final buffer - remembering that in sprintf's format string, those buffers contain character strings, which you'll need to specify with '%s' format-specs.


Can't store temperature in variable ( for further processing) I am trying to store temperature data in a variable, so that I can use it for making a JSON object, but the problem is, that when I try to store the temperature in a variable, it prints out the wrong value. I'm using a DHT11 temperature/humidity sensor and a library for calculating the temperature.

Serial.print("Temperature (°C): ");
Serial.println((float)DHT11.temperature, DEC);
int temp1 = ((float)DHT11.temperature, DEC);
Serial.println(temp1);

These 4 lines is printing out this:

Temperature (Â°C): 23.0000000000
10

The first one is correct, but the second line should also be saying "23".
I have tried only loading the data in once with the library, as in outcommenting one line, but that does not work.
It's like I have some syntax wrong, but I can't figure out what.

This line:

int temp1 = ((float)DHT11.temperature, DEC);

casts DHT11.temperature to an float, throws away the value, then assigns DEC to temp1. That is not what you want.

int temp1 = DHT11.temperature;


#Ardunio Send Float values with bluetooth.print in arduino I have been creating the example for bluetooth communication with arduino with hc_05  Problem I am facing are below.

String statuss= "1.00,2.00,3.00";
bluetooth.print(statuss);
Serial.print(statuss);

This is the code where is get only last 2 digits i.e 00 in android while its showing me complete string in serial monitor.

String statuss= "Hello";
bluetooth.print(statuss);
Serial.print(statuss);

Then I get the output as ello in Android n in Serial monitor it show Hello

Can Anybody suggest the whats the problem

I suspect (at first sight) a speed problem. Android runs Bluetooth at 115200 Bauds. So you must set your HC-05 o HC-06 at this speed to get proper result.

But as you perform "bluetooth.print(statuss);" and also "Serial.print(statuss);" this mean you have created a virtual port, probably using the Software Serial lib.
Unfortunatly, this lib is not very efective. At speed higher than 19200 Bauds, you lost data (I've had a lot of problem with that before understanding!!)
The only right way is to use directly the RX and TX port of the Arduino (pin 0 and 1) and use (eg) a LCD Display to display data and help you debugging your Arduino code (as when you plug the HC on Pin 0 and 1 you lost the access to the serial monitor).

A trick: with the HC on pin 0 and 1, each time you send the sketck to the Ardino, you must unplug RX as it's used for sending the code.

Hope this will help.


Schematic interpretation, where to put resister? I'm new to schematics, trying to figure out where to put a resistor (no  instructions other than the schematic)

I'm told I need:
10K variable Resistor x 1, 4.7K Resistor x 1, 100 Resistor x 1

But I only see where to put the 10k resistor (I added a blue circle around the 10k). Can someone show me (describe, illustrate) where to put the others?

And where there's the triangles for +5V or AGND, do I put something there (purple circles)??

Thanks!

Here is a link from the project I'm trying to build
https://bestengineeringprojects.com/arduino-weighing-machine-using-hx711/

Neither are shown in that schematic, as described in the text.

Calibration Circuit: The weight calibration circuit is shown in figure 2. [...]
[A schematic that includes a 4.7kohm resistor]

...

Note: Cathode and Anode pin of LCD (pin 15 and pin 16) is not shown in circuit diagram. Connect +5 volt to pin 15 with current limiting resistor (generally 100-ohm) and pin 16 of LCD to ground.


How to assign ESP8266 access point a hostname that can be resolved by the stations? I want to assign a hostname to a ESP8266 access point, so that the clients can reach a webserver on this access point without caring about the IP address of the AP. How can that be done?
I tried using WiFi.hostname("something"); but that does not work with AP mode. Can this somehow be done?
UPDATE
Using mDNS seems to work in this AP mode too. However, I am still curious to know if this is possible to access the webserver on the AP using the hostname and not mDNS.

I'm unclear on the distinction being drawn here:

the hostname and not mDNS

mDNS, like DNS, and hostname lists are all things a "resolver" would use to map a "hostname" to an IP address.
If you mean "how do I use DNS instead of mDNS?", you'd need to have your ESP8266 running a DNS server.  And for clients to be aware of it you'd probably have to be running a DHCP server as well.
By the way, the examples list for the ESP8266 Arduino package contains a DNSServer/DNSServer example that appears to do exactly this.  I have just tested it.
This is the exact code I ran out of the ESP8266 Arduino github repo at the tag for the version of the ESP8266 Arduino core I tested it on, 2.7.4.


Possible to put the ESP8266 in bootloader mode without a FTDI? I am trying to upload something directly to the ESP8266 using the ESP8266 IDE.
I have configured the ESP8266 to communicate at 9600 using UART_DEF and I have set the ESP8266 IDE at 9600. I see some tutorials that say to use a FTDI but I only have a Serial to TTL cable (note it even says at the bottom that it's not good for Arduinos :( ) and  am making the following connections:

ESP8266 RX - TTL cable TX
ESP8266 TX - TTL cable RX
ESP8266 GND - common GND
ESP8266 VCC - External 3.3V
GND from External 3.3V - common GND
ESP8266 GPI0 (through a 10k resistor) - common GND
ESP8266 GPI2 (through a 10k resistor) - External 3.3V
EPS8266 CH_PD - External 3.3V (sorry, that was wrong before)

However, when I upload that sketch I get an error that the board cannot be found. I have read online that the ESP has some bootloader mode that needs to be activated but haven't found great instructions on how to do that. Any advice would be appreciated.

FYI I also have an Uno if that is any help. I have communicated with the ESP8266 through the Uno before (connecting the Uno reset to ground) .

The cable you point to is fine for programming the ESP8266. The only reason it's not "good" for an Arduino is the lack of a DTR signal to trigger a reset for you - which you can do manually anyway and still use it for an Arduino (if your reactions are fast enough).

You have no such problem with the ESP8266. Once you have it in bootloader mode it stays in bootloader mode until you tell it to exit bootloader mode.

First make sure that the ESP8266 is actually set up to run properly. That means:

Connect CH_PD to 3.3V, not GND, through a pull-up resistor.
Connect GPIO0 to 3.3V via a pull-up resistor.
Connect RST to 3.3V via a pull-up resistor.

Then for simplicity of programming:

Connect a button between RST and GND
Connect a button between GPIO0 and GND

To enter bootloader mode simply hold the GPIO0 button in, tap the RST button, then release the GPIO0 button.  When you have successfully uploaded your firmware just tap the RST button to exit bootloader mode.

ESP8266 boards with a built-in USB interface usually use both the DTR and the RTS pins to control both those buttons virtually. That's somewhat complex to arrange for an external USB to TTL UART adaptor, so it's simpler to just press the buttons manually.

Here's a link to a website that details the circuit and operation using an ESP-01 as an example.


Connecting an Arduino to a telephone line? I would like to connect my Arduino Uno to a telephone line in order to answer a call, record a sequence of DTMF tones, generate a DTMF tone in response, and hang up.

The telephone line uses a standard RJ11 connector. When a touch-tone phone is connected to the line, it receives one of two rings:

a standard ring, which signals an incoming call
a shorter "two-ring" sequence which signals a call from a local intercom

I would like my Arduino to listen for the "two-ring" sequence and only answer those calls.

How would I go about connecting my Arduino to the telephone line? Is there a shield designed for this purpose? I know I can use the tone() function to generate the DTMF tones, but I'm assuming I would need to perform some form of Discrete Fourier transformation in order to "read" the DMTF tones from the other end of the line.

Any suggestions would be appreciated.

You can interface arduino to telephone line using MT8870D chip. This IC can decode DTMF tones. Below is a reference schematic from the datasheet.

Another popular design floating on the internet is below:

There are pre-build modules available from futurelec :

You can use Holtek HT9200 IC to encode DTMF that can be interfaced with Arduino. Below is the reference schematic from its datasheet.


Force Sensitive Resistor OverLoad I've got just a simple question. What happens when I overload Force Sensitive Resistor (FSR). Example Here.

Let's say that it's got force sensitive range between 100g and 10 000g. What would happen if I'd create pressure about 100kg? I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance? If so, can this FSR survive this overload? Has somebody test that?

Thank you for any answer.

I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance?

The harder the force, the lower the resistance. Sparkfun has a datasheet attached that shows the following graph:

Notice how both axis of the graph are logrithmic. This means that the resistance will never reach 0 ohms. However it will get close. At 10 Kg (22 lb) the resistance is about 250 ohms.

  What would happen if I'd create pressure about 100kg?

The datasheet has the following to say for weight above the 10 Kg mark:

  At the high force end of the dynamic range, the response deviates from the power-law behavior, and eventually saturates to a point where increases in force yield little or no decrease in resistance. Under these conditions of Figure 2 [ie. the graph above], this saturation force is beyond 10 kg. The saturation point is more a function of pressure than force. The saturation pressure of a typical FSR is on the order of 100 to 200 psi. For the data shown in Figures 2, 3 and 4, the actual measured pressure range is 0 to 175 psi (0 to 22 lbs applied over 0.125 in^2). Forces higher than the saturation force can be measured by spreading the force over a greater area; the overall pressure is then kept below the saturation point, and dynamic response is maintained. However, the converse of this effect is also true, smaller actuators will saturate FSRs earlier in the dynamic range, since the saturation point is reached at a lower force.

In summary, the weight applied can go over 10 Kg providing that weight is spread over the sensing area. The larger FSRs (such as this one) are better suited for this purpose as they have a larger area for which to spread the pressure.

Note: It is quite possible that with 100 Kg you could irreversibly damage the FSR, particularly if the weight isn't spread over the sensor area.

Measuring an analog voltage from the sensor is possible so that it can be fed into one of the analog pins of the Arduino. This Adafruit page has a nice table at the bottom showing the analog voltage that you get when you put the sensor in a voltage divider network (ie. in series) with a 10K ohm resistor.


16 bit SPI on Arduino Due I'm trying to control AD7091-8 using Arduino Due.

This IC calls for 16 bit SPI R/W. I'd read that I can change the transmit and receive bits of Arduino DUE by changing a register (bits 4-7 of SPI_CSR).

I was able to change the SPI of Due from 8 to 16 bits. Confirmed this by looking at SCLK and MOSI in the scope. However, the data I want to transfer is becoming intermittent.

I want to send 0x1000. On 8 bits, using the line

SPI.transfer(10,0x10,SPI_LAST);

I really can see this being sent on MOSI.

However, when I'm on 16 bits, the line

SPI.transfer(10,0x1000,SPI_LAST);

It's either becoming 0x0000 or 0x0008. I'm losing the bit or it's becoming LSB_FIRST. Not MSB_FIRST.

Below is the actual code.

#include <SPI.h>
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component\component_spi.h"
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_spi0.h"

#define CS 10

void setup() {

  pinMode(CONV,OUTPUT);

  Serial.begin(9600);
  SPI.begin(CS);
  SPI.setDataMode(CS, SPI_MODE0);
  SPI.setClockDivider(CS,21);

  REG_SPI0_WPMR=0x53504900;
  REG_SPI0_CR=0x1;
  SPI0->SPI_CSR[0]=0x00001580;

  SPI.setBitOrder(MSBFIRST);
  delay(1);
}

void loop() {

  SPI.transfer(CS,0x1000,SPI_LAST);

  int a = SPI.transfer(CS,0x0000, SPI_LAST);
  delay(1000);

  Serial.println(a);
}

How can I make my data reliable and the order still with MSB first?

Found the problem on the SPI library.

When I do the command SPI.transfer, the data is stored on a byte type variable. And I'm passing a 16 bit data on it.

I've changed line 84 of SPI.h to

uint16_t transfer(byte _pin, uint16_t _data, SPITransferMode _mode = SPI_LAST);

so it will return and receive 16 bit data.

Also have to change the corresponding function on SPI.cpp (line 174)

uint16_t SPIClass::transfer(byte _pin, uint16_t _data, SPITransferMode _mode)

so they will match.

I've copied and renamed the SPI library that I've changed so it won't affect other codes.


LEDs always dim with arduino nano so I'm making an animated LED brake light using arduino nano, similar to this: https://www.youtube.com/watch?v=d5Ohzg3JKq0&ab_channel=IMEEMADE
I have 18 channels, with differet amount of series LEDs and resistor. All LED + are wired together, intended for 14.5V input, with individual resistor after the last LED cathode:
14.5V -> + LED - -> R -> GND
I have some channels with 1 LED, 2 LED and 4 LED, all tuned with different resistors so that each channel "pulls" ~20mA at 14.5V. 12V works fine as well just ever so slightly dimmer. On a power supply, I can ground any channel without cross talk, or ground all and all LEDs light up evenly (from what my eyes can tell).
I had originally planned on providing 5V input to the arduino using a buck converter and sinking each channel to a digital output pin (D2-D19 or D2-D13 + A0-A5). I ended up providing 12V to Vin and 12V to the LEDs as well as the arduino did not work at all as expected with 14.5V to the LEDs and 12V to the Vin.
My problem is that with this setup, no matter what I do in code, when the arduino is connected to Vin and ground, some LEDs are always lit dimly (D2-D13 oddly). They do indeed get brighter when pinMode is set to OUTPUT and digitalWrite({pin}, LOW) is called. But writing HIGH or setting pinMode to INPUT doesn't turn them off, just leaves them dim. I've tried adjusting Vin between 7-12V, setting the regulator to 5V and connecting directly to 5V. No change in behavior. Only thing that gets the LEDs to stop lighting dimly is lowering input voltage to the LEDs themselves. But then I don't have enough to drive the 4 series LED channels...
I know this can work because in the video I linked, there are 4 series LEDs driven in the same manner (though red, I'm using white), but not much is explained with the use of the arduino.
What am I doing wrong or how can I make this work? I need at least 12V to the LED board to ensure the 4 series channels light up properly. I've already maxed out the digital channels on the arduino nano from what I've read, so I can't use one as input (instead of Vin or 5V) if that matters or split the 4 series into 2 channels, etc...
Thanks in advance!

You can't drive LEDs from a source greater than 5V as a low-side switch with an Arduino directly. To do so you need an "open drain" output.
You can create them on the Arduino by adding a single transistor (N-channel MOSFET with "logic level" threshold, or NPN BJT) which the Arduino switches:

simulate this circuit – Schematic created using CircuitLab
R2 just exists to keep M1 turned off when the Arduino's not actively driving it (i.e., while the bootloader runs, etc).


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

Python

import serial

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

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

print('done')

Arduino

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

void loop()
{

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

}

If I keep the ser.write(b'2') line in the Python code commented out, the code executes nearly instantly, and I am able to see both transmissions in the serial monitor. If I uncomment it, the Python code takes about 5-7 seconds to execute, and none of the data comes through the serial monitor.

I've tried different baud rates but that hasn't helped. I've also tried sending an integer rather than b'#', and the same thing happens, no data is transmitted if I have all three serial commands active.

What is happening in my code? Is the serial buffer overloaded by the three successive writes and the buffer ends up flushing?

The problem is that your code works but you substract 48 from what you received.
Which if python sends a char with values: '0' '1' '2' it will result in the serially outputted values of NUL SOH STX which are invisible.

If python transmits the raw byte value (aka 0x00 0x01 0x02) this would result in 0x00 - 48 = undefined behaviour with a underflow (same goes for 0x01 and 0x02)


HC-06 pairing to arduino I have a bluetooth module HC-06 and want to pair it to my Arduino UNO. The thing is when I researched how to do so, I got different answers. What pairing should I use? Thank you in advance. I have highlighted the differences.

First version:
https://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/

HC-06>>>Arduino

VCC>>>>3.3v

GND>>>>GND

TXD>>>>RXD

RXD>>>>TXD

Second version:
http://42bots.com/tutorials/hc-06-bluetooth-module-datasheet-and-configuration-with-arduino/

HC-06            <<>> Arduino

HC-06 Ground GND <<>> GND

HC-06 VCC pin  <<>> 5v

HC-06 TX/TXD pin <<>> Arduino RX

HC-06 RX/RXD pin << resistors >> Arduino TX

[![enter image description here][1]][1]

[![enter image description here][2]][2]

Which you use depends on two factors: the HC-06 carrier board you have, and which Arduino you are using.

If your carrier board has (and most do) a 3.3V regulator then you power the board from 5V.

If your Arduino is a 5V Arduino (such as an Uno) then you need a voltage divider on the (arduino)TX->(hc)RX pins otherwise you risk damaging the bluetooth module.


What is the highest baud rate that can work between Android device and an Arduino connected to an HC05? I see a lot of baud rates in the AT Command documentation for the HC05 however I am not sure what is the fastest that can work between the Arduino controlled embedded system and the Android phone. I also do not know of a way to change the baud rate of the Bluetooth communication in software. I am writing the application in Java with Android Studio IDE.
I read the documentation for HC05 and realize that it only operates with one Bluetooth profile. i.e the Serial Port Profile. The documentation says that this profile offers a maximum data-rate of 128000 bits/sec. However, the HC05 has a max baud rate option of 1382400 bits/sec. Why would this option be there if it is not possible to use? Can you please explain what I am missing and point me into the direction of some useful information? Thank you.

The HC-05 may only have implemented baud rates up to 1382400, even though the protocol is spec'd for up to 128000.
If you're using Software Serial to talk to the HC-05 from an Uno, 9600 baud is about as fast as SoftwareSerial can keep up with incoming bytes (I've heard from some people that 19200 will work).
If you're using one of the UARTs on a Mega, you may be able to use the full rate implemented by the HC-05. An experiment would be in order...
Update:

I did an experiment and found out that the maximum baud rate
achievable between the HC05 (communicated with by SoftwareSerial on
Arduino Nano) and the Android device is 115200.

I would guess you were transmitting from the Arduino? I've been able to transmit that fast with SoftwareSerial but its receiving ability is more limited. (This has enabled me to, f/ex, set an HC-05 or an ESP8266 to a slower baud-rate than it shipped with, by blindly transmitting an appropriate 'AT' command at the higher speed, then testing it at my intended speed to see if the command worked).


Setting a Pin to HIGH to simulate a button with a "pull up" resistor in the below Fritzing diagram, I have a button that has a pull-up resistor, which when pressed, sets the GPIO Pin 23 to HIGH. On the Raspberry Pi, when the button is released, the GPIO goes LOW. The Raspberry Pi detects when the button is released and pressed. This is my desired behavior.

However, in my current configuration, I have PIN 13 connected to the Base of a NPN transistor to try to simulate the same behavior as the button with a pull-up resistor. When pin 13 is set to high, it sets the GPIO 22 Pin to high. When I set the Arduino Pin 13 to low, The GPIO Pin goes low but the Raspberry PI does not detect that GPIO 22 pin went low. Is there a way to simulate the same behavior as a button with a pull-up resistor with an OUTPUT pin from the arduino?

First of all, I don't think you will need full simulation of a button. There are a couple of things this approach won't have:

Bouncing: it'll be (kinda, minus interference) a square wave. With a real button, the metal contacts "bounce," thus creating a weird waveform. Depending on interference, you'll still need debouncing code, although I would be surprised if it was necessary. I'd inlcude it in case I modified it to add a real button and/or there's some weird interference.
The time it's "pushed" may be very short, depending on your code. Keep this in mind when designing this.

Basically, you're hooking up the Arduino and the RPi together, with a voltage divider or a level shifter between the two.

Voltage divider:

Sparkfun

That is a voltage regulator (drawn four different ways; it's the same circuit). I calculated the values you will need: 1700 ohm for R1, 3300 ohm for R2.

Of course, serial (with USB of the Arduino) communication would be a lot easier...


Time.h rollover after 49.7 days I'm developing a arduino based system, which includes a alarm system.

Searching on the Internet, I found these lybraries "Time.h" and "TimeAlarms.h".

In the requirements, it says: "Time does not require any special hardware. Internally, Time depends upon Arduino's millis() function to keep track to elasped time."

Considering Arduino's millis() rollover after 49.7 days, how can I ensure these lybraries are handling the rollover well?

I don't think that waiting 49.7 days to test it is the better way.

As long as the date is before 2038, and your code calls one of the time functions at least once every 49 days, rollover won't affect you.

Internally the library uses Unix epoch time. Every time you call a function it checks to see if 1 or more seconds have past since the last time it was called and then updates the epoch time accordingly. Only for this check it uses millis(). And in only checks the difference between the last call's millis-value and the current millis-value, and rollover has no effect on time differences (as long as they are less that 49 days).


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

My Arduino code is

int sensorValue;

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

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

On my serial monitor, I am getting values like

307
277
289
282
283
283
260
248
265
285
308
278
278
315
321
316
327

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

That is what I would expect to see with one of these sensors.

I'm not sure on the wiring, I think you may be wrong.  Have a read of http://playground.arduino.cc/Main/MQGasSensors#readdatasheet and see if you agree.

Did you leave the sensor to warm up?  It takes a few minutes (from memory) and until its warm it won't give you a proper reading.

An MQ4 should be able to detect Methane, butane and propane, so was your lighter using on of these gasses?  When it does detect the target gas, the number will go up, and stay up for a while.

Another thing you can try is blowing on the sensor, the results will vary depending on what you have been eating, but it should shift one way or another.

If it still doesn't work then buzz out your connections, just to triple check, and re-read the manual.


Arduino PWM Frequency - Pros and Cons of Modifying I am interested in using an Arduino Uno to produce an analog signal by running PWM through an RC low-pass filter.

I'll be controlling a highly dynamic object and need a clean voltage signal to avoid instabilities.  Per this calculator on RC designs, it's suggested that one strategy to reducing voltage ripple is to increase the PWM frequency.

With PWM configured to a default of 980Hz for pins 5 and 6, and PWM of 490Hz for the remaining pins, I've decided that this will create too much voltage ripple for my filter.  I've found resources that describe how to configure the registers to increase the PWM frequency rather drastically.

My question is very simple: Are there any disadvantages to using a higher frequency PWM?  Why is the default set to be so slow?

Thank you!

A PWM frequency of 490Hz means a period of approximately 2.041ms. This allows a high period of 2ms, which is the maximum pulse length required by a large number of inexpensive servos. Obviously if your design uses no servos then this is not a consideration.

Timer 0 itself is used for the various Arduino timing functions (delay(), millis(), etc.), so if you change the frequency used for timer 0 then those functions will no longer have accurate results.


arduino + GSM/GPRS SIM 900A cannot able to read a message Here I am using Arduino uno and GSM sim900A, I want to read sms from sim900A. But i am trying to read message, it is showing the empty values. I tried different methods, but no use. Here I have added my script. Please help me.

#include <avr wdt.h="">
String phoneSMS = "+91xxxxxxxxxx";
String messageTxt;
void setup()
{
Serial.begin(9600);
delay(60000);
srl_msg();
}
String srl_msg()
{
Serial.println("AT+CMGF=1\r");
delay(1000);
Serial.println("AT+CNMI=2,2,0,0,0");
delay(1000);
Serial.println("AT+CMGL=\"ALL\"\r"); // to read ALL the SMS in text mode
delay(1000);
char txtmsg2[100]; // AT command output
String date = readSerial(txtmsg2);
String value = date.substring(1, 50);
messageTxt = "Internal - Heart Beat;";
messageTxt.concat(value);
Serial.println(value);
SendSMS(messageTxt);
}
void loop()
{
}
void SendSMS(String message)
{
Serial.print("at+cmgf=1\r");
delay(1000);
Serial.print("at+cmgs=\"");
Serial.print(phoneSMS);
Serial.println("\"");
delay(1000);
Serial.println(message);
delay(1000);
Serial.print((char)26);
delay(15000); // AAN
}
String readSerial(char result[])
{
int i = 0;
while (Serial.available() > 0)
{
char inChar = Serial.read();
if (inChar != '\r')
{
result[i] = inChar;
i++;
}
}
return result;
}

output is look like this:
AT+CMGF=1

OK

AT+CNMI=2,2,0,0,0

OK
AT+CMGL="ALL"

OK

Check you sim card inbox. I also had the same problem, and it turns out the sim card sms inbox capacity is full.
You can also try to use another library, here is one of them


Can I use a DAC with an L293D driver? I'm trying to provide analog control to a Bluetooth controlled car, via Arduino. I have joystick app (as the pot).
It send values between 0 to 255
So I'm thinking... Whether this flow down here  will work?

Joystick app --> Bluetooth Rx --> DAC --> Vs pin of L293D. Or motor?

Is Arduino required at all? Or is the serial word enough to translate into voltage via DAC?

No, you cannot. A DAC cannot provide enough current to either directly drive a motor or to power a motor driver (which is basically driving the motor directly through a switch anyway).

A motor driver requires a PWM signal to rapidly switch a high current source on and off to set the motor speed.

You could feed the DAC output into the input of a voltage-to-PWM converter chip which would then feed the motor driver's EN pin, but that is pretty pointless when you could just use a small microcontroller to receive the digital speed value and directly generate a PWM signal.

After all, that is the kind of job that small microcontrollers are designed for...


Extract .hex from ATtiny45 using Arduino As it is possible to program a ATtiny45 using Arduino as ISP Programmer, is there a way to backup an ATtiny45 program to a .hex file using Arduino?

Assuming the lock bits on the device haven't been set, sure. Simply prepare the Arduino for ArduinoISP, hook up the ATtiny45, and perform a read using AVRDUDE instead of a write (-U flash:r:foo.hex:i).


How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable? How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?

Android devices usually don't have a USB host: they expect to be connected to some smarter device like your computer. Same goes with Arduino.
For this reason Arduino made the Mega ADK (that means Accessory Development Kit).

Mega ADK and Due act as USB hosts and can be connected directly to your Android phone. If you already have a board, another option is to get a USB host shield to add USB host capababilities.

Your sketch will tell the phone what kind of accessory application it is and your phone will download the appropriate application from the store.

There is a book about connecting Arduino to Android.


cannot show free space of SD card with arduino nano I'm using a nano v3, the SD module and a 64GB microSD card.
Writing to the card works fine.
But I can't print out the free space left on the card.

I'm using this code:

/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
//#include <SD.h>
#include "SdFat.h"
SdFat SD;

#define csPin 4
File myFile;
SdFat sd;

int startMillis;
int duration;

uint32_t freeKB;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(csPin)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  myFile = SD.open("test.txt", FILE_WRITE);

  for (int j = 0; j < 1000; j++) {
    myFile.println(j);
  }
  myFile.close();
  startMillis = millis();
  ShowFreeSpace();
  duration = millis() - startMillis;
  Serial.print("Took ");
  Serial.print(duration);
  Serial.println("ms to calculate");
  delay(1000);
}

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = sd.vol()->freeClusterCount();
  lFreeKB *= sd.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}

What am I doing wrong?

You have two instances of SdFat class. In setup() you begin the SD and for free space you try to use sd. Delete SdFat sd; line and in ShowFreeSpace use SD.vol().


How many sensors can an ARDUINO UNO support? I'm doing a project that requires me to use 4 different sensors, namely a load sensor, RFID tag sensor, 2 IR sensors and a Hall effect sensor on one Arduino Uno board, along with a L293D motor expansion shield. Is this possible? or will there be some issue with doing this?

A arduino can theoretically use more sensors than it has bits of storage based on your lowlever programming and algorithmic skills.
however since most people tend to only use one connection per arduino pin and mostly basic c++ and arduino instructions this is a lot lower. some people also use a shift register to easily increase the port amount.
for your project it depends you can use your ir sensors using one pin each for most ir sensors. the load sensor can be used on a single analog pin if you make it yourself, most prebought ones support ic2 which is really great for your case as I will describe later however you might not need it. hall effect sensor needs one I/O pin, rfid shield seems to use around 5 I/O pins for the average module, and the motor shield you plan to use the lose module which controls 2 motors uses up to 6 I/O pins, the arduino shield might contain more than  L293D motor driver so it might use up more pins, also you should make sure the specific shield edition supports connecting pins to the unused I/O you often have to solder those connections yourself.
so assuming you use all I/O connections and no ic2 where you use one  L293D motor driver board and not a shield(or a shield with pin redirection you should need around:
14 I/O pins from which 1 to a max of 3 are Analog pins(the load and ir ones might be analog based on the type).
however you should check the ports and layout of your actual hardware since this all can differ based on what types you use.
might some of tour sensors use ic2(they have a sda and scl pin) than you need 2 pins on your arduino for all of them together as long as they don't have matching id's. see i2c like a computer network.
so you should be able to use it without a shift register since a arduino uno has 18 basic I/O pins assuming you don't use pin 1 and pin 2 due to the interference with the serial port. 6 of those 18 pins are analog ones. analog pins can be used like normal digital pins. if you use i2c you should also take 2 pins of so you would have 16 usable pins when you use i2c and serial. you can theoretically use 20 pins, but I would recommend not using pin 0 and 1 as for they can prevent your board from accepting a new scetch upload which might require more difficult ways of uploading and problems when using serial connection.


led chaser fill color effect Please help. I am learning a lot about Arduino. Most all in lightning. I am a newbie. I play with nano and LED ws2812 and use fastled library.

What ask is to make effect like fill effect. For example with larson scanner/chaser.

for (int i = 0; i<NUM_LEDS; i++)
{
  leds[i]=CRGB::Red;
  FastLED.show();
  leds[i]=CRGB::Black;
  delay(50);
}

From that code above how to make LED stop and lit up and loop again and stop and lit up.  I want every LED stop the LED lit up even LED looping start again from first LED. It like this:

  10000 01000 00100 00010 00001 10001 01001 00101 00011 10011 01011
  00111 10111 01111 11111

You need two counter for this, one to keep track of how far the LED bar is filled, and one about the current 'running' LED to eventually 'touch' the LEDs which are already moved to the right.

Every led (currentLed) will run from index 0 until the last filled index, while the last filled index is decreased with 1 after every loop.

(note: I haven't checked the code).

// Fill from the right, thus count backwards.
for (int filledLedIndex = NUM_LEDS; filledLed >= 0; filledLed--)
{
   // Now let a LED run from 0 upto filedLedIndex;
   for (int currentLed = 0; currentLed < filledLedIndex)
   {
      // Make previous LED black
      if (currentLed > 0)
      {
         leds[i - 1] = CRGB::Black;
      }

      // Make current LED red
      leds[i] = CRGB::Red;

      // Show.
      FastLED.show();
      delay(50);
   }
}

// Clear all LEDs.
for (int led = 0; led < NUM_LEDS; led++)
{
    leds[i] = CRGB::Black;
}

FastLED.show();
delay(50);


MQTT and IR code Raw I want to upload/pubish RAW IR Code to MQTT server received through my ESP8266. I have received the following RAW IR code from the Television using the IR receiver sensor:

RAW IR CODE = {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450,
  650,500, 600,500, 600,500, 600,550, 550,1700, 550,
  1650, 600,1650, 550,550, 600,500, 600,550, 550,550,
  600,500, 600,550, 550,1650, 600,550, 550,550, 600,500,
  600,550, 550,550, 600,500, 600,1650, 600,500, 600,1650,
  550,1700, 550,1650, 600,1650, 550,1650, 600,1650, 600
}

I want to create a new variable with the following structure:

value = RAW IR CODE+";" + "ESP8266-01"(This is the ID of the esp8266)

value =  {
  4650,4250, 700,1550, 650,1550, 700,1550, 650,450, 650,500,
  600,500, 600,500, 600,550, 550,1700, 550,1650, 600,1650, 550,550,
  600,500, 600,550, 550,550, 600,500, 600,550, 550,1650, 600,550,
  550,550, 600,500, 600,550, 550,550, 600,500, 600,1650, 600,500,
  600,1650, 550,1700, 550,1650, 600,1650, 550,1650, 600,1650,
  600
}; ESP8266-01

I am unsure: which data type do I need to save the variable value so that it can later be retrieved/subscribed and sent to another IR sender using irsend.sendRaw, because I want to split the variable "value" into 2 parts after receiving it, the ID and the RAW code. After getting the RAW code, I want to use the irsend.sendRaw(RAW CODE, length of RAW , 38).

Could someone help me?

My attempts:
At first I tried to save it as a string, so that it can be retrieved and separated for irsend.sendRaw. However I am unable to compile it.

This is the code which I used to upload:

      /*
     * IRremoteESP8266: IRServer - MQTT IR server
     * An IR LED must be connected to ESP8266 RX port (GPIO-3)
     * An IR receiver to GPIO 0
     * used library:
     * https://github.com/markszabo/IRremoteESP8266
     */
    #include <WiFiClient.h>

   #include <ESP8266WiFi.h>

 #include <IRremoteESP8266.h>
    #include <PubSubClient.h>
    int RECV_PIN = 0; //an IR detector/demodulator is connected to GPIO pin 0

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    const char* ssid = "MY-SSID";
    const char* password = "MY-WIFI-PSK";

    const char* topicRaportPrefix = "esp8266/02/info/";
    const char* topicSubscribe = "esp8266/02/sender/#";
    const char* topicPrefix = "esp8266/02/";

    const char* mqtt_server = "10.10.10.10";
    const char* mqtt_user = "mqtt_user";
    const char* mqtt_pass = "mqtt_pass";

    String clientName; // MQTT client name
    char message_buff[100];

     void dump(decode_results *results) {
        const int count = results->rawlen;
          Serial.println(c);
          c++;
          Serial.println("For IR Remote ");
          for (int i = 1; i < count; i++) {

          if ((i % 2) == 1) {
            Serial.print("+");
            Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
        uint16_t  raw_ir_code[count] = results->rawbuf[i]*USECPERTICK;
            client.publish( "esp8266/02/sender", raw_ir_code);

After doing the changes proposed, I still get an error in compiling:

  no matching function for call to 'PubSubClient::publish(const char [18], uint16_t [(int)count])'

First create a topic and include the ESP8266 ID. Do not make it part of the published value.

Second publish the raw data as-is, uint16_t raw_ir_code[RAW_IR_CODE_MAX]. The alternative is to convert to string (characters). But if the subscriber has the same architecture (interpretation of data), there is no need to convert it to string and back. Simply publish the raw data as it is.

You will need to cast the raw_ir_code vector to the appropriate type for the MQTT publish call.

Cheers!


Is it safe to power an MQ-7 gas sensor with a 9V D.C supply? I'm looking for a portable power source for an MQ-7 gas sensor. According to my research - it needs 5V D.C power with at least 0.3A of current. I'm not really good with electronics so I need to know if I can use a 9V battery instead which produces 0.5A. Will the cell damage my sensor and if it does may you please recommend me something else.

You can, but you will have to reduce the voltage to the 5V the sensor needs, otherwise you will blow up the sensor.

To that end you require a voltage regulator. You can use a linear regulator like the Arduino has on-board, but they are very wasteful of power and will dissipate the excess 4V of electricity as heat.

Better would be to use a switching regulator (commonly and cheaply available on eBay and other sites) to step the voltage down to 5V more efficiently.


Android phone can't get ESP8266WebServer page if Content-Length > 1460 I uploaded the following sketch to my ESP8266:

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);
String toServe;

void serveShortString() {
    server.send(200, "text/plain", "short string!");
}

void serveLongString() {
    server.send(200, "text/plain", toServe);
}

void setup() {
    WiFi.softAP("test");

    // fill string to serve:
    toServe.reserve(3000);
    for(int i=0; i<150; i++) toServe += "1234567890123456789\n";

    server.on("/long", serveLongString);
    server.on("/short", serveShortString);
    server.begin();
}

void loop() {
    server.handleClient();
}

It serves a short message on /short and a long message (3000 chars) on /long.

The /short page works everywhere: Windows, Desktop Linux (Fedora) and Android.
The /long page, on the other hand, only works on Windows and most of the time on desktop Linux. It never works on Android. I tried two phones.

I captured the network traffic on my Android phone using tPacketCapture. This is the result:

When trying to get /short, everything works fine. When trying to get /long, only the header comes through but the content never arrives. As I said, everything works fine on Windows and (most of the time) on Desktop Linux. Any idea what's going wrong?

The solution is to add the following line to platformio.ini:

build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY

I noticed that the same sketch works without a problem when building with the Arduino IDE, so I checked the differences in building with platformio and the Arduino IDE.

Turns out the relevant difference is that the Arduino IDE uses lwIP 2 by default, while platformio uses 1.4, which seems to have this bug (the same bug appears when using the Arduino IDE with lwIP 1.4).

The build flag above tells platformio to use lwIP v2.


How to wake up Arduino with an rtc? I am doing a data logger with an Arduino Mega2560 and I want to use a code to make it sleep when no measure is needed and wake it up with an RTC when time comes. The reason I want this is because I intend to run the code on a Pro Mini later so I need to save as much energy as I can. I am able to put the arduino to sleep using the alarm interrupt when a minute is passed but it doesn't wake up from sleep afterwards.

Here is the code I am using:

#include <Wire.h>
#include <RtcDS3231.h>
#include <avr/sleep.h>

const byte interruptPin = 2;
volatile bool alarm = 0;
volatile byte counter = 0;

RtcDS3231<TwoWire> rtcObject(Wire);

void setup() {

  Serial.begin(9600);
  Serial.println("Initialisation");
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);

  rtcObject.Begin();

  RtcDateTime timestamp = RtcDateTime(__DATE__, __TIME__);
  rtcObject.SetDateTime(timestamp);

  rtcObject.Enable32kHzPin(false);
  rtcObject.SetSquareWavePin(DS3231SquareWavePin_ModeAlarmOne);

  DS3231AlarmTwo alarm2(
    0,
    0,
    0,
    DS3231AlarmTwoControl_OncePerMinute);

  rtcObject.SetAlarmTwo(alarm2);
  rtcObject.LatchAlarmsTriggeredFlags();

}

void loop() {
  if (alarm == true){
    handleAlarm();
    if (counter == 1){
      mesure();
      counter = 0;
      delay(100);
      sleepNow();
    }
  }
}

void handleInterrupt() {
  alarm = true;
  counter ++;
  Serial.println(counter);
}

void handleAlarm() {
  alarm = false;
  rtcObject.LatchAlarmsTriggeredFlags();
}

void mesure(){
  RtcDateTime timestamp = rtcObject.GetDateTime();

  Serial.print("time interrupt at: ");
  char time[10];

  sprintf(time, "%d:%d:%d",
          timestamp.Hour(),
          timestamp.Minute(),
          timestamp.Second()
         );
Serial.println(time);
}

void sleepNow() {
  Serial.println("Entering sleeping");
  delay(100);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // sleep mode is set here
  sleep_enable();                         // enables the sleep bit in the mcucr register
  attachInterrupt(digitalPinToInterrupt(interruptPin),wakeUpNow, FALLING);  // use interrupt 0 (pin 2) and run function
  sleep_mode();                           // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

  sleep_disable();         // first thing after waking from sleep: disable sleep...
  detachInterrupt(digitalPinToInterrupt(interruptPin));      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
Serial.println("Woke up");
delay(100);
}

I want to understand how to wake it up properly so I can later make it sleep first in the loop and wake it up only if an interrupt is detected from the rtc.

Thank you for your help !

If you use the DS3232RTC library then you can setup an alarm which is like an alarm. I have put a good tutorial on how to do that below.
https://thekurks.net/blog/2018/2/5/wakeup-rtc-datalogger
There is also other threads on arduino.cc you should check out. They might have additional work-arounds.
https://forum.arduino.cc/index.php?topic=333654.0
https://forum.arduino.cc/index.php?topic=99588.0