text:
error compiling for board node MCU 1.0
Arduino: 1.8.9 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Serial, 115200, 4M (3M SPIFFS)"
In file included from C:\Users\Priyaranjan Tiwari\Documents\Arduino\007mcu_php\007mcu_php.ino:3:0:

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:84:9: error: 'WiFiClient' does not name a type

         WiFiClient & getStream(void)  __attribute__ ((deprecated)) ;

         ^

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:85:9: error: 'WiFiClient' does not name a type

         WiFiClient * getStreamPtr(void);

         ^

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:97:9: error: 'WiFiClient' does not name a type

         WiFiClient * _tcp;

         ^

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:98:9: error: 'WiFiClientSecure' does not name a type

         WiFiClientSecure * _tcps;

         ^

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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

2.0.0 is a very old version from 2015. the ESP8266HTTPClient.h then expected HTTPESP8266WiFi.h included before it in the sketch as you can see it in examples


text:
I need help in designing a circuit to connect an Arduino MEGA and a CD-Pickup Reader/Writer
I'm trying to use the IR source and detector of the CD Pickup reader/writer (KSS-213C) along with the lens focussing/tracking system. I want to control them using an Arduino MEGA. So since I will be needing one constant source for the diode, I will connect it separately to a source, not to the Arduino. Since this is a sensitive device, I read that you need to have constant current sources and so on. Now, I'm new to designing circuits of my own, I found this picture in an article, but it is for a DVD writer. Could someone tell me if I could use the same circuit with some modifications or should I try something else. Now note that my main output is that of the IR sensor that my Arduino would read.

I don't know how to answer most of your question, but one caution. The relay in that circuit should either be a "digital" relay that's separately powered and designed to be controlled with a CMOS logic signal, or you need to drive it using a power transistor protected with a "flyback diode". (Inductive loads like relay coils have "back EMF" that will destroy solid state components like transistors or Arduinos.)

@DuncanC, there was a circuit given in the question of this link: https://electronics.stackexchange.com/questions/278887/how-to-determine-the-operating-voltage-and-current-of-a-laser-diode. Can I use the same instead of the LM317-Constant Current Source circuit from my question?
By the way, I'm sorry I don't know if my relay is a digital one. I'm using a HE-LQC3FC Relay, would that work?

source: Stack Exchange

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

sort: votes


text:
DS18B20 with only OneWire library
Peter Scargill found a way to use a DS18B20 temperature sensor only using the OneWire library, and it's amazing how blazing fast it is! (It's an old article from 2013.)
#include <OneWire.h>

int16_t dallas(int x,byte start) {
  OneWire ds(x);
  byte i;
  byte data[2];
  int16_t result;
  do {
    ds.reset();
    ds.write(0xCC);
    ds.write(0xBE);
    for (int i = 0; i < 2; i++)
      data[i] = ds.read();
    result = (data[1] << 8) |data[0];
    result >>= 4;
    if (data[1]&128)
      result |= 61440;
    if (data[0]&8)
      ++result;
    ds.reset();
    ds.write(0xCC);
    ds.write(0x44, 1);
    if (start)
      delay(1000);
  } while (start--);
  return result;
}

void setup () {
  dallas(A0,1);
}

void loop () {
  float currentTemp = dallas(A0, 0);
}

The problem is the accuracy; he converts float to int to get an accuracy of 1°C and it's working just fine.
How can I get an accuracy of 0.5°C (or 0.2°C) using this semi library?

Which is the pin of DS18B20? i dont understand

Actually he isn't really converting float to int. He never uses float since he doesn't need it. The datasheet of the DS18B20 shows at page 6 how the data is formatted:

The 4 highest bits just resemble the sign bit 11.
The first digit with full degrees is bit 4. Every bit below that has values below 1°C

So the data bytes 0b1111100001010000 will represent a temperature of -123°C and 0b1111100001011000 -122.5°C.
The author from the link then shifts this data 4 bits to the right, so that all bits representing values under 1 vanish. You can convert the received value per hand to float by also using this.
int16_t whole_degree = (result & 0x07FF) >> 4;
float temperature =
whole_degree +
0.5 * ((data[0]&0x8)>>3) +
0.25 * ((data[0]&0x4)>>2) +
0.125 * ((data[0]&0x2)>>1) +
0.0625 * (data[0]&0x1);
if (data[1]&128)
  temperature *= -1;

As float does not have the same structure as the data, we need to convert it. So I first calculate the number of whole degrees analog to your code. Then I add this up with the values of the lowest 4 bits. ((data[0]&0x8)>>3) and its siblings will be 1, when the corresponding bit is set, and 0, if not.
So you get the full precision of the sensor (12 bits). Please note that for this to work, you should not configure the sensor to less resolution. In that case you would have to ignore the corresponding lowest bits. But the sensor is in 12 bit mode at power up anyway and your code does not configure it otherwise.
Note: I'm unsure about the line result |= 61440; in the original code. This sets the 4 highest bits of a 16 bit value to 1. I don't see why this should be correct here, since a normal 16-bit integer does only have 1 sign bit. In my understanding the original code would lead to false readings (way off), when reading temperatures below zero. I instead simply multiplied the resulting temperature with -1.
The whole code would look like this (I also added the statement for printing out the pure received data as binary, as I requested it in my comment. These statements are currently commented out):
#include <OneWire.h>

float dallas(int x,byte start) {
  OneWire ds(x);
  byte i;
  byte data[2];
  int16_t result;
  float temperature;

  do {
    ds.reset();
    ds.write(0xCC);
    ds.write(0xBE);
    for (int i = 0; i < 2; i++)
      data[i] = ds.read();
    result = (data[1]<<8) |data[0];
    // Here you could print out the received bytes as binary, as requested in my comment:
    // Serial.println(result, BIN);
    int16_t whole_degree = (result & 0x07FF) >> 4; // cut out sign bits and shift
    temperature = whole_degree +
    0.5 * ((data[0]&0x8)>>3) +   // 0.5    = 2^-1
    0.25 * ((data[0]&0x4)>>2) +  // 0.25   = 2^-2
    0.125 * ((data[0]&0x2)>>1) + // 0.125  = 2^-3
    0.0625 * (data[0]&0x1);      // 0.0625 = 2^-4
    if (data[1]&128)
      temperature *= -1;
    ds.reset();
    ds.write(0xCC);
    ds.write(0x44, 1);
    if (start)
      delay(1000);
  } while (start--);
  return temperature;
}

void setup {
  // Adding Serial.begin(9600); for printing the received bytes here
  //Serial.begin(9600);
  dallas(A0,1);
}

void loop {
  float currentTemp = dallas(A0, 0);
}

i implanted that into the code and reading is like around 470 degree!

Mhh, can you output the pure reading in binary and write this into a comment. You can do this via serial by Serial.println(result, BIN);

i think maybe my implantation is wrong, can you please embed that code into my code or provide some instruction to where i should paste those lines?

"'result' was not declared in this scope"

@newbie I added a not-tested implementation to my answer. You can try it. There are also the statements for printing the pure reading in binary. These statements just have to be uncommented in the case, that this code is not working correctly

thank you, it says:
"'result' was not declared in this scope" when i want to do Serial.println(result, BIN); in void loop/setup. and temperature is still above 400...

Yes, surely it says that in loop, since you should not put it there, but into the function dallas(). But you can just use my provided code an uncomment the lines with Serial in dallas() and setup()

111001010 458.00

@newbie you asked me to look at this question, but I think this answer explained it well (and upvoted it)... or do you have something specific for me to look at?

@MichelKeijzers yes thank you, chris explained it well but the temperature reading isn't right. thought maybe you have an idea about it...

@newbie I have corrected my code. The sign thing didn't work as I thought it would, so I now did it simply by multiplying with -1. Also I included a bit to to cut out the sign bits from whole_degree before shifting, so that the 1's there cannot make garbage values. Please again check, if this works for you. I hope, that it is correct now. I tested the calculations with a spare Arduino Nano and a mockup value (The one you posted as comment should result in 28,625°C)

@chrisl thanks but the result is still the same for me! 111000011 451.00  very strange!

@newbie It's more efficient to follow chrisl's fix since he is at the correct answer almost or already, instead of me starting to dive in this problem.

@MichelKeijzers thanks for checking in man, really appreciate it.

@chrisl i copy/pasted the exact code you posted and i'm just doing this two prints: Serial.println(result, BIN); and Serial.println(dallas(A0,0));, why i'm still getting this 111000011 451.00  at the output!

I will investigate again

@chrisl i'd buy you a drink if i knew you in real world, you're such a nice gentleman.

@newbie you're welcome ... but all credits are for chrisl

I think I have found the problem facepalm I didn't change the return statement of the function. It still returned result, but the real temperature is in the variable temperature. I'm changing this now

Comments are not for extended discussion; this conversation has been moved to chat.

Why not rewrite the dallas() function so that it returns a float?
#include <OneWire.h>

OneWire ds(A0);

float dallas(OneWire& ds, byte start = false) {
    int16_t temp;
    do {
        ds.reset();
        ds.write(0xCC);
        ds.write(0xBE);
        ds.read_bytes((uint8_t*) &temp, sizeof(temp));
        ds.reset();
        ds.write(0xCC);
        ds.write(0x44, 1);
        if (start) delay(1000);
    } while (start--);
    return (temp * 0.0625);
}

void setup {
  dallas(ds, true);
}

void loop {
  float currentTemp = dallas(ds);
}

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


text:
Arduino Uno - Stepper motor not working with button
I am completely new to Arduino, and all sorts of hardware and software. I have a stepper motor, which I want to rotate by a number of rotations when I press a button, and then go backwards by a number of rotations when pressed again. I'm not getting any errors with the code, but it does not seem to do what I want. Before adding the button, the stepper motor worked fine, so I don't think it's malfunctioning. When the button is pressed, the LEDs on the H-bridge flicker, but there's no response at all from the motor. I don't know if it's a problem with the code or the set up.
#include <Stepper.h>
const float STEPS_PER_REVOLUTION = 4096;
const float GEAR_REDUCTION = 4;
const float TOTAL_STEPS = STEPS_PER_REVOLUTION * GEAR_REDUCTION
int StepsRequired = 16384;
int switchPin = 7;
boolean current = LOW;
boolean last = LOW;
boolean isOpen = LOW;
Stepper steppermotor (STEPS_PER_REVOLUTION, 8, 10, 9, 11);

void setup() {
  pinMode(switchPin, INPUT);
}

boolean debounce(boolean inLast) {
  boolean inCurrent = digitalRead(switchPin);
  if(inLast != current) {
    delay(5);
    inCurrent = digitalRead(switchPin);
    }
  return inCurrent;
}

void garageAction(float factor){
  StepsRequired = TOTAL_STEPS*factor;
  steppermotor.setSpeed(1000);
  steppermotor.step(StepsRequired);
  if (isOpen == LOW) {
    delay(3000);
  } else if (isOpen == HIGH) {
    delay(5);
  }
}

void loop() {
  current = debounce(last);

  if (current == HIGH && last == LOW && isOpen == LOW) {
    garageAction(2);
    isOpen = !isOpen;
  }

  if(current == HIGH && last == LOW && isOpen == HIGH) {
    garageAction(-2);
    isOpen = !isOpen;
  }
}

I would really appreciate any help with this - as mentioned, I'm completely new to any sort of hardware and software, and I'm also under time pressure to get this done, so I'd really appreciate any help in getting this solved. I could just be missing something really silly, but I'm completely lost.
Thanks in advance

all this program will do is constantly alternate isOpen and call garageAction. This will happen so fast that nothing will actually happen in the real world.Now that I've reformatted your code, perhaps you can reconsider the other two clauses in your if statements relating to current and last. That is untile the debounce function sets current to be low - after that nothing will happen until current is reset to HIGH.


text:
Data Structures and Color Data Types in FastLED
So i'm doing something wrong but i don't exactly know what and hope somebody can give me a quick pointer:
I declared a starting color for my fastled animation:
CHSV startcolor(100, 255, 255);

and then a data structure
typedef struct {

int currentBrightness = 0;

int targetBrightness = 0;

int updown;

CHSV color = startcolor;

} blinkblink, *pblinkblink;

So basically my idea is to have every LED be represented with this data structure to control brightness within an anmation. However if i now set
CRGB leds[NUM_LEDS];

and do something like
for (int i = 0; i < sizeof(myLeds); i++) {

leds[i] = myLeds[i].color;

}

FastLED.show();

nothing happens. I'm pretty sure, that this is because i'm somehow not understanding the data type thing. What am i doing wrong?

you did not use the name of the struct blinkblink .... http://www.cplusplus.com/doc/tutorial/structures/

Where have you defined the myLeds array?

Your second mistake was not observing the complete and reproducible parts of Minimal Reproducible Example. Once you fix that error, others will have a chance to help you with your first error (i.e. why doesn't my code work?)


text:
Sound sensor dont work in whole project
When I put this code only on arduino, sound sensor works:
int soundSensor=A1;
int LED=5;

boolean LEDStatus=false;

void setup() {

Serial.begin(9600);

  pinMode(soundSensor,INPUT);
  pinMode(LED,OUTPUT);

}

void loop() {

  int SensorData=analogRead(soundSensor);

  if(SensorData>600){

    if(LEDStatus==false){
        LEDStatus=true;
        digitalWrite(LED,HIGH);
    }
    else{
        LEDStatus=false;
        digitalWrite(LED,LOW);
    }

    delay(50);
  }

 }

When I upload same code in big project, even when I upload little part of project on arduino, sound sensor doesnt work.. whats happening?
I checked soundsensor with everything.
I leave whole code till void loop ()  and sound sensor works.
But if I put even delay(1000) in void loop after, sound sensor doesnt work.
Also, if I put every other thing : servo, dht, lighting in code with sound sensor.. with or without delay... sound sensor doesnt work!
Thanks
Whole code:
#include <Servo.h>
#include "DHT.h"
#include <SPI.h>
#include <MFRC522.h>
#include <Wire.h>

#define SERVO_PIN 8
#define SS_PIN 10
#define RST_PIN 9
#define lightingOutput A2
#define ldrPin A0
#define PIR 7
#define ledGrn 6
#define heatingOutput A3
#define coolingOutput A4
#define DHTPIN 2
#define DHTTYPE DHT11

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create instance of our reader
Servo myservo; // Create instance of our motor /// create servo object to control a servo
DHT dht(DHTPIN, DHTTYPE);     //// Initialize DHT sensor for normal 16mhz Arduino

int pos;
int light;
float h, t;
int soundSensor=A1;
int LED=5;
boolean LEDStatus=false;
const int buzzer = 4;
long zadnje_ocitanje=0;

void setup()
{

  Serial.begin(9600);
  dht.begin();
  SPI.begin();
  mfrc522.PCD_Init();
  myservo.attach(SERVO_PIN);
  myservo.write(0);

  pinMode(heatingOutput, OUTPUT);
  pinMode(coolingOutput, OUTPUT);
  pinMode(ledGrn, OUTPUT);
  pinMode(soundSensor,INPUT);
  pinMode(LED,OUTPUT);
  pinMode(lightingOutput, OUTPUT);

  zadnje_ocitanje=millis();
}
void loop() {

  Serial.println("\nHOME AUTOMATION\n");

  readSOUND();
  readRFID();
  readDHT();
  readLIGHT();

delay(1000);

}

////////////////////////////////////////////
void readRFID()

{
  //Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent() ) {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial() ) {
    return;
  }
  // If a card is detected, execute the following:
  Serial.println("Time to open");
  // Print the card's ID
  String content = "";
  byte letter;
  for ( byte i = 0; i < mfrc522.uid.size; i++ ) {
    content.concat(String(mfrc522.uid.uidByte[i], HEX));
    if ( i < mfrc522.uid.size - 1 ) content += "-";
  }
  content.toUpperCase();
  Serial.println();
  Serial.println("UID tag :'" + content + "'");

  if (content == "C0-E5-86-25") {

    Serial.println("Authorized access");
     digitalWrite(ledGrn, HIGH);

    for (pos = 0; pos <= 90; pos += 1) {
      myservo.write(pos);
      delay(25);
    }
    for (pos = 90; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(70);
      digitalWrite(ledGrn, LOW);
    }
  }
  else {
    Serial.println("Access Denied");
      tone(buzzer, 1000, 6000);
  }
}

//////////////////////////////////////////////////////

void readDHT()
{

  h = dht.readHumidity();
  t = dht.readTemperature();
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.println();

  if (t < 18) //if temperature is less than 18 celcius
  {
    digitalWrite(heatingOutput, HIGH);
    Serial.print("Heating activated\n");
  }
  else
  {
    digitalWrite(heatingOutput, LOW);
  }

  if (t > 22) //if temperature is more than 22 celcius
  {
    digitalWrite(coolingOutput, HIGH);
    Serial.print("Cooling activated\n");
  }
  else
  {
    digitalWrite(coolingOutput, LOW);
  }
}

//////////////////////////////////////////////////////

void readLIGHT()
{

 int value_pir = digitalRead(PIR);
 light = map(analogRead(ldrPin) , 0 , 1024 , 1 , 100);

  Serial.print("Lighting percentage: ");
  Serial.print(light);
  Serial.print("\nMotion detector: ");
  Serial.print(digitalRead(PIR));

if ((millis()-zadnje_ocitanje)>6000)
  {

  if ((light < 50) && ( value_pir == HIGH) )
  {
    digitalWrite(lightingOutput, HIGH);
    Serial.println("\nLighting ON");
  }
  else
  {
    digitalWrite(lightingOutput, LOW);
    Serial.println("\nLighting OFF");
  }
    zadnje_ocitanje=millis();
  }
}

//////////////////////////////////////////////////////////////

void readSOUND()
{
  int SensorData=analogRead(soundSensor);

  if(SensorData>600){

    if(LEDStatus==false){
        LEDStatus=true;
        digitalWrite(LED,HIGH);
    }
    else{
        LEDStatus=false;
        digitalWrite(LED,LOW);
    }

    delay(50);
  }

}

See his post on Arduino.cc for additional information before you go too far.  https://forum.arduino.cc/index.php?topic=626641.0

You found on that thread that your sound sensor does indeed work.  It's just that you have your threshold set wrong?  Put a line there to print the reading from the sensor.  Does it every go over 600?  We just found out on Arduino.cc that it doesn't.


text:
Remove Function at Preprocessor Time
I have a single function for debugging messages, used through all the project. When KEYDEBUG is defined as 1 or 0, the function is enabled or disabled as required.

#define KEYDEBUG 0

void debugging(int var){
   #if KEYDEBUG
   //Assert
   #endif
}

When checking the compiler, the variable var raises a warning -Wunused-parameter.
How should remove this warning just at this part of the project?
Or which other alternative for using debugging code and removing it from memory for production release?

In your case you do not use the entire body, so you can use a macro.
This way the code when KEYDEBUG is 0, will be like the complete function would not exist (except for the void cast, see below).
#include "assert.h"

#define KEYDEBUG 0

#ifndef KEYDEBUG
#define debugging(x) void(x);
#endif

void debugging(int var){
   assert(var);
}

void setup() {
  // put your setup code here, to run once:
  debugging(1);
}

The information below is for not using the function parameter, but keep the function (in case you have code in your function that also does something when KEYDEBUG is 0.
Unused attribute
The cleanest way I could find is using the unused attribute:
#if KEYDEBUG
   void debugging(__attribute__((unused)) int var){
      //Assert
#else
   void debugging(int var){
      //Assert
#endif
   }

or if you prefer better readability:
#if KEYDEBUG
   void debugging(__attribute__((unused)) int var){
      //Assert
   }
#else
   void debugging(int var){
      //Assert
   }
#endif

Cast to void
Less clean but does the job:
void debugging(int var){
   #if KEYDEBUG
      //Assert
   #else
      (void) var; // prevent unused parameter warning
   #endif
}

Macros/Parameter
It's not easy to remove the variable since it's used in a function and will be called from many places probably. You could maybe you use a macro but that gets messy soon.
This solution works, and afaik the compiler will optimize the code out (if not , it will cost very less anyway).

It is possible to remove absolutely the debugging function and its calls without touching the debugging calls?

Not fully, well in the macro I defined, the function call is replaced by a void cast, so this is not a function, and you don't have to touch the debugging calls.


text:
Header file or library to test i2c FRAM?
I found a header file to test a i2c eeprom 24LC256, but I used this to test my eeprom CAT24C32.The test sketch works fine. I modified the line BLOCKSIZE 8 because my eeprom have 32byte page write only.
I have also a FRAM MB85RC256V, I am wondering if can I use the same header to test the FRAM. I saw the command byte write are same like eeprom, but the page write have a different side of buffer, it says have 32Kbytes. Can I use it?
If I made a mistake please help me. Thanks very much!
Here the .h

#ifndef  EEPROM_ROUTINES
#define  EEPROM_ROUTINES

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif
#include <Wire.h>

#define BLOCKSIZE 8
#define I2CADDR 0x57
#define BLOCKSIZE_READ 30

template <class T>
uint16_t writeObjectSimple(uint8_t i2cAddr, uint16_t addr, const T& value){

      const uint8_t* p = (const uint8_t*)(const void*)&value;
      uint16_t i;
      for (i = 0; i < sizeof(value); i++){
            Wire.beginTransmission(i2cAddr);
                  Wire.write((uint16_t)(addr >> 8));  // MSB
                  Wire.write((uint16_t)(addr & 0xFF));// LSB
                  Wire.write(*p++);
            Wire.endTransmission();
            addr++;
            delay(5);  //max time for writing in 24LC256
      }
      return i;
}

template <class T>
uint16_t readObjectSimple(uint8_t i2cAddr, uint16_t addr, T& value){

            uint8_t* p = (uint8_t*)(void*)&value;
            uint8_t objSize = sizeof(value);
            uint16_t i;
            for (i = 0; i < objSize; i++){
                  Wire.beginTransmission (i2cAddr);
                        Wire.write((uint16_t)(addr >> 8));  // MSB
                        Wire.write((uint16_t)(addr & 0xFF));// LSB
                  Wire.endTransmission();
                  Wire.requestFrom(i2cAddr, (uint8_t)1);
                  if(Wire.available()){
                        *p++ = Wire.read();
                  }
                  addr++;
            }
            return i;
}

template <class T>
uint16_t writeObject(uint16_t addr, const T& value){
      const uint8_t* p = (const uint8_t*)(const void*)&value;

      Wire.beginTransmission(I2CADDR);
      Wire.write((uint16_t)(addr >> 8));        // MSB
      Wire.write((uint16_t)(addr & 0xFF));      // LSB

      //in the loop: counts the bytes we may send before
      //our block becomes full
      //but initialise it to the number of bytes up to the
      //next 16-byte aligned address
      uint8_t blockBytes = (addr/BLOCKSIZE + 1)*BLOCKSIZE - addr;
      uint16_t i;
      for (i = 0; i < sizeof(value); i++){
            if (blockBytes == 0){
                  //block is full;
                  Wire.endTransmission(); //dispatch the buffer
                  delay(5);
                  //restart new block
                  addr = (addr/BLOCKSIZE + 1)*BLOCKSIZE;
                  blockBytes = BLOCKSIZE;
                  Wire.beginTransmission(I2CADDR);
                  Wire.write((uint16_t)(addr >> 8));  // MSB
                  Wire.write((uint16_t)(addr & 0xFF));// LSB
            }
            Wire.write(*p++); //dispatch the data byte
            blockBytes--;     //decrement the block space
      }
      Wire.endTransmission();
      delay(5);   //required write delay 5ms
      return i;
}

template <class T>
uint16_t readObject(uint16_t addr, T& value){
      uint8_t* p = (uint8_t*)(void*)&value;

      Wire.beginTransmission(I2CADDR);
            Wire.write((uint16_t)(addr >> 8));        // MSB
            Wire.write((uint16_t)(addr & 0xFF));      // LSB
      Wire.endTransmission();

      //counts the bytes we may read before buffer is depleted
      uint8_t   blockBytes = 0;
      uint16_t  objSize = sizeof(value);
      uint16_t  i;
      for (i = 0; i < objSize; i++){
            if (blockBytes==0){
               //we need a new block
               blockBytes = BLOCKSIZE_READ;
               if (objSize < blockBytes) blockBytes = objSize;
               //get the new block
                Wire.requestFrom((uint8_t)I2CADDR, blockBytes);
            }
            if(Wire.available()){
                  //read a byte from buffer
                  *p++ = Wire.read();
                  blockBytes--;
            }
      }
      return i;
}

#endif

Here the skecth to test eeprom
#include <Wire.h>
#include "eeprom_routines.h" //definitions of the functions:
                             //writeObject, readObject,
                             //writeObjectSimple, readObjectSimple
#define BLOCK_OPERATIONS 0

#if BLOCK_OPERATIONS>0
  #define __WRITE__(ad, obj) writeObject(ad,(obj))
  #define __READ__(ad, obj) readObject(ad,(obj))
#else
  #define __WRITE__(ad, obj) writeObjectSimple(0x57,ad,(obj))
  #define __READ__(ad, obj)  readObjectSimple(0x57,ad,(obj))
#endif
#define MEM_ADDR_MULTI 3458

//This is the structure we write and read from EEPROM
class MyData{
      long result;
public:
      float  f1;
      float  f2;
      double f3;
      int    i1;
      long   i2;
      long   i3;
      bool  negative;

      long getResult(){
            return result;
      }
      long calcResult(){
            //makes a calculation with its data
            //and stores the result to a private variable
            long    i = (i2+i3)/i1;
            double  f = f3/(f1+f2);
            result = f/i;
            //round off
            result += result>0 ? 0.5 : -0.5;
            if (negative) result=-result;
            return result;
      }
      MyData() : result(0){   }
};

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

      MyData data[5];

      //data[0] - result should be 20
      data[0].i1 = 10;
      data[0].i2 = 150000;
      data[0].i3 = 350000;
      data[0].f1 = 0.5;
      data[0].f2 = 2.5;
      data[0].f3 = 3.0E+6;
      data[0].negative = false;

      //data[1] - result should be -40
      data[1].i1 = data[0].i1;
      data[1].i2 = data[0].i2;
      data[1].i3 = data[0].i3;
      data[1].f1 = data[0].f1;
      data[1].f2 = data[0].f2;
      data[1].f3 = 2*data[0].f3;
      data[1].negative = true;

      //data[2] - result should be 80
      data[2].i1 = data[0].i1;
      data[2].i2 = data[0].i2;
      data[2].i3 = data[0].i3;
      data[2].f1 = data[0].f1;
      data[2].f2 = data[0].f2;
      data[2].f3 = 4*data[0].f3;
      data[2].negative = false;

      //data[3] - result should be -20
      data[3].i1 = data[0].i1;
      data[3].i2 = -data[0].i2;
      data[3].i3 = -data[0].i3;
      data[3].f1 = data[0].f1;
      data[3].f2 = data[0].f2;
      data[3].f3 = data[0].f3;
      data[3].negative = false;

      //data[4] - result should be -2
      data[4].i1 = data[0].i1;
      data[4].i2 = -data[0].i2;
      data[4].i3 = -data[0].i3;
      data[4].f1 = data[0].f1*10;
      data[4].f2 = data[0].f2*10;
      data[4].f3 = -data[0].f3;
      data[4].negative = true;

      Serial.println ("Data before writing to eeprom");
      for (int i=0; i<5; i++){
            data[i].calcResult();
            Serial.print("data-"); Serial.print(i);
            Serial.print(": result = ");
            Serial.println(data[i].getResult());
      }
      Serial.print("Size of each object: ");
      Serial.println(sizeof(MyData)) ;

      Serial.println ("Writing data to eeprom");
      int memaddr = MEM_ADDR_MULTI;
      long t0 = millis();
      for (int i=0; i<5; i++){
            memaddr += __WRITE__(memaddr, data[i]);
      }
      long t1 = millis();
      Serial.print ("...writing finished. Elapsed time: ");
      Serial.println(t1-t0);
      delay(1000);

      Serial.println ("Reading data from eeprom");
      MyData read[5];
      t0 = millis();
      memaddr = MEM_ADDR_MULTI;
      for (int i=0; i<5; i++){
            memaddr += __READ__(memaddr, read[i]);
      }
      t1 = millis();
      Serial.print ("Time to read: "); Serial.println(t1-t0);

      for (int i=0; i<5; i++){
            Serial.print ("Read object: #");
            Serial.println(i);
            long storedResult = read[i].getResult();
            Serial.print ("  >stored result = ");
            Serial.println(storedResult);
            long newResult = read[i].calcResult();
            Serial.print ("  >recalculated result = ");
            Serial.println(newResult);
            if (storedResult== newResult &&
                  storedResult==data[i].getResult() )
                  Serial.println ("SUCCESS");
            else  Serial.println ("FAIL");
      }
}

void loop() {
}

Here the serial output of eeprom CAT24C32 test
Data before writing to eeprom
data-0: result = 20
data-1: result = -40
data-2: result = 80
data-3: result = -20
data-4: result = -2
Size of each object: 27
Writing data to eeprom
...writing finished. Elapsed time: 126
Reading data from eeprom
Time to read: 15
Read object: #0
  >stored result = 20
  >recalculated result = 20
SUCCESS
Read object: #1
  >stored result = -40
  >recalculated result = -40
SUCCESS
Read object: #2
  >stored result = 80
  >recalculated result = 80
SUCCESS
Read object: #3
  >stored result = -20
  >recalculated result = -20
SUCCESS
Read object: #4
  >stored result = -2
  >recalculated result = -2
SUCCESS

At Fujitsu's site is said

Furthermore, applications that have used other products with I2C interfaces, such as EEPROMs and microcontrollers, can now replace EEPROMs, with the new FRAM products

So you can use it without any modifications in your code.


text:
src folder in sketch structure and include library from subfolder
My Arduino/PlatformIO libraries folder
libraries
└── cleaner_robot
    └── TB6612_Dual
        ├── tb6612_dual.h
        └── tb6612_dual.cpp

I used this code to innclude it:
#include <TB6612_Dual/tb6612_dual.h>

But the compilation has errors like "undefinded variables, undefinded reference,...etc"
This is my sketch folder
Cleaner_Robot
└── src
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h

If i use this code, all is ok
#include "src/libs/TB6612_Dual/tb6612_dual.h"

So the question is how to include if header file is in a sub folder of a folder in libraries folder of Arduino/PlatformIO ?, i has searched for many things, but cant help.
I also read about src folder allowed in Arduino, but where can find an official announcement/manual for this structure ?, cant find much about this
Thanks  :)

You're using PlatformIO? Maybe you should ask on a PlatformIO forum?

https://www.arduino.cc/en/guide/libraries#toc5 -|- https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

I could include header files in subfolder after including root header file.
#include <TB6612_Dual.h>
#include <TB6612_Dual/tb6612_dual.h>

TB6612_Dual
└── src
    ├── TB6612_Dual.h << Add this empty file.
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h

Examples:

utils_asukiaaa/examples/string/string.ino
utils_asukiaaa/src/utils_asukiaaa/string.h
utils_asukiaaa/src/utils_asukiaaa/string.cpp
utils_asukiaaa/src/utils_asukiaaa.h


text:
RFduino device required for RFduino hex file
So I have been working trying to measure the velocity of a string attaches using Rfduino microcontroller.
I have downloaded all the library(based on https://www.youtube.com/watch?v=K0JiPQnrkHQ) and check the PCB all the connection via multimeter ( i have made the PCB, and assemble via Chineses manufacture). and connect PCB to my laptop via FTDI board as this;

When I compile the code it. It's compiled nicely. But when I try to download the code it says
RFduino device required for RFduino hex file

Does anyone had any experience with this sort of error message?
(this is my first question in this forum. I don't no this belong to hardware or software side)
EDIT:
I'm trying to program RFD22302 micro using RFD22121 USB shield and USB MicroB Plug Breakout board.
RFD22302
USB Development Kit-RFD22121
USB MicroB Plug Breakout
any help would be appreciated!
Thanks, Heaps!

https://crownstone.rocks/2014/03/05/rfduino-without-rfduino-code

Hi Juraj, unfortunately, the link page video doent work and im trying program RFD22302 micro!


text:
Sending multiple byte data from Arduino as Slave on SPI
I have been working around the teardown of an induction cooktop and thought of having a tweak in the system. So far, I have deduced following circuitry out of the cooktop-
There are two devices communicating with each other in 3-wire SPI mode. The master, which controls power management and Induction circuitry, continuously sends commands and data to the slave. The slave, which is TM1628, receives the master commands and data, then accordingly displays the data on the seven segment or responds with the switch pressed, if any.
The above picture explains it better. Now, I thought of replacing TM1628 with an Arduino. So far so good. I gathered all the data that was being sent by the master and the reply sent by the slave.
But, when I started to code, I got stuck in one place. So the data as sent by the master and its response looks like this -
(Master to Slave)**Command1 - Command2 - Data1 - Data2 - ... - Data 14 - Command1 - Command2 - **(Slave to master)**Data1 - Data2 - ... - Data5 - **(And now the repetition)
When the master is sending the data, I have no issues as the data will continuously be read by Arduino and I can take the action accordingly.
But when the Arduino (Working as a slave) needs to send continuously 5 streams of data, depending only on the clock input timing from the master, how could I know that one stream has been written and now the next data has to be written to the SPDR register.

DodZi , Please write me an email - vjacheslavra @ yandex . ru .
I also now want to do an induction stove control through arduino instead TM1628 .
Please show your sketch arduino.

With SPI there is no such thing as "sending" and "receiving".  It is a full duplex operation every time. Whenever the master runs the clock the slave both receives bits from the master and simultaneously sends bits to the master.
These operations are inseparable.
Whatever mechanism you are using to recognise "A byte has arrived from the master" is the same mechanism that you use for filling the SPDR register. The bytes where you "send" data to the master are actually bytes where the master is sending you data, but you don't care about what that data is. Just like when the master is sending you "commands" you are sending the master data (which you haven't specified) and the master "doesn't care" what that data is.
It's up to you to keep track of how many bytes the master has clocked in and out, and to say "For bytes 19-23 the master is expecting valid data, so I need to make sure that I put data into the SPDR for those bytes".


text:
Optimizing code to use less Flash Memory and SRAM
I'm trying to reduce my sketch size and managed to reduce both SRAM and Flash memory.
From:
1570 SRAM - 32144 Flash memory
To:
644  SRAM - 19458 Flash memory

This are what I've done so far:
✓ Enabling LTO
✓ Using PROGMEM
✓ Dropping string and using char
✓ Dropping bootloader
✓ Using port manipulation
✓ Using registers to declare pins output/input
✓ Removing/Optimizing/Combining; unnecessary/repeated codes in the sketch
Using EEPROM is not an option for me.
What else i can do to take optimization one or two step further?

ArduinoIDE is designed to be easy and not fast. To really optimise your code switch to AtmelStudio and write logic on registry level. ArduinoIDE loads many libraries out of box. Some of them are probably unnecessary in your sketch.

Change the compiler optimization levels. I looks like you can do that within the code, though I've done it by changing the boards.txt file in the past.

Also use the right type for (global) variables. Use byte instead of int for variables whose values are always between 0 and 255.

What you can do in addition to the items you mentioned:
SRAM reduction

Use the smallest amount of data type for integers, e.g. use an 8 bit data type instead of the default integer, this saves you one byte for every variable. See remark below about types. I made my own types (if not existing) for int32_t, uint32_t, int16_t, uint16_t, int8_t and uint8_t and always use the smallest possible.
Use unsigned instead of signed for types that cannot be negative. This might save you one byte if you can prevent using an unsigned byte instead of a signed int because a value can be in range [128..255]. The same for unsigned int instead of signed long.
Use bit fields if you use multiple booleans inside a struct or class. Make sure the bit fields are declared consecutively.
Pack data in smart structures ... I.e. if you have two variables, where one can be 0..7 and another can also be 0..7, store this together using bit fields (in combination with boolean to bit field above).
Prevents float/doubles (see KIIV's comment below), instead:
Instead of using a float, multiply the value by the needed accuracy and store it in an integer (if you don't need high accuracy and it fits in the integer type).
In case you need a lot of strings to be stored, and those strings do not have characters above 128, you can save 1 bit per byte, of course this means quite some programming work to handle 7 bits 'ASCII' characters.
The same, if you have to store a lot of values that can be e.g. 0 to 50, you can use 6 bits instead of 8 bits; you cannot use bit fields, but you can make a smart array and program your own get/set functions to access the 6 bit values.
If you use libraries which declare big buffers, try to minimize those buffers, this might cause to copy them and manually change them yourself.
Prevent your own buffers to be made global, instead use them as a local variable temporarily when you need them. If you have two of such buffers, you don't have both buffers allocated at the same time; note however, that during execution, that buffer still needs space (so you have to calculate or make a guess/estimation what the maximum stack size will be).

Flash Reduction

Don't use duplicated code blocks, but make functions with parameters to differ between the differences of the duplicated code.
Instead of lookup tables, create a function that calculates it (if possible). Of course the gain depends on the length of the lookup table and the length of the function.
Instead of debugging strings, use numbers.

Both SRAM/Flash Reduction

Split your application over multiple MCUs, of course this adds some kind of communication protocol (UART, I2C, SPI).

It's more like: Don't use floats/doubles on architectures without hardware FPU (pretty much just some Cortex M3/M4 boards have it). And for example on AVR based arduinos is double just an alias for float.

@KIIV Thanks for the comment, didn't know the aliases were the same.k

You can also change to a processor with more SRAM, such as 16kbytes in Atmega1284P.  I use that chip in many Arduino-based projects. Dual hardware serial ports,128K flash, 16K sram, and 32 IO.

@CrossRoads I didn't took hardware solutions into account (because of the OP not wanting EEPROM, which is more or less equal than using another MCU). Too bad they don't make a (cheap) Arduino with that MCU, I think the 2 KB SRAM is really a limit for many projects. I'm now making mine with a Mega and using an external EEPROM for storage. I was thinking about an external SPI RAM but I try to make my project without that.

Yep, China is not offering '1284P based boards like they do for Uno, Nano, and Promini. I sell boards, but I get my parts from Digikey & Mouser, so there is some markup there, but it ensures I get parts from a known good supply.

@CrossRoads I guess that's better, but for me a Mega will do. I wish I could make the entire project with STM32's, but I found out my knowledge is lacking to get a fast progress, so I stick with simple Arduino's until I'm ready to use some STM32's.

I'm having flashbacks to my early days as a C programmer in the 80's.
Some thoughts in addition to all of the excellent advice already given ...

Depending on how much data your application uses, you may want to
read / write data to an SD card (or other external storage).
While there is a certain amount of
overhead for the libraries, the payoff is you then have virtually
unlimited storage.  This is the equivalent of how we used to store
data on 5 1/4" diskettes back in the old days.
Avoid static variables whenever possible.
Keep the scope of a variable as small as possible.
As a philosophy you should consider unsigned char to be your
default data type and only 'upgrade' to a bigger footprint when your
code requires.

Re “use dynamic memory as much as possible”: You should probably be more specific. When hearing “dynamic memory”, most would think malloc(), which is something to be avoided if you can. I guess you mean “automatic allocation”, i.e. local variables not qualified as static.

Re “re-use variables if you don't need them at the same time”: −1, as this is terrible advice! Please, refrain from encouraging such horribly bad practice. It may have been a reasonable optimization 30 years ago, but since at least 20 years, it has become quite difficult to find a compiler dumb enough to not do this optimization itself. Trust your compiler, and write clear code. Or ditch the compiler if you managed to find one that is that bad.

Funny, keeping scope as small as possible is mutualy exclusive with reusing variables. Reusing variables is also error prone, but maybe little bit less error prone than variable declaration and initialization later (often later than it's used)

Agreed with feedback, updated my answer to reflect that.


text:
serial port through Rx and Tx want work

my serial connection prints rubbish, but it systematic, so it's not just random as you see on image 1, any help would be appreciated
other info:
the first image of the serial monitor of COM6 is my own serial connection, image nr. 2 is the serial monitor of COM4 which already uses the onboard serial to USB
the last image shows how I made my own serial connection
the 2 black cables are providing around 4 volts, I know these are not necessary cause the USB already provides 5 volts and ground
and oh ye, normally the USB on the last image would be connected to my pc ofc

Is that a USB to RS232 adapter there? RS232 != UART. Also it risks killing your target device through incorrect voltages being applied.

You're using a USB to RS-232 adaptor. That is wrong.
RS-232 is not (electrically) the same as UART.  Not only is the logic inverted, but it uses ±10V NRZ signalling.
That means that when the UART expects a 3.3V HIGH signal the adapter is sending it a -10V signal. When it's expecting a 0V LOW signal it's being sent a +10V signal.
So yes, it's gibberish - it's getting the opposite of what it expects to see - and the excess and negative voltages risk damaging your ESP. Fortunately the currents involved are usually so low that it doesn't damage it straight away, but with prolonged use you can probably kiss your ESP goodbye.
Disconnect that dongle immediately and get a proper USB to UART adapter.

Or implement a RS232 to UART adapter by using the MAX232

@chrisl The MAX232 is probably what's inside there, so you'd be doubling it up and making a "double negative" scenario ;) Pretty wasteful on components and things. Best to do things properly.  But yes, you could do that if you are psychotic enough...

Just check the code by running on all different Baud-rates (in the serial monitor) ..It should normally work on the rate u have declared in the code.


text:
How can I assign a variable to a function output in Arduino?
I'm trying to assign the output of my function (which adjusts a DAC output) to a variable so I can print and display it in my serial monitor. Here's the code
#include <Wire.h>
#include <Adafruit_MCP4725.h>

Adafruit_MCP4725 dac;

int volza;

void setup() {
  Serial.begin(38400);
  Serial.println("Hello!");
  dac.begin(0x60);
}

void loop() {
    volza = dac.setVoltage(1095, 1); // THIS IS THE PROBLEM
    Serial.println(volza);
}

I am receiving an error because of the commented line. I think it's because I am trying to return a value while inside a void loop. How do you fix this?

I know it's because I am trying to return a value while inside a void loop ... how do you know this?

From researching the problem I've come across several threads that mention having a "void" means you cannot have a return value. Please correct me if I'm wrong

that is correct, however that would be the value returned by loop() ... loop() never exits, therefore it is not returning to any caller

I see.. thanks!

The setVoltage method has the following prototype:
void setVoltage( uint16_t output, bool writeEEPROM );

This means it does not return a value.
If you expect to return 1095, why not write:
volza = 1095;
setVoltage(volza, 1);
Serial.println(volza);

Some background information:
Assume you want to have the library a getVoltage method, than this is possible (you have to make a copy in your own project of the file and add the method. However, I'm not sure how easy it is to get the value from the EEPROM. If it is not easy, there is some programming work to do. Another solution is to store the value in memory, but that means some extra bytes from the scarce free SRAM. Also, in theory the content could be changed already (if another MCU would have access to the EEPROM too).

Great, thank you so much for the clarification. The "1095" I have is just a dummy example, I plan on having an analog input actually adjust this value, therefore I was interested in reading it by assigning it to a variable. Would you say I could use an analogRead instead of trying to assign it to a variable?

Probably, however, it depends on the implementation of setVoltage what actually happens.


text:
How does WiFiServer.status() work?
What are the possible outcomes of calling status() on a WiFiServer from ESP8266WiFi.h? The only documentation I could find only says it returns uint8_t. Here's the link.

wl_status_t at this page https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/include/wl_definitions.h

The basic set of functions of the esp8266 WiFi object follows the API of the Arduino's first WiFi library for Arduino WiFi Shield. It is documented here.
The esp8266 implementation of status() focuses on state of the STA and maps SDK status to some of Arduino documented codes.
wl_status_t ESP8266WiFiSTAClass::status() {
    station_status_t status = wifi_station_get_connect_status();

    switch(status) {
        case STATION_GOT_IP:
            return WL_CONNECTED;
        case STATION_NO_AP_FOUND:
            return WL_NO_SSID_AVAIL;
        case STATION_CONNECT_FAIL:
        case STATION_WRONG_PASSWORD:
            return WL_CONNECT_FAILED;
        case STATION_IDLE:
            return WL_IDLE_STATUS;
        default:
            return WL_DISCONNECTED;
    }
}


text:
How to read distance of passing object?
Ok, guys this is my first post and I am new to Arduino but somewhat familiar with programming so I hope you guys can assist me. If any of this is confusing, I apologize in advance! :)
I want to be able to utilize a TOF sensor that will be stationary to capture the distance of a passing object at a certain moment after it is first detected, because it is round. So I wanted to use a photoelectric switch, so when the object would pass, it would send the signal to the TOF sensor to read the distance 17ms after that moment.(I've done the math, and the delay to be in the center(closest edge to the sensor of solid ball) of the object passing would take 17ms) Then I would like to have that distance be displayed onto a LCD screen, until the next object passes and the process repeats....Think of a conveyor belt with a basketball on it. The basketball would be moving and pass the sensor, but the distance to the center(closest edge to the sensor)of the ball would be measured at a certain moment and displayed until the next ball passes.
The next problem is that the distance needs to be converted to a "zone" So like between 10-12cm, it would = 2. 12.1-14 would be 3 etc... The last part is probably the easiest but, I have no idea where to start...I appreciate all who helps!
I was needing help with the code to make this work with the Arduino uno. The tof sensor is VL53L1X and E-931-S35RRQ photoelectric sensor. And the LCD will be a 7 segment display so as long as it’s programmed for that I can change out sizes later..

@velocitygraphix - I've removed the "financial reward" part of your question because the Stack Exchange community frowns on monetary bounties for questions: https://meta.stackoverflow.com/questions/316137/what-to-do-when-op-offers-payment-for-solution

Yes all the balls are the same size. I’m not trying to find the size of the ball, only the distance to each one as it passes and then display it. Thanks!

Distance to the middle of the ball?...I’m not sure how you would word to say the middle of the ball..(halfway on the surface of the circumference?)...it’s a solid ball so the time of flight sensor would need to measure the closest edge of the ball-on the surface...

Not sure what you mean by closest approach but I want it measured to the part of the ball that is closest to the sensor which will fall halfway from front to back when passing. Picture if you pointed your finger out horizontally at a height exactly half the diameter of the ball...your finger is the sensor. Now if a ball rolls by and grazes your finger, that is the closest edge to the finger (sensor) that should be measured...

The ball part may be confusing you, as the shape doesn’t matter as long as the sensor takes a distance reading 17ms after the beam is broken...as long as the sensor takes a reading at that exact time, it’ll automatically be measuring to the correct part of the object.

i understand now ... you do not have it in your mind clearly ... as a result, your post is just a mess of irrelevant information ... all you want is for the TOF sensor to take a distance reading 17ms after a trigger signal ... you only need one sentence to ask that, not several paragraphs

Well sort of. I wanted to explain in detail. It also needs to hold the reading on a display until the next object passes...as well as convert the distance to “zones”...

Is there any specific question about this project? And do you already have the TOF sensor? Or at least have chosen one?

So break this into parts and solve each part separately. First, figure out how to interface the photoelectric sensor. First just write a loop() that waits for the state change when the sensor trips.
To get accurate timing you'll probably want to respond to the photoelectric sensor with an interrupt service routine that starts a timer. Get that working next.
Then figure out how to interface with your ToF sensor. When I googled it I found the bare sensor as well as versions on PC boards with an I2C interface. You may be able to find somebody's library that interfaces with the sensor. Get that working so you can take readings from the TOF sensor.
Then figure out how to drive the 7-segment display. Just write code that displays the values from 0-9 for 1 second each using a delay.
Once you've got all the pieces working separately, it's time to map out the logic if your program and make it work. Take a look at the "arduino blink without delay" example for how to write code that handles timed responses without using the delay() function.

The sensor has a 50Hz ranging frequency; depending on the speed of the balls passing the measuring section, you may only need to wait for ranges of less than (whatever passes for inifinity in your setup) and then track the ranges until they hit a minimum, save that value, and there's your first answer. This saves a detector and has the additional virtue of being independent of the speed of the traveling ball (up to a resolution limited by the sensor's measuring frequency & your precision requirements).
The second part just needs a few ifs, such as:
if( range < 10.0 ){
  zone = 1;   // or whatever else you need to do here
}
else if( range < 12.0 ){
  zone = 2;
}
else {
  zone = 3;   // anywhere else
}


text:
Why does SoftwareSerial::read() return int?
The documentation on Arduino's website shows SoftwareSerial::read() as returning a char. (link)
The header shows that the method returns an int. (link)
The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values. (link)
Given all of this:

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

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

You'll see in the code just above your third link that the function can return a value of -1 if there is no data present. Thus a 16-bit value is used to cover the range of 8-bit uint8_ts, plus one extra value to show 'no valid data available'.
For simplicity, I guess.
Yes. This is what it's designed for.

In short, for all intents and purposes, only an 8-bit value is returned, but if you were to read into an int, you couldn't differentiate between a valid and invalid value.

Ah awesome! The -1 value makes sense.
So assuming I gate the read() invocation w/ available(), it sounds like I can read it into a uint8_t directly and work with it as a true byte.

All the applications I've seen (for all stream type objects) is if(available()){read();}. The code you linked to reads the data from the ring buffer into a temporary uint8_t before returning into an int, so you're not going to lose any data that way

The actual answer to number 2 is "Because, as in many instances, the Arduino documentation is complete garbage."

I'm a bit surprised no-one mentioned the fact that it's the exact same reason why getchar() and friends return an int in standard C.

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

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

The header shows that the method returns an int.

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

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

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

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

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

the character read, or -1 if none is available

You can't return -1 in a uint8_t.

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

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

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

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

It's this kind of confusion with return types and bytes and integers and things that make people ask why they keep getting ÿÿÿÿÿÿ on the serial monitor. That's -1 cast as a char. I.e., "no data available" but they ignore that and treat everything returned as a char - most probably because the Arduino documentation shows an overly simplified example that ignores the possibility of a -1 being returned and treats everything as a char.
IMHO much of the Arduino documentation is somewhat sub-par and should not be taken literally - only as a rough guide for what is available. The same goes for much of their example code and projects.

There is hope though, as it seems the Arduino documentation is in the process of being refactored. The documentation for Serial.read(), which comes from the new GitHub-hosted ASCII doc-based repository, clearly states “Data type: int.” The documentation for SoftwareSerial is still in the old format and has presumably not been migrated yet.

@EdgarBonet That's promising. Maybe they'll do the same with all the bad schematics and example projects...

Stream declares read as returning int (look in hardware/arduino/avr/cores/arduino/Stream.h). SofrtwareSerial inherits from Stream, so they have to override that declaration, otherwise there would be two read() methods, one returning int and one returning uint8_t. Since SoftwareSerial::read() would onlyreturn an int between 0 and 255, which would fit in a uint8_t, there is no problem.
As for the Arduino docs, you get what you pay for :)

many words, no answer. the reason of int is to return -1 meaning "no data to return".


text:
Is it possible to transmit radio signal with cheap 433Mhz transmitter as strings and receive it with an RTL-SDR
I have these Arduino transmitters and receivers.
They are very common. I am just trying to transmit a "Hello" Message using this code.
#include <RH_ASK.h>
#ifdef RH_HAVE_HARDWARE_SPI
#include <SPI.h> // Not actually used but needed to compile
#endif

RH_ASK driver;
// RH_ASK driver(2000, 4, 5, 0); // ESP8266 or ESP32: do not use pin 11 or 2
// RH_ASK driver(2000, 3, 4, 0); // ATTiny, RX on D3 (pin 2 on attiny85) TX on D4 (pin 3 on attiny85),

void setup()
{
#ifdef RH_HAVE_SERIAL
    Serial.begin(9600);   // Debugging only
#endif
    if (!driver.init())
#ifdef RH_HAVE_SERIAL
         Serial.println("init failed");
#else
    ;
#endif
}

void loop()
{
    const char *msg = "hello";

    driver.send((uint8_t *)msg, strlen(msg));
    driver.waitPacketSent();
    delay(200);
}

But they have to be received from the receiver module using another set of codes which I have done it.
But my question is, is it possible to receive the transmitted message with one of RTL-SDR's INSTEAD of using the receiver module? If so, How to do it?

yes, it is possible ... use a PC or a Mac ... run an audio recording program such as Audacity to see the waveform

@jsotola Ah I see, then how do I decode the audio into a string?

i saw an article on the web once ... i think that it read the data from a weather station.... google sdr decoding weather station

Found it thanks, i will just put the link here for anyone interested: https://www.rtl-sdr.com/tag/weather-station/

In general you can use RTL-SDR to decode any AM and FM modulated signals (+some digital modulations) that lie within the frequency range form roughly 50MHz to about 1GHz. So 433MHz is confortably within that range.
There are many projects on GitHub that leverage the RTL-SDRs ability to decote 433MHz OOK modulated signals like:
RTL_433
Which comes with a ton of decoders for various appliances.
OOK_Decoder
Which will give you the demodulated raw output for you to decode the bits yourself.
I'm sure you will find more but those are in my opinion the most noteworthy for the 433MHz OOK space.


text:
I'm not getting the readings of sensors connected to an Arduino MEGA correctly using PLX-DAQ
I'm trying to send data from four sensors that are connected to my Arduino MEGA to an excel file using PLX-DAQ. So I want to keep taking readings at an interval of 1 second until I wish to stop. So I have two questions. First, this code is not working, I just get three readings but all in one row. And I try resetting the Arduino the first time using the physical button on it, and again I get the next set of three readings AFTER I press the reset button the second time. So there is no real-time updation. For example, I upload the code and I click on connect in PLX_DAQ. I see nothing in the Excel file. I press the reset button, and I get three readings all in one row. I wait for some time, I press reset again and I get another three readings and that's it.
Second, how do I control when to start taking readings or stop taking readings, either using Arduino code or by PLX-DAQ.

int sensC=A12;
int sensA=A13;
int sensB=A14;
int sensD=A15;

void setup() {
  Serial.begin(9600);
  Serial.println("CLEARDATA");
  Serial.println("LABEL,A0-Voltage,B0-Voltage,C0-Voltage,D0-Voltage");
}

void loop() {
  Serial.print(analogRead(sensA));
  Serial.print(",");
  Serial.print(analogRead(sensB));
  Serial.print(",");
  Serial.print(analogRead(sensC));
  Serial.print(",");
  Serial.println(analogRead(sensD));
  delay(1000);
}

**********EDIT 1**************
@user85471, ok so I added another line right under void loop(), which is: Serial.print("DATA,");
and I ran it again. Now i see my data being stored, but I have four sensors, but only three are of the right output.

A0-Voltage should be somewhere around 330-340, but I'm getting some sort of a time output.

Could you add a copy/paste of what you're seeing in the Serial monitor or your spreadsheet?

@user85471, please check EDIT 1, and help. Thanks :)

The first column must always be a timestamp value by the looks of things.

Go back to using the serial monitor in the Arduino IDE. Edit your question to show that output. My guess is there is some problem with the way you are capturing the data into Excel.

(You should edit your question to explain what PLX-DAQ is, and include a link. I had never heard of it and had to Google it.)

Changing the format of column A to a numeric format should display its true value. It looks like it's being displayed as a time, and since the values are all whole numbers, the time is midnight (00:00:00). If you were to change it to a date format, it would probably show a date around early December 1900.

I'm guessing that your import software assumes that the first column will be a timestamp, hence the change of this column only.

@DuncanC, yes your guess is right. I had originally checked the output from the serial monitor, and I was getting 4 values. But there is some error in the transfer from Arduino to Excel using PLX-DAQ. If you know any way to save the output from the serial monitor, that would be a useful lead for me. And yes, I'll add a link to explain what PLX-DAQ is.

@user85471, but I also tried labelling the first column for time and another four for A,B,C,D. Even then I don't get the expected output.

@Danush, not labelling, but change the actual displayed format of the cells. Select the column, right-click and choose format- you want to change to a number format instead of a date. I don't have Excel here, so I can't tell you the exact wording.

@Danush: alternative workaround. Add a fifth dummy column before your data. IE before printing the sensA value, print something random (zero would probably work, something like millis() would give some kind of timestamp) followed by a comma. If the column doesn't do what you want, jump over it and ignore it.


text:
Can arduino-cli verify sketches?
I'm trying to do some simple unit testing with arduino-cli in a .gitlab-ci file like so
variables:
  DOCKER_HOST: tcp://docker:2375

image: "docker:latest"

services:
  - docker:dind

before_script:
  - docker pull "arduino/arduino-cli:latest"
  - arduinocli(){ docker run arduino/arduino-cli:latest "$@";}

search:
  script:
    - arduinocli lib search hi

but instead of arduinocli lib search hi at the end, I want to verify my sketch. Is there a way to do this with arduino-cli?

In the Arduino IDE verify is just "compile" without upload

https://github.com/arduino/arduino-cli#step-5-compile-the-sketch as KIIV said.

In Arduino parlance the word "Verify" is used (erroneously) to mean "Compile the code into a binary or HEX file, but don't upload it to the board".
To compile (and thus "verify") the code just pass the compile command to arduino-cli with the board you want to compile for and the sketch you want to compile.

@Majenko's is 100 % correct. Here's my updated .gitlab-ci.yml for my arduino library.
image: ubuntu:latest

before_script:
  - apt-get update -yq
  - apt-get install -yq ca-certificates
  - apt-get update && apt-get install -y --no-install-recommends bzip2 curl unzip
  - apt-get upgrade -yq
  - curl -L -o arduino-cli.tar.bz2 https://github.com/arduino/arduino-cli/releases/download/0.3.3-alpha.preview/arduino-cli-0.3.3-alpha.preview-linux64.tar.bz2
  - tar xjf arduino-cli.tar.bz2
  - mv arduino-cli-0.3.3-alpha.preview-linux64 /usr/bin/ino
  - export APPDIR=$(ino config dump | grep --only-matching --regexp=/.*/Arduino)"/libraries/DC_motors"
  - mkdir --parents $APPDIR
  - mv ./* $APPDIR

test:
  script:
    - echo 'run a script'

compile:
  script:
    - ino core update-index
    - ino core install arduino:avr
    - ino core list
    - ino lib install "Adafruit Motor Shield V2 Library"
    - ino lib search Regexp
    - ino lib install Regexp
    - ino lib install AccelStepper
    - ino compile --fqbn arduino:avr:uno $APPDIR/examples/API

In case that library moves, here's the tree output of DC_motors
├── examples
│   └── API
│       └── API.ino
├── extras
│   ├── test
│   │   └── Makefile
│   └── testPython.py
├── .gitignore
├── .gitlab-ci.yml
├── keywords.txt
├── library.properties
├── README.md
└── src
    ├── MSv2.cpp
    ├── MSv2.h
    ├── MSv2Motors.cpp
    ├── MSv2Motors.h
    ├── MSv2Steppers.cpp
    ├── MSv2Steppers.h
    └── utility
        ├── MSv2Common.cpp
        └── MSv2Common.h


text:
USB power on arduino digitalRead is normal, but, gives error when using buck(step down) converter
I am using arduino for digitalRead(). i've been using INPUT_PULLUP, and when using USB power, all seems normal. but, when i switched to  power supply and buck converter(12v to 5v), the digitalRead() randomly change. why is that?

Impossible to say without more details. Provide a circuit diagram including the models of components, info about where you feed the input power, and the code for a minimal application that exhibits the behavior.

Is the 12V to 5V output being applied to the barrel jack connector? That is too low a level for the onboard 5V regulator to work from. Connect that 5V to the 5V pin instead.

If you read the docs they advise against feeding 5V into the 5V pin. What I've done is to cut a USB cable and feed my regulated 5V into that. That way you get the benefits of the on-board power source selection and protection circuits. (The Arduino intelligently manages choosing between USB power and barrel connector power. If you feed 5V into the 5V pin directly then you have to remember to disconnect that before plugging in a USB cable to program the Arduino.)


text:
How do I implement reverse enumeration?
Basically I'm trying to output a string based upon a value in an array, the following code is what I have come up with to achieve my desired result, but I have a feeling that there is a better way to do it.
String day(int day) {
  if (day == 1) return "Sunday";
  if (day == 2) return "Monday";
  if (day == 3) return "Tuesday";
  if (day == 4) return "Wednesday";
  if (day == 5) return "Thursday";
  if (day == 6) return "Friday";
  if (day == 7) return "Saturday";
  else return "Undefined";
}

void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(day(1));
}

void loop() {
;
}

This prints "Sunday" in the Serial monitor
I would appreciate any input on how to optimize this code, thank you!

Just one little thing to add to all the answers. Since this is "enumeration" I suggest substituting the magical int number with a refactor friendlyenum.

My method makes use of the __FlashStringHelper class:
// For convenience:
typedef const __FlashStringHelper *FlashString;

FlashString reverseEnum(int val) {
    switch (val) {
        case 0: return F("Option zero");
        case 1: return F("Option one");
        case 2: return F("Option two");
        default: return F("Invalid Enum");
    }
}

Printing now is as simple as:
Serial.println(reverseEnum(2));

Because it's a "flash string" the print function is overloaded properly and it performs the proper PROGMEM reading.
You can, of course, assign to a FlashString:
FlashString myString = reverseEnum(2);
Serial.println(myString);

Or if you don't want to use a typedef you can use the raw type:
const __FlashStringHelper *myString = reverseEnum(2);
Serial.println(myString);

It's just much cleaner to use a typedef.

Thanks for the info, I was really hoping for a way to use the enum, forwards and backwards without having to code out the reverse.

You could possibly craft something really horrible and complex with many layers of preprocessor macros, but it would be nasty and hard to understand. So don't. ;)

I'm no expert, but I imagine something along these lines would work:
char* day(int day) {

  static char* dayName[7] = {"Sunday", "Monday", .... };

  if (day > 0 && day < 8) {
    return dayName[day-1];
  }
  else
    return "Undefined";
  }
}

In any case, I'll be interested to hear why it's wrong (-:

Yeah, an array of char* C strings seems better than a long switch statement. (Voted)

Pointers to string literals should be const char* rather than char *.

@EdgarBonet - Curious - what's the advantage of const here? Is it style, speed, storage...?

Correctness. In C++, you are not allowed to modify the contents of a string literal.


text:
How to heat the air with arduino?
I have a plant growing box, fully controlled with arduino.
Youtube: ESP8266 IOT Flora
All things are under control, besides the air temperature.
I can cool it down running fans, but cannot find a way to heat it up.
Need to keep the temperature between 25-28 C all the time.
I was thinking of:

8x8 (64) Leds - maybe this can heat up the temperature, how much ?
Dedicated Module - is there any 5v heating module available ?

How are you powering the ESP8266?

3A 5V - Typical iPhone charger.

It really depends on the space you need to heat. Are you brewing beer or trying to survive a high latitude winter? How much insulation does the space have, how often is it opened to the outside (for inspecting your beer, or people entering and leaving the space, respectively)? You could need to control anything between a Peltier-effect heater/cooler, to a house- (or larger?) sized HVAC unit.

@PeeS you can use a piece of nickel chrome wire to heat that tiny box, just have to calculate the length of wire...

You could add some insulation to the box.

@newbie - is there anything i can read about it? Seems like a simplest solution.

@JRobert - the box is in the garage, all year - actually the tempearture drops there during winter to 13C.

@Gerben - good point actually, thanks.

@PeeS see the answer i just posted.

LEDs are not really efficient for heating up, you can better use a normal light bulb for that (they are less efficient, thus giving more heat).
The Arduino can only control some 100's of mA, that's not much for heating purposes.
Did you think about using a real heater (maybe small size), and use a relay to turn it on by your Arduino, and using a temperature sensor to switch it off above 28 and switch it on below 25 (or a lesser margin to keep up with the time it takes to change the environment temperature)?
If you do not want an external mains power, you could use probably a 12V heater and use a 12V->5V converter for your Arduino, or use a 5V heater pad, but according to what I have seen they are more for warming up cold hands, I doubt they can bring up the heat to 25-28 degrees Celcius. Besides, they are probably not very efficient.

Thank You Michel,
sure i can go with the external power supply - reason i didn't do it yet is just because  i like how clean the whole setup is with a single 5V 3A power.
I also have ESP12E motor shield :
https://arduino-shop.eu/arduino-platform/1456-nodemcu-esp8266-motor-shield-lua-l293d-esp8266-wifi-motor-control-arduino-esp-12e.html
where i can connect external power source and there's a relay.
Question is what do i choose to keep that 25-28 ..

If you search for a recommendation for a heater, than I don't know. Also, to be honest, that's not an Arduino question and on Electronics stackexchange product recommendations are not allowed. Maybe you can try Home Improvement/ DIY stackexchange: https://diy.stackexchange.com/

Thanks again, will look more and update the post with findings.

Good luck with your project :-)

The total current of your power supply, 5V • 3A is only 15 watts. That's not enough power to create a meaningful amount of heat. (although looking at your video your grow box is really tiny...)
LEDs are a terrible choice for providing heat. They produce mostly light, and very little heat (which is good if you want light, but bad if your goal is to build a heater.)
You probably want 30-60 watts of heat. As others have said, you could use a light bulb with a relay to control it. You could use a digital thermometer like a DHT11 to measure the temp, and then have a "digital" relay to control the heat source. You'd write a sketch that would turn your heater on at slightly above your minimum temp and turn it off at slightly below your max temp. (How much above and below your thresholds should be would depend on how strong your heater is and how long it takes to heat up your grow space. You'd need to do some testing.)
I created a forced air "boot dryer" where I used a couple of 120V, 500 watt heating elements in series (which lowers the power to 250 watts) and a thermostat. That is likely way too much heat for your tiny grow-box. Here is a link to that heating element: https://www.amazon.com/gp/product/B005RG64LQ/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
And for a relay I used a 5V "digital" relay like this one: https://vetco.net/products/single-relay-module-for-arduino?gclid=EAIaIQobChMIgfy8jtjJ4wIVA5-fCh2TXQH1EAQYBCABEgI3mfD_BwE

Note that if you have a high current DC supply you can use a MOSFET transistor rather than a relay to switch your heater on and off. To drive a heater you don't need a regulated supply. A simple high current "wall wart" style DC supply that puts out >= 30 watts and a low powered heating element would work.

For that matter, you could use an AC step-down transformer and a full wave bridge rectifier to create switched DC and feed that into a high power switching MOSFET and then to your heating element. For driving a heating element you don't need to regulate the power at all - just get rid of the negative voltage, since transistors can only switch current in one direction.

So why the down-vote? If you think my answer needs improvement please explain why.

note that most LEDs make about half light and half heat, which isn't half bad for making heat. even the best ones are only about 65% efficient.

You can use nickle chrome wire to easily heat that small box.
From Wikipedia:

Almost any conductive wire can be used for heating, but most metals conduct electricity with great efficiency, requiring them to be formed into very thin and delicate wires in order to create enough resistance to generate heat. When heated in air, most metals then oxidize quickly, become brittle, and break. Nichrome wire, however, when heated to red-hot temperatures, develops an outer layer of chromium oxide, which is thermodynamically stable in air, is mostly impervious to oxygen, and protects the heating element from further oxidation.

5V nickle chrome wires are available online to order, it's usually used as car seat heater.
Just be careful do not use Nickle chrome wire with Arduino directly because it can draw up to 2A from the power source and burn your Arduino board, instead use a relay to control the heater.
Here's the schematic to control a heater using Arduino and a relay:

simulate this circuit – Schematic created using CircuitLab

One simple way I can think of would be to turn a 100 W lightbulb (EDIT or whatever size makes sense for your application) on / off using a relay.  You could use a heat lamp, but with a small box like you have, a lightbulb should give off plenty of heat.  You would want to make sure that the bulb didn't give off enough heat to damage any plastic too close to it.

I was thinking a 100W bulb as well, but given how tiny that box is, 100W might be too much. I'm thinking 30W might be better.

Yeah, one of the cool things about using lightbulbs is you can tune it to the desired output just by swapping bulbs.  I'd think the desired result would be the minimum wattage that was able to maintain temp, so as to avoid thrashing the relay.

Thrashing the relay or cooking the seedlings. You don't want to either cycle the power too often or overshoot the target temp/blast the seedlings with too much infrared.

I wonder if an (incandescent) grow light (more expensive) would give a two for one deal and also provide better growing conditions?

I thought about that, but plants do best with a distinct day and night period. Lights that turn on and off at odd intervals driven by the temperature would likely disturb the plants' circadian rhythms. Better to run the lights based on day/night cycles, and the heater based on temp. Using LEDs for the grow lights would be a good idea to avoid overheating the plants during their day hours.

I had a similar concern.  I think if one were to go with the "lightbulb" approach then it would probably be best to use a low wattage heat lamp pointed away from the plants themselves.


text:
Restart variable every day
How can I restart a variable every day? I have an RTC1307. The problem is that I can't use an alarm event because the Arduino will be shut down during that hour. So I need a more reliable solution.
Will this work? A date could be an integer?
#include <EEPROM.h>
#include "RTClib.h"

int  lastDay;
int EE_ADDR = 0;
int totalLitres;

void setup() {
  EEPROM.get(EE_ADDR, lastDay);
}

void loop() {
DateTime now;
  if (now.day() != lastDay) // this happens exactly once a day.
    totalLitres = 0; // reset the accumulated volume

  lastDay = now.day();
}

Why does your Arduino shut down? And is your intention to prevent the shut down from happening?

I still don't understand the problem ... if the Arduino is shut down, it will restart and the variable gets its initial value again.

Ya, you gotta be a little more clear.   You want to zero a variable every day but there is a chance the arduino is not running when the new day starts?   One option would be to store a "lastResetDay" variable in EEPROM.  Then on startup, and periodically in your code, you will pull them variable from EEPROM, check it against the current day value from the RTC, if they match-do nothing. If they dont match then zero the flow variable and strore the current day back in EEPROM.

think about what will happen if the day changes right after the if statement compares the two values

@jsotola: Nothing special will happen: now.day() does not change by itself. DateTime is nothing but a container for timestamp items (year, month, day, hours, minutes and seconds). If you don't explicitly initialize it, is gets default-initialized to 2000-01-01T00:00:00 (the default used to be 2106-02-06T06:28:16, until this pull request got accepted).

Here are a few suggestions:

Since your RTC has some non-volatile RAM (NVRAM) onboard, you could
use it instead of the EEPROM. This way you will not have to worry
about the EEPROM endurance.
If there is the possibility that the device gets power-cycled within a
single day, you probably want it to preserve the liter count. This can
be achieved by periodically saving this count to the NVRAM, and
restoring it at startup. You can save often, as you don't have
endurance limits.
If the device is started after a full month of being off, if should
notice some days have passed, even it the day number is the same as
when it was turned off. Instead of saving just the day number, I would
store the total number of days elapsed since 2000 Jan 1.

Untested implementation of the above suggestions:
#include <Wire.h>
#include <RTClib.h>

const uint32_t NVRAM_UPDATE_PERIOD = 10000;  // 10 seconds

/* Addresses for data items saved in the RTC's NVRAM. */
const uint8_t ADDRESS_LITERS    = 0x00;
const uint8_t ADDRESS_RESET_DAY = 0x02;

RTC_DS1307 rtc;
uint16_t liters;
uint16_t reset_day;

/*
 * If `liters' has not been reset today, reset it now and update both
 * the RAM and NVRAM copies of `reset_day'.
 */
void reset_liters_if_needed()
{
    uint16_t current_day = rtc.now().secondstime() / 86400;
    if (current_day > reset_day) {
        liters = 0;
        reset_day = current_day;
        rtc.writenvram(ADDRESS_RESET_DAY,
                (uint8_t *) &reset_day, sizeof reset_day);
    }
}

void setup()
{
    /* Pull the initial `liters' and `rest_day' from NVRAM. */
    rtc.begin();
    rtc.readnvram((uint8_t *) &liters, sizeof liters,
            ADDRESS_LITERS);
    rtc.readnvram((uint8_t *) &reset_day, sizeof reset_day,
            ADDRESS_RESET_DAY);
    reset_liters_if_needed();
}

void loop()
{
    /* Periodically update the NVRAM. */
    static uint32_t last_nvram_update;
    if (millis() - last_nvram_update >= NVRAM_UPDATE_PERIOD) {
        reset_liters_if_needed();
        rtc.writenvram(ADDRESS_LITERS,
                (uint8_t *) &liters, sizeof liters);
    }
}

For extra safety you may want to add a large capacitor in order to keep
the Arduino powered for a few milliseconds after being unplugged. And a
circuit that detects when it gets unplugged in order to immediately save
the data and stop accessing the NVRAM before it gets out of juice. This
kind of trick has already been discussed here, you should be able to
find the relevant questions and answers.

@santilococo: Just beware that a float is 4 bytes. If you store liters as a float at address 0, you can put reset_day at address 4, but not at address 2.

@santilococo: No, sizeof(float) is 4.


text:
How can I pause a stepper motor with a ultrasonic sensor?
I'm trying to use a stepper motor to stay stationary and rotate about 90 degrees, when the ultrasonic sensor detects something in front of it, and stay at that position until the ultrasonic sensor does not detect anything in front of it any more, to which the motor will rotate back to it's original position.
I'm using an Arduino Uno, a Longruner 5X Geared Stepper Motor 28byj 48 Uln2003 5v Stepper Motor with a  Uln2003 Driver Board.

#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

// defines pins numbers
const int trigPin = 7;
const int echoPin = 6;

// defines variables
long duration;
int distance;

void setup() {

   pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
   pinMode(echoPin, INPUT); // Sets the echoPin as an Input
   Serial.begin(9600); // Starts the serial communication
   myStepper.setSpeed(60);
    // initialize the serial port:  (again??)
   Serial.begin(9600);
}

void loop() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
   duration = pulseIn(echoPin, HIGH);

// Calculating the distance
   distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
   Serial.print("Distance: ");
   Serial.println(distance);

   if (distance < 10) {
       myStepper.step(-stepsPerRevolution);
       delay(1000);
       if (distance > 10) {
           myStepper.step(stepsPerRevolution);
           delay(10000);
       }
   }
}

Here's my code. I can't really figure out how to stop/pause the stepper motor once it rotates. Any ideas? (I'm a beginner, so apologies for any beginner mistakes).

it is your job to tell us what you see happening when you run the program ... please edit your post above ... do not use comments

the stepper motor control and the ultrasonic sensor reading are two completely separate functions .... develop the stepper motor code separately from the sensor ...  use a pushbutton to initiate the motor motion ... when the motor behaves the way you want it to behave, then add the sensor code

I do not think it is a major issue, but why are you calling Serial.begin() twice?

Oops my mistake didn't catch that


text:
Pro Micro with Atmega32U4 - reset - reprogramming
i am a new user on arduino card. i have a question about "Pro Micro with Atmega32U4".
- is this product programmable several times ? and the third pin (RST) - (Reset). so, does reset mean it erases memory?
Thank you in advance for your answers.

Yes, the microcontroller on Arduinos (in this case the Atmega32U4) can be reprogrammed many times, only limited by the write limit of the flash memory (As I remember Microchip garantuees about 100,000 write cycles at minimum). You can program it over the USB port of the board or through an ISP programmer.
The Reset pin will do the same as a power cycle (turning off an on again) would do. If you program the Arduino, this program will start, when the Arduino get's power (after the Bootloader, which is used to program over USB without ISP programmer). This program will then run until the power is turned off, or until a reset is done by pulling the RST pin to ground. When the RST pin is released again, the Arduino will again start up. The flash memory and the EEPROM stay untouched and will not loose any data. But the data, that lies in SRAM (like any normal variable in the program) will be lost.

Firstly, thank you for your quick response.
So, and if i want to erase completly the memory of my arduino card with the arduino App, is it possible ?
PS : because i found several subject talks about erasure memory arduino card and it isn't possible.

You are always talking about an "Arduino card". I think you mean a standard Arduino board (board is the better term here). 2. If programmed over USB, the current program will be overwritten, except for the bootloader, which you need to program it this way. There is no need to do an extra erase step. You can just write a program in the Arduino IDE, connect the Arduino, choose the correct port and board type and then hit upload. The Arduino IDE will then compile your code and upload it onto the Arduino.

Thank you very much for your help

If you think my answer is correct and good, you can upvote it and accept it as correct :)


text:
'Delay command' and bluetooth communication problem
I have a project where I send data to Arduino via Bluetooth using an Android application. For example, when I press 1 from the 'bar led' part of the application, an animation needs to happen. When I press 2, a different animation will be displayed. However, because there is a 'delay command' in the animations, there is a delay in data exchange when I press the button. How can I prevent this? Is there a command I can use instead of the 'Delay command'?

void loop() {
  if (bluetooth.available()) {
  while (bluetooth.available())
    {
      bar_analog = bluetooth.parseInt();
      head_analog = bluetooth.parseInt();
      bar_anim = bluetooth.parseInt();
      strip_anim = bluetooth.parseInt();
      motor_speed = bluetooth.parseInt();
      direct = bluetooth.parseInt();
      level = bluetooth.parseInt();
      if (debug) {
        Serial.print("Bar Brightness: ");
        Serial.println(bar_analog);
        Serial.print("Bar Animation Type: ");
        Serial.println(bar_anim);
        Serial.print("Headlight Brightness: ");
        Serial.println(head_analog);
        Serial.print("Strip Animation Type: ");
        Serial.println(strip_anim);
        Serial.print("Motor Speed Level: ");
        Serial.println(motor_speed);
        Serial.print("Direction: ");
        Serial.println(direct);
        Serial.print("Mast Goes: ");
        Serial.println(level);
        Serial.println("--------------------------------");
      }
      if (bluetooth.read() == '\n') {

      }
  }}
  if(bar_anim==1) {
  digitalWrite(8,HIGH);
  delay(50);
  digitalWrite(8,LOW);
  delay(250);
  }
  else if(bar_anim==2) {
  digitalWrite(8,HIGH);
  delay(250);
  digitalWrite(8,LOW);
  delay(50);
}
}

Do you mean a delay with every command that you send? Or just with one special command?

Every data I send is delayed because there is a 'delay command' in the animation part.

See the example program BlinkWithoutDelay.ino in the IDE.

I see 2 problems with your code:

You use the delay() function, which is not good coding style, since it is basically busy waiting. The Arduino will do nothing in this time, also not reacting to any input. Instead you should use a non-blocking coding style, which only does something, when it is time to do so, and will not block until something happens. You can see this style in the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as a time measure. Think of how you would bake a pizza. You would not sit on front of the oven doing nothing, until the pizza is ready. You would do other things while looking at your watch regularily, checking, if it is time to take out the pizza.
In the Serial communication part you use parseInt(). That can be a problem, since it has a timeout of 1s (standard value). Until the timeout the function will block. This is mitigated, if you consecently send a non-digit character at the end of every value. But it is better to first read a full message (until the newline character \n) and then process the message as a whole.

Also the line if (bluetooth.available()) is not necessary here, since the while loop will do the same.

Thank you for your nice answer.I tried to use the millis () command. However, I was able to turn the LED on and off with only 1 second interval.For example, I want the LED to be on for one second and off for half a second.How do I do this using millis ()?

You can use an if statement to distinguish between OFF state and ON state. Inside this if/else you put the millis() if statements with different interval values

I solved this problem, thank you.I have one last question.Is it possible to use millis () with the for loop?e.g
for (int j = 0; j <NUM_LEDS_PER_STRIP; j ++) {
fastled.setbrightness (255);
leds [j] = CRGB (100, 172, 45);
fastled.show ();
delay (100);
}
Can I use millis () instead of 'delay' here?

You should not use a for loop in this case. You have to build the functionality yourself by declaring a variable, that holds the number of the current LED. Then write a millis if statement, in which you set the color of the current LED and increment the variable to the next number.


text:
Why the global variables info is not shown for Arduino Due in IDE?
If I compile a sketch for the Arduino Mega:
Sketch uses 1804 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 188 bytes (2%) of dynamic memory,
leaving 8004 bytes for local variables. Maximum is 8192 bytes.

If I compile the same sketch for the Arduino Due:
Sketch uses 26304 bytes (5%) of program storage space. Maximum is 524288 bytes.

Why is the global variables part not supported for the Due, it seems to me it's quite important (even more than the sketch size).
Or can I enable this option somehow? (and if yes, how)

There is a difference in how the build system calculates the memory size for AVR and SAM. The platform.txt file contains the rule for calculating the size. There is a difference how this is done for SAM (Arduino Due).
The AVR size rules (https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L79) are:
## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*
recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*

And the rules for SAM (https://github.com/arduino/ArduinoCore-sam/blob/master/platform.txt#L91) are:
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=\.text\s+([0-9]+).*

They may be updated to give more information about the memory size. A good reference on the subject is http://www.support.code-red-tech.com/CodeRedWiki/FlashRamSize which shows that the output from size command for SAM contains much more information.
I assume that from the above information you see how this could be updated.
Cheers!

Thank you very much ... that output looks very much to what I get when I compile software for the STM32. However, I tried to find how to run arm-none-eabi-nm -S --size-sort -s project.axf, but I cannot find the axf file and there is - at least no menu option - to  run arm-none-eabi-nm


text:
Sending code for error detection facing problem with error not able to compile code
MY PROJECT CODE:

#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>
#define FIREBASE_HOST "iot-based-smart-dustbin.firebaseio.com"
#define FIREBASE_AUTH "ljIbV03K07rLwoHRKSaAxWzJNCb3Lh6buc76dkvb"
#define WIFI_SSID "AndroidAP"
#define WIFI_PASSWORD "ashu1234"
char c; //ESP
String data   = "";  //ESP
#define DOUT  15
#define CLK  13
#define IR1 14
#define IR2 12
HX711 scale(DOUT, CLK); // Init of library
float calibration_factor = -96650; //-106600 worked for 3-40Kg max scale setup
const int rs = 16, en = 5, d4 = 4, d5 = 0, d6 = 2, d7 = 10;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup()
{
   Serial.begin(9600);
   pinMode(IR1,INPUT);
  pinMode(IR2, INPUT);
  pinMode(DOUT, INPUT);
  pinMode(CLK, OUTPUT);
  lcd.begin(16, 2);     // Print a message to the LCD.
  lcd.print("WELCOME");
  delay(2000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
//  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED)
    {
  //    Serial.print(".");
      delay(500);
    }
//  Serial.println();
//  Serial.print("connected: ");
//  Serial.println(WiFi.localIP());
  scale.set_scale();
  scale.tare(); //Reset the scale to
}
void loop()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  float a=scale.get_units();   // a Variable to take weight values at input
  lcd.clear();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setFloat("Weight", a);  //to set value in firebase // value on a sent to weight variable
  if (digitalRead(IR1)==HIGH)
  {
    Firebase.setFloat("IR1", HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Location 1:High");
  }
   if (digitalRead(IR1)==LOW)
  {
    Firebase.setFloat("IR1", LOW);
    lcd.setCursor(0, 0);   //column, Row
    lcd.print("Location 1: Low");
  }
   if (digitalRead(IR2)==HIGH)
  {
    Firebase.setFloat("IR2", HIGH);
    lcd.setCursor(0, 1);
    lcd.print("Location 2:High");
  }
   if (digitalRead(IR2)==LOW)
  {
    Firebase.setFloat("IR2", LOW);
    lcd.setCursor(0, 1);
    lcd.print("Location 2: Low");
  }
  delay(2000);
  lcd.clear();
  if (a>=4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: High");
  }
   if (a<4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: Low");
  }
 delay(2000);
}
void send_msg_1()
{
  Serial.println("AT+CMGF=1");// for GSM module in TEXT mode
  delay(1000);
  Serial.println("AT+CMGS=\"+9921526975\"\r");// Phone number (change)
  delay(1000);
  Serial.println("Dustbin at Location 1 is full");// Message body (change as per requirement)
  delay(1000);
  Serial.println((char)26);// send message
  delay(1000);
}

ERRORS I am Getting while compiling as follows:
sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'
 HX711 scale(DOUT, CLK); // Init of library
                      ^
C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:
In file included from C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:23:0:
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
   HX711();
   ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
 class HX711
       ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'HX711::HX711(int, int)'

Please help me to solve this problem. Too much struggling...

Probably the main problem is already in the first lines:
#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>

You should use the correct formatting:
#include "ESP8266WiFi.h"
#include "LiquidCrystal.h"
#include "FirebaseArduino.h"
#include "HX711.h"

Also, HX711 does not have a constructor with arguments, so instead of
HX711 scale(DOUT, CLK);

uese
HX711 scale;

and in Setup:
scale.begin(DOUT, CLK);

You probably have the code meant for a different library.
See HX711_full_example. Or use the code belonging to your used HX711 library.

Thank you so much for your precious Help sir. from last many days struggling with errors. Not much familiar with Arduino IDE.. Thank you very much for help. Really grateful.

You are welcome, success with your project. If the answer solves your problem, please accept the answer (by pressing the button near the answer).