text:
DHT22 and DS18B20 together
I am trying to get DHT22 and DS18B20 to work together. The code below is the one I am using:
#include <SD.h>
#include "SPI.h"
#include "DHT.h"
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <stdlib.h>
#include <avr/interrupt.h> // library for interrupts handling
#include <avr/sleep.h> // library for sleep
#include <avr/power.h> // library for power control
#include <OneWire.h>
#include <DallasTemperature.h>

#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22  (AM2302)
#define wakePin 2 //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ONE_WIRE_BUS 4  //DS18B20 is plugged into pin 4

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const int chipSelect = 10;
int interval_sec=0; //An alarm interval in seconds
int interval_min=5; //An alarm interval in minutes
int interval_hr=0; //An alarm interval in hours
char file_name[25]="Readings.csv"; //
DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature.

void setup () {
  Serial.begin(9600);
  delay(3000); // wait for console opening
  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT_PULLUP);
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);
  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);
  //Initialize DS18B20 libraries
  sensors.begin();
  /**SD CARD**/
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
  //Remove File from SD card and create a new one
  SD.remove(file_name);
  File dataFile = SD.open(file_name, FILE_WRITE);
  dataFile.println("Date,Hour,Minute,Air_Temp,Humidity,Surface_Temp");  //Write the header
  dataFile.close();
   Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
  DateTime now = rtc.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" (");
  Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  Serial.print(") ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  /**Temperature and Humidity**/
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  //float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  //if (isnan(h) || isnan(t) || isnan(f)) {
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
    // Compute heat index
    // Must send in temp in Fahrenheit!
    //float hi = dht.computeHeatIndex(f, h);
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C\t");
    delay(3000); // wait for console
    /**DS18B20**/
    // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus
    sensors.requestTemperatures(); // Send the command to get temperatures
    float surface_temp=sensors.getTempCByIndex(0);
    Serial.print("Temperature for the device 1 (index 0) is: ");
    Serial.println(surface_temp);
    delay(3000); // wait for console

    /**Store on SD**/
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open(file_name, FILE_WRITE);
    String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + surface_temp;
    //String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + String("surface_temp");
    //Serial.println(dataString);
    // if the file is available, write to it:
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      //Serial.println(dataString);
    }
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening file to log data");
    }
    /**INTERRUPT Based sleep**/
    DateTime nextAlarm = now + TimeSpan(0, interval_hr, interval_min, interval_sec);
    //Format is TimeSpan(day,hour,min,sec). Either use interval_min or interval_sec
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1); //set wake-up time here
    rtc.alarmInterrupt(1, true);
    delay(3000); // wait for console
    attachInterrupt(0, wakeUp, LOW); //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    //Arduino enters sleep mode here
    detachInterrupt(0);
    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);
    Serial.println();
    delay(3000);
}

void wakeUp() {
  // here the interrupt is handled after wakeup
}

The above code ideally should read and store the temperature from DS18B20, and temperature and humidity from DHT22 and then go to sleep for a pre-determined time (5mins now) and then wake up when an interrupt is generated from the RTC.
However, I am unable to get both DHT22 and DS18B20 to work together. The code above works as expected if I comment out the code for DS18B20. Similarly, if I just run the examples (named Single and Simple) for DS18B20 as provided by DallasTemperature on the same Arduino keeping all the connections intact (DHT, RTC, SD Card, along with DS18B20) the DS18B20 also work as expected. Hence, I think I can be certain that the connections are proper. However, if I run the code above which include both DHT22 and DS18B20, then the output I get is as follows:
Initializing SD card...card initialized.
Initialisation complete.
201Initializing SD card...card initialized.
Initialisation complete.
2⸮

I would appreciate if someone can point me to where I am going wrong.
P.S.: I have also successfully tried a simple program like the one below to ensure that there are no conflicts in libraries of DHT22 and DS18B20.
#include <DallasTemperature.h>
#include <OneWire.h>
#include <DHT.h>

#define ONE_WIRE_BUS 4
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(dht.readTemperature());
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

What does the compiler say about the used memory ?

@Jot: Yes! There is a warning saying that there is too less free memory and the program might not work properly. I have reduced the number of print statements and now it works as expected. Can you add your comment as an answer?

My first thought was that sram is being overwritten. That seems to be the case, as you have confirmed.
The SD library uses a lot of sram memory, because it has to handle a table of the FAT data structure from the SD memory card.
You don't use the 'PSTR()' or the 'F()' macro and not the PROGMEM.
For example this code:
Serial.println("Dallas Temperature IC Control Library Demo");
creates that text in Flash memory and during startup that text is also copied to sram memory. You can avoid that by forcing that text to stay in flash memory only with the 'F()' macro:
Serial.println(F("Dallas Temperature IC Control Library Demo"));
Perhaps you have already seen sketches that use the 'F()' macro a lot.
The names of the days of the week can be placed in Flash code with PROGMEM. It requires special functions to read data from PROGMEM, since the AVR microcontrollers can not read data from flash directly.
[ADDED] The 'F()' macro, the 'PSTR()' and the PROGMEM are explained here: Nick Gammon about PROGMEM

Nice tidbit about F(), @Jot.  It is predefined?

Yes, it is part of the Arduino and mostly used with AVR microcontrollers like the Arduino Uno, Nano, Leonardo, and so on. I have added a link to my answer to Nick Gammon's page about it.


text:
Getting BPM from the given code
I have found code that can blink an LED on Arduino according to Heart Beat. I am using AD8232 as a sensor for Heart Rate.
Code for it is:
//  Variables
int PulseSensorPurplePin = 0; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13; // The on-board Arduino LED
int Signal; // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550; // Determine which Signal to "count as a beat", and which to ingore.

void setup() {
  pinMode(LED13, OUTPUT); // pin that will blink to your heartbeat
  Serial.begin(9600); // Sets up Serial Communication at certain speed.
}

void loop() {
  Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor's value.
  // Assign this value to the "Signal" variable.
  Serial.println(Signal); // Send the Signal value to Serial Plotter.
  if(Signal > Threshold) {
    // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
    digitalWrite(LED13, HIGH);
  } else {
    digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
  }
  delay(10);
}

My question is: How can I get BPM?
Edited below:
Is this code for BPM correct?
int x = 0;
int LastTime = 0;
bool BPMTiming = false;
bool BeatComplete = false;
int BPM = 0;
#define UpperThreshold 518
#define LowerThreshold 490
int LED13 = 44; // The on-board Arduino LED
int Signal; // holds the incoming raw data. Signal value can range from 0-1024

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

void loop() {
  int value = analogRead(0);
  if (value > UpperThreshold) {
    if (BeatComplete) {
      BPM = millis() - LastTime;
      BPM = int(60 / (float(BPM) / 1000));
      BPMTiming = false;
      BeatComplete = false;
    }
    if (BPMTiming == false) {
      LastTime = millis();
      BPMTiming = true;
    }
  }
  if ((value < LowerThreshold) & (BPMTiming))
    BeatComplete = true;
    // display bpm
  Serial.print(BPM);
  Serial.println(" BPM");
  x++;
  Signal = analogRead(0); // Read the PulseSensor's value.
  // Assign this value to the "Signal" variable.
  if (Signal > UpperThreshold) {
    // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
    digitalWrite(LED13, HIGH);
  } else {
    digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
  }
}

If you know the interval between heart beats, you can calculate the frequency using the formula: frequency = 1 / time. Now if you take the frequency and multiply it by 60, you should get BPM.
I don't have one of the sensors you are using so I connected a potentiometer to pin A0 to test this code.
    int UpperThreshold = 518;
    int LowerThreshold = 490;
    int reading = 0;
    float BPM = 0.0;
    bool IgnoreReading = false;
    bool FirstPulseDetected = false;
    unsigned long FirstPulseTime = 0;
    unsigned long SecondPulseTime = 0;
    unsigned long PulseInterval = 0;

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

    void loop(){

      reading = analogRead(0);

      // Heart beat leading edge detected.
      if(reading > UpperThreshold && IgnoreReading == false){
        if(FirstPulseDetected == false){
          FirstPulseTime = millis();
          FirstPulseDetected = true;
        }
        else{
          SecondPulseTime = millis();
          PulseInterval = SecondPulseTime - FirstPulseTime;
          FirstPulseTime = SecondPulseTime;
        }
        IgnoreReading = true;
      }

      // Heart beat trailing edge detected.
      if(reading < LowerThreshold){
        IgnoreReading = false;
      }

      BPM = (1.0/PulseInterval) * 60.0 * 1000;

      Serial.print(reading);
      Serial.print("\t");
      Serial.print(PulseInterval);
      Serial.print("\t");
      Serial.print(BPM);
      Serial.println(" BPM");
      Serial.flush();

      // Please don't use delay() - this is just for testing purposes.
      delay(50);
    }

Updated answer in response to your comments below:
The sketch is reading the data and sending the data to the serial monitor every 50ms because of the delay(50). What if we changed that to 1000 ms? The serial monitor would update once per second which would be more "human readable". The problem with that idea is for heart rates faster than 60 BPM, the reading would be inaccurate. I don't have a sensor to test with but I'm guessing a 1 second delay would make the code inoperable.
Before we add more complexity to this sketch we really should get rid of that delay. It would be nice to have one "timer" that we could use to update the BPM calculation and a second "timer" to update the serial monitor every second, or half second, or what ever you want it to be.
We can do that without any libraries using millis(). Here is an updated sketch using millis() for timers. This sketch has the blinking of the on board LED added to it. I'm using an Uno so you'll have to change LED_BUILTIN to what ever pin number you are using.
int UpperThreshold = 518;
int LowerThreshold = 490;
int reading = 0;
float BPM = 0.0;
bool IgnoreReading = false;
bool FirstPulseDetected = false;
unsigned long FirstPulseTime = 0;
unsigned long SecondPulseTime = 0;
unsigned long PulseInterval = 0;
const unsigned long delayTime = 10;
const unsigned long delayTime2 = 1000;
const unsigned long baudRate = 9600;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;

void setup(){
  Serial.begin(baudRate);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop(){

  // Get current time
  unsigned long currentMillis = millis();

  // First event
  if(myTimer1(delayTime, currentMillis) == 1){

    reading = analogRead(0);

    // Heart beat leading edge detected.
    if(reading > UpperThreshold && IgnoreReading == false){
      if(FirstPulseDetected == false){
        FirstPulseTime = millis();
        FirstPulseDetected = true;
      }
      else{
        SecondPulseTime = millis();
        PulseInterval = SecondPulseTime - FirstPulseTime;
        FirstPulseTime = SecondPulseTime;
      }
      IgnoreReading = true;
      digitalWrite(LED_BUILTIN, HIGH);
    }

    // Heart beat trailing edge detected.
    if(reading < LowerThreshold && IgnoreReading == true){
      IgnoreReading = false;
      digitalWrite(LED_BUILTIN, LOW);
    }

    // Calculate Beats Per Minute.
    BPM = (1.0/PulseInterval) * 60.0 * 1000;
  }

  // Second event
  if(myTimer2(delayTime2, currentMillis) == 1){
    Serial.print(reading);
    Serial.print("\t");
    Serial.print(PulseInterval);
    Serial.print("\t");
    Serial.print(BPM);
    Serial.println(" BPM");
    Serial.flush();
  }
}

// First event timer
int myTimer1(long delayTime, long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

// Second event timer
int myTimer2(long delayTime2, long currentMillis){
  if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
  else{return 0;}
}

The code compile size with delay is 4,732 vs the millis timers at 4,682 (with the LED code removed). Two timers for less than the price of one delay :)
The LED will remain on for the duration of the heart beat reading above the LowerThreshold. If you want to have it on longer or decide how long it should be on for, I won't write the code for you but I will give you a hint. You can copy myTimer1() again and make a third timer.

Thank you very much for reply and for editing my question, the code you provided works flawlessly, but i have a LED connected to pin 44, I want to indicate that LED for every Heart Beat, that means when beat happens that LED should blink..
and another thing is : for the first few seconds in the Serial monitor, BPM is showing more than 500 of values - Sometimes it's going to 1000's as well, how to avoid this.?
See my Edit..

See this http://s44.photobucket.com/user/beingmachine/media/Screen%20Shot%202017-08-23%20at%204.00.08%20PM_zpshktk2ucq.png.html

source: Stack Exchange

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

sort: votes


text:
View Arduino M0 SD card content on a computer
Recently I bought an Arduino M0 board and I'm using it in one of my projects, which logs GPS data into an SD card.
Can an Arduino M0 be programmed as a USB SD Card reader? So that I don't have to remove the SD card from the system and use the same USB port from M0 to see the contents of the SD card directly on my computer.

Yes, in at least some way, but what is realizable and best depends on a few things.

A traditional "card reader" is a USB Mass Storage device which basically exports the logical blocks of the card to the USB host computer.  While this is active, nothing on the embedded system may interact with the card.  The embedded system will need a USB device port which can operate in this mode, suitable software, and whatever data is recorded on the card will need to be a in a filesystem (FAT or whatever) that the host PC can read, and a data format in the files that existing or custom software for that PC can make sense of.
A different option would be to still store data on the card in a way that would be PC-compatible if the card were removed and placed in a PC, but not to be a USB Mass Storage device.  Instead, you might use the existing quasi-serial interface that is the typical role of an Arduino-type board's USB port, to send or summarize the data, either directly or by interpreting it first.  This could either flow into a simple terminal program, or into something custom.  Typically this means less work on the Arduino side, more but more work on the PC side.  Additionally, since there is never a direct export of the card's block, the embedded system continues to have access to the card the whole time, rather than having to surrender control of the card to the PC operating system as USB Mass Storage requires.
A variation of the above could leverage the fact that if only the Arduino ever reads the card for its own purposes or to report the data to a PC, it doesn't necessarily need to store things in a PC compatible file system, or even in a file system at all.

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


text:
myserial.available() returns zero byte
I wrote an Arduino program that requires two ports for serial communication. I intended to use both hardware serial and software serial, but the problem is receiving data from receiving buffer of the software serial: it always returns zero byte from myserial.available().
For clarity I used the software serial example in Arduino IDE ver. 1.8.4.
I tried to change the baud rate but still the problem persists. I read somewhere that they made some code changes in the SoftwareSerial library's .cpp and .h files. I tried to find the site without success. And my PC where I installed those libraries was stolen. Before that it was working properly.
The mistake I made is that I just copied the code and pasted in the library without concentrating on it. Here is the example of program with two serial ports.
#include <SoftwareSerial.h>

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

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

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

What devices are your serial ports connected to? Can you add a clear photo of your wiring and devices.

Currently I'm using proteus 8 professional for simulation of the project, where I used arduino UNO and virtual terminal for serial transmitting and receiving. hardware serial port is connected to pins 0 and 1 and software serial port is connected to pins 2 and 3, and also I tried pins 10 and 11 as in example. hardware serial port has no problem and software it transmits without problem, but the problem is on receiving the bytes, myserial.available() returns zero bytes always. that means nothing detected in the receive buffer

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

Example

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

#define rxPin 10
#define txPin 11

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

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

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

The constructor does set the pinMode(): https://github.com/arduino/Arduino/blob/1.8.4/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L257-L284. The example sketches included with the library as well as most of the other example code in the reference don't set the pin mode. However, it has been suggested (https://github.com/arduino/Arduino/issues/3041) that doing this so early in the constructor is bad so whether setting the pin mode in setup() is necessary would depend on the implementation of init(). It shouldn't hurt (other than wasting memory) and it's worth a try.

On struggling to solve my problem I met that example I also tried to copy and make a trial but the problem continued. On the past days I read the solution of the same problem on Github and it solved my problem, but by that time I was a beginner I actually didn't catch up the solution they made in the library files, there were some amendments on some codes and it solved the problem, but right now the computer I installed the files was stolen and the sites I had seen the solution is not opening it end-ups with error that the site is not found.

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
Not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

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


text:
Cutting neopixel routine code short
I've been working on a level meter with a neopixel strip (WS2812).
The code is very simple: reading a potentiometer, mapping the input and showing the output in the led strip.
So far, so good. The code I include below is working fine but, obviously, ugly and repetitive.
Since my knowledge of programming is very weak, I wonder if there is any loop way to cut the code short. Please note that the seven led have different colours. Actually this is the confusing point for me to build a loop. Any idea, folks?
Yes, I also know that using so many delays isn't the mos elegant solution, but it does not compromise the device performance and the bar led appearing is quite nice.
void leveller () {
     int millivolts;
     int level;

     millivolts = analogRead(A3);

     level = map(millivolts, 0, 1024, 0, 7);
     if (level <=0){
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          strip.show ();
      }
      else if ((level > 0)&&(level<1)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
      }
      else if ((level>= 1)&&(level<2)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
      strip.show ();
      }
      else if ((level>= 2)&&(level<3)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
             delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
      strip.show ();
      }
      else if ((level>= 3)&&(level<4)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          }
      else if ((level>= 4)&&(level<5)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(5, 0, 128, 0);
          delay(30);
          strip.show ();
      }
      else if ((level>= 5)&&(level<6)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(5, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(6, 0, 128, 32);
          delay(30);
          strip.show ();
      }
      else if (level>= 6) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(5, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(6, 0, 128, 32);
          delay(30);
          strip.show ();
          strip.setPixelColor(7, 0, 128, 64);
          delay(30);
          strip.show ();
    }
}

simplest reduction .... do not repeat code unnecessarily .... you have if a>0 do x ... else if a>1 do x,y ... else if a>2 do x,y,z ......... instead do if a>0 do x ... if a>1 do y ... if a>2 do z

First, a small remark:

if ((level > 0)&&(level<1))

level is an integer, and there is no integer that is both strictly
larger than zero and smaller than one.

if ((level>= 1)&&(level<2))

There is only one integer that verifies this condition. It would be
clearer then to just write
if (level == 1)

Now, for your actual question: one trick that often works to shorten
repetitive code is to turn code into data, store the data in arrays and
run through them with loops. Here the sequence of colors can be stored
in an array:
const uint8_t colors[8][3] = {
    {128,   0,   0},
    {128,  32,   0},
    {128,  64,   0},
    {  0, 128,   0},
    {  0, 128,   0},
    {  0, 128,   0},
    {  0, 128,  32},
    {  0, 128,  64},
};

You can then call setPixelColor() within an loop that runs through the
array. As the end point of the loop depends on the measured level, it
could be written like this:
void leveller() {
    int level = map(analogRead(A3), 0, 1024, 1, 9);
    strip.clear();
    for (int i = 0; i < level; i++) {
        const uint8_t *color = colors[i];
        strip.setPixelColor(i, color[0], color[1], color[2]);
        strip.show();
        delay(30);
    }
}

Note that, since the output of analogRead() is always smaller than
1024, the variable level will always be smaller than 9, i.e. it will
take values between 1 and 8 inclusive. And that is the number of colors
that will be shown.

Brilliant! It worked fine at the first try. Thank you so much for your programming lessons. Best regards from Spain.

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


text:
If I try to pause my loop function my output screen starts printing trash
I am working of on a Wemos R1 D2 board with VL53L0X Laser Sensor. I need to stop my program after calculating an average of 50 readings but as soon as I try while(1) { } or any other method my output produces garbage.
void loop()
{
  float initial=0,inside=0,outside=0,sum=0,x;
  for (int i = 0; i < 10; i++) {
    x = sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
    sum = sum + x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
  while(1) {};
  Serial.flush();
}

I don't see the number 50 anywhere in your code. What happens if you don't try to pause it? Is the output OK then?

ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.
Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.
The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.
I would suggest adding a delay() or yield() to your while block will fix the problem.

There is nothing immediately obviously wrong with your program, but what happens if you do it a bit more "normally"?
By normally, just do nothing after the 10th (or 50th) time through, instead of the infinite loop you are currently executing.
int cntr = 0;
float initial=0,inside=0,outside=0,sum=0,x;

void loop()
{
  if (cntr < 10 /* or 50 */) {
    cntr++;
    x=sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) {
      Serial.print(" TIMEOUT");
    }
    sum=sum+x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
}

My reason for suggesting this is that when I tried an ESP board, there was an enourmous amount of bloatware included in the generated code. There may well be other stuff that needs to happen in the background between calls to the loop method. But you are preventing that from happening with your infinite loop.
However, clearly something is happening in the background because your infinite loop is somehow generating, as you put it,  "garbage".
You did not publish the  details of sensor library or its methods. Could there be any side affects there? What pins does the sensor connect to?


text:
Unresolved reference to public function from library
I have three libraries that I've written and I'm trying to use. They're stored as follows
Documents
├── Some/Path/To/Folder
│   └── firmware.ino
└── Arduino
    └── libraries
        ├── error
        │   ├── error.h
        │   └── error.cpp
        ├── lmp91000
        │   ├── lmp91000.h
        │   └── lmp91000.cpp
        └── tps7a7100
            ├── tps7a7100.h
            └── tps7a7100.cpp

Both lmp91000.h and tps7a7100.h have #include "../error/error.h" and are able to access variables and functions declared in error.h and error.cpp just fine.
firmware.ino includes all three libraries as you would expect them to be included and it is able to create instances of classes defined in both lmp91000 and tps7a7100 and use their methods (which depend on error). I am also able to create instances of a struct (ERROR) defined in error.h from firmware.ino, however I am not able to access functions from error.h and error.cpp. Error recived is
firmware.ino:19: undefined reference to `LOG_E(ERROR)'

However when I remove the guards in error.h that error no longer appears (implying that LOG_E can be resolved) but I get the expected errors of multiple definitions as there are multiple #include error.h.
My thoughts are that because of the guards error is not being included in a location where the sketch has access to the functions, but I may be completely off on that. I know there must be a way around this, as I'm able to access Wire.h for example from firmware.ino even though that is included in lmp91000.h - how do I solve this?
firmware.ino
#include <error.h>
#include <lmp91000.h>
#include <tps7a7100.h>
#include <Wire.h>

lmp91000 pot(12);
tpsa7100 vreg(10,9,8,7,6,5,4);

void setup() {
    Wire.begin();
    Serial.begin(115200);
    while(!Serial);
    vreg.enable();
    pot.enable();
    ERROR misc;
    misc.errorCode = 0x50;
    LOG_E(misc);
}

void loop() {
}

error.h
#ifndef error_h_included
#define error_h_included

#include "Arduino.h"

// Error Structure
typedef struct{
    int errorCode;
    char const *errorName;
    char const *errorDesc;
    bool isFatalError;
    bool shouldRetry;
}ERROR;

// Global error types
const ERROR E_SUCCESS = {0x00, "E_SUCCESS", "Success", false, false};
const ERROR E_INVALID_ARG = {0x10, "E_INVALID_ARG", "Invalid argument passed", true, false};
const ERROR E_I2C_NACK_ADDR = {0x20, "E_I2C_NACK_ADDR", "NACK on I2C address byte", false, true};
const ERROR E_I2C_NACK_DATA = {0x21, "E_I2C_NACK_DATA", "NACK on I2C data byte", false, true};
const ERROR E_I2C_BUFF_LEN = {0x22, "E_I2C_BUFF_LEN", "Transmit Data too long for I2C buffer", true, false};
const ERROR E_I2C_ERROR = {0x23, "E_I2C_ERROR", "Undefined I2C Error", true, false};
const ERROR E_I2C_TARGET_DISABLED = {0x24, "E_I2C_TARGET_DISABLED", "Target device for I2C comms disabled", false, false};
const ERROR E_I2C_READ_ERROR = {0x25, "E_I2C_READ_ERROR", "I2C Data could not be read", false, false};
const ERROR E_I2C_WRITE_ERROR = {0x26, "E_I2C_WRITE_ERROR", "Attempting to write zero bytes to I2C bus", false, false};

// Function Definitions
bool E(ERROR error_struct);
void LOG_E(ERROR error_struct);
ERROR WireErrorDecode(int code);

#endif

error.cpp
#include "error.h"

// Error Handling Functions

// E(ERROR)
// Evaluate the successfullness of the error
// Return 0 if error is a success error
// Return >0 if error is not success error
bool E(ERROR error_struct) {
    return (int)(error_struct.errorCode & 0xF0);
}

// LOG(ERROR)
// Log the error
void LOG_E(ERROR error_struct) {
    Serial.print(error_struct.errorCode);
    Serial.print("\t");
    Serial.print(error_struct.errorName);
    Serial.print("\t");
    Serial.println(error_struct.errorDesc);
}

// WireErrorDecode(code)
// Decode Wire.EndTransmission error codes
ERROR WireErrorDecode(int code) {
    switch(code) {
        case 0:
            return E_SUCCESS;
        case 1:
            return E_I2C_BUFF_LEN;
        case 2:
            return E_I2C_NACK_ADDR;
        case 3:
            return E_I2C_NACK_DATA;
        case 4:
            return E_I2C_ERROR;
        default:
            return E_INVALID_ARG;
    }
}

Update: These errors seem to be board specific - see question here

"... implying that LOG_E can be resolved". No, it does not imply anything like that. "Undefined reference" is a linker error. And without include guards you simply never get to the linking stage because of an avalanche of other errors.

check if guard defines are unique

Did you add library.properties files to your libraries? At least test moving all the library files into the sketch folder. That might give some additional information about the build on this "unique" Arduino :)

@MikaelPatel moving the libaries into the sketch folder does allow it to compile without error. I don't unerstand why that would make a difference though, as they were originally in the libaries folder of the Arduino path. Additionally why would it only have an impact on the 101 and not on any other board as descirbed in the linked question

Are you sure that the name error is not already taken by some existing library on 101? Try renaming your library from error to something else.

Next step is to turn on verbose mode when building in the Arduino IDE so that you get the actual compile and link command lines. Study the output and you will find your error.

The filename error.h is not a good name for a library. Some compilers and cores (such as the ESP32 and Curie cores) have a file error.h of their own which will be used in preference to yours.
Instead, name your library something more sensible.


text:
Arduino UNO and RS485 Communication Problem
I am learning Arduino, a beginner in programming. I want to use Arduino UNO to connect a wind direction sensor RS485. The problem is the output in the serial monitor, the return data from the wind direction sensor is unstable.

I need to get the return data from the wind direction sensor to get the wind direction. From the factory manual, they said sent a data to the sensor: 0x01 0x03 0x00 0x00 0x00 0x02 0xC4 0x0B and the sensor will return, like 0x01 0x03 0x04 0x06 0x48 0x00 0xA0 0x7A 0xD5
The wind direction dat at the above 5 and 6 position, the 0x00 0xA0 => 00A0H(HEX)=160 degree.
Tools:
Arduino Uno Board
Wind Direction Sensor
http://www.jnrsmcu.com/equipment/299.html
RS485 Board (3.3V)
https://www.waveshare.com/rs485-board-3.3v.htm
The following is my coding:
#include <SoftwareSerial.h>

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

void setup()
{
    RS485Serial.begin(4800);   // set the data rate
    Serial.begin(4800);
    Serial.println("Start");

    pinMode(12, OUTPUT);
    digitalWrite(12, HIGH);  // Init Transceiver
}

byte buf[8];

int byteReceived;

void loop()
{
    digitalWrite(12, HIGH);

    byte wind[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
    RS485Serial.write(wind, sizeof(wind));
    Serial.flush();
    RS485Serial.flush();
    // Serial.print(wind[0], HEX);
    Serial.println("Send");

    digitalWrite(12, LOW);
    delayMicroseconds(200);

    RS485Serial.readBytes(buf, 8);
    delay(10);
    Serial.println(buf[0], HEX);
    Serial.println(buf[5], HEX);
    Serial.println(buf[6], HEX);
    Serial.flush();
    RS485Serial.flush();
    delay (1000);
}

Connection map:

Is there any documentation available in English for this sensor?

It's probably SoffwareSerial not being able to respond fast enough to the incoming data in time. You should hook up a logic analyser and check that the data being sent does in fact differ from the data you are receiving. If so, then you really need to use a development board that has a hardware UART that you can use. I would never ever recommend using SoftwareSerial for anything, ever. Period. Exclamation mark.

You could use SoftwareSerial for sending the outbound packet, and the hardware UART for both receiving the response (on RX) and talking to the PC (on TX). May be not be elegant, but it should be more reliable that trying to read from SoftwareSerial.

@Majenko recommend to us, your peons, a well-rounded tactical budget logic analyzer (case not necessary)

I use a little usb dongle I got from Alibaba or somewhere for $5...

I would suggest you simplify your setup to the point where you have a 'working baseline  configuration', and then start building the system up one step at a time from there.
Start by eliminating the SoftwareSerial interface as a possible contributor to the problem.  Get an Arduino Mega with multiple hardware serial ports.
Next, verify that you can send characters to the selected hardware serial port and receive those same characters back when the Txn and Rxn lines (the 'n' here is the selected hardware serial port number) are connected via a jumper wire. This is called a 'loopback' configuration and is a basic serial comms troubleshooting technique (software serial ports don't support simultaneous transmit and receive, so they don't support loopback testing).  Don't proceed until you have this step completed successfully.
Next, get a second RS-485 module and extend your previous 'loopback' configuration with the hardware serial port on the Mega to include the two RS-485 modules.  Then you should be able to send characters out to one RS-485 module and receive the same characters back from the other, by connecting TXn to DI on one of the two RS-485 modules, and Rxn to DO on the other.
At this point you will have verified all the communications connections, so you can be confident that whatever you send will actually show up at the DO port of the RS-485, and whatever shows up at the DI port of the RS-485 will actually make it back to your serial console.  Now you can connect the sensor and figure out any issues do to data formatting, command sequences, and the like.
This basic 'cut the problem in half' building block technique will work on any system, large or small, simple or complex.
Frank

I don't see any connection between the sensor's GND and your Arduino's. This is likely the problem if they're not connected, since a common GND is necessary even with RS-485.
Check the sensor's power supply, make sure it's actually within the advised 10-30 V range. Also check the polarity of the differential lines.
Have you tried using the provided configuration software?
flush() does nothing for SoftwareSerial ports since they have no TX buffer, so you can just get rid of those lines, including the unnecessary Serial.flush()
Finally, your device datasheet says to wait for at least 200 milliseconds not microseconds, before checking for a response. Though it really shouldn't matter since you're using readBytes() after that, which waits for a second anyways by default, before giving up. Instead, use a bigger buffer, say 20 bytes, then try to read just 8 (the expected length) into it with readBytes():
byte buf[20];
int rlen = RS485Serial.readBytes(buf, 8);

Then try to print rlen which tells you how many bytes were actually read and also print the whole response to verify the packet format is as it should be. You should get enough info from this to at least eliminate a bunch of possible problems.


text:
Question About The Error In This Code
Could someone point out what exactly I'm screwing up here and provide a specific solution. Here's the error message:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

sketch_jul24g:38:11: error: expected ')' before '(' token
 (  pinMode(led, OUTPUT);     )
           ^

sketch_jul24g:38:30: error: expected unqualified-id before ')' token
 (  pinMode(led, OUTPUT);     )
                              ^

sketch_jul24g:39:1: error: expected declaration before '}' token
 }
 ^

exit status 1

expected ')' before '(' token

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

And here's the code:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
 #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

// Which pin on the Arduino is connected to the NeoPixels?
#define PIN        6 // On Trinket or Gemma, suggest changing this to 1

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 16 // Popular NeoPixel ring size

// When setting up the NeoPixel library, we tell it how many pixels,
// and which pin to use to send signals. Note that for older NeoPixel
// strips you might need to change the third parameter -- see the
// strandtest example for more information on possible values.
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

#define DELAYVAL 0 // Time (in milliseconds) to pause between pixels

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {
  // These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
  // Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  // END of Trinket-specific code.

  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
}

  // initialize the digital pin as an output.
(  pinMode(led, OUTPUT);     )
}

// the loop routine runs over and over again forever:
void loop() {
   pixels.clear(); // Set all pixel colors to 'off'

  // The first NeoPixel in a strand is #0, second is 1, all the way up
  // to the count of pixels minus one.
  for(int i=0; i<NUMPIXELS; i++) { // For each pixel...

    // pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
    // Here we're using a moderately bright green color:
    pixels.setPixelColor(i, pixels.Color(255, 255, 255));

    pixels.show();   // Send the updated pixel colors to the hardware.

    delay(DELAYVAL); // Pause before next pass through loop
  }
  pixels.setPixelColor(i, pixels.Color(255, 255, 255)); // turn the LED on (HIGH is the voltage level)
  delay(3);               // wait for a second
  pixels.setPixelColor(i, pixels.Color(0, 0, 0));    // turn the LED off by making the voltage LOW
  delay(8000);               // wait for a second
}

Like I said-what's going on? Thanks!

examine example code that is included with the Arduino IDE ... pay attention when you are looking at the code

Please pay attention when structuring your code and try to understand what opening and closing braces { } and parentheses ( ) are used for in C++.

use { pinMode(led, OUTPUT); } to create a new scope and if you don't need new scope just remove (, )


text:
i2c Connection for MCP4725(Dac) with Esp8266 wemos d1 mini
------------ This question has been edited ------------
note: Dac and Adc is12bits
my problem : I use two ESP. Using esp1, I read the Adc amount of the alternating signal (ECG) and send it to esp2 with UDP and I get it. Now, using the same amount of Adc, I would use the MCP4725 to convert the digital value of the Adc to the analog. But I don't know how to do it !

Do you need sine lookup table like default library example again ??!
If so, how is it done?!
I wrote the following code right now, what is your opinion?
Explain to me if my code is in error.

I just want the DAC output, to be the ADC signal input.
Code:
void loop () {

  int noBytes = Udp.parsePacket();
  String received_command = "";

  if ( noBytes ) {
    Udp.read(packetBuffer,noBytes);

    for (int i=1;i<=noBytes;i++)
    {
      received_command += char(packetBuffer[i - 1]);
    }
    int dac_value ;
    dac_value = received_command.toInt();
    Serial.print("dac value: ");Serial.println(dac_value);
    aPin = dac_value ;
    if (!si.i2c_start((I2C_7BITADDR<<1)|I2C_WRITE)) {
      Serial.println("I2C device busy");
      return;
    }

    else{
      Serial.println("i2c is worked");
    }

    for (byte i=1; i<noBytes; i++){
      si.i2c_write(aPin);
      si.i2c_rep_start((I2C_7BITADDR<<1)|I2C_READ);
      si.i2c_stop();
      delay(50);
    }
  }
}

I use #include <SlowSoftI2CMaster.h>.
si is: SlowSoftI2CMaster si = SlowSoftI2CMaster(4, 5, true);
Photo:

If the problem is how to interface the MCP4725, I recently answered a question about it, where is explained how to interface it correctly. Please read this. Also have a look at the Wire library and the MCP4725's datasheet

I'm waiting for answer..

Ok, I will explain the basic principles and give some tips. This won't be about your code, since it is neither compilable, nor does it make much of a sense to me.

The I2C Protocol: An I2C connection always needs 2 lines, SDA (which carries the data) and SCL (where the master outputs the clock signal). The communication always get's started by the master with a START CONDITION. Then it transmits the first byte, which consists of the 7 bits long address of the slave device and one bit, that shows if a read or a write operation will be performed. The slave - if there is any with that address - will then respond with an Acknowledgement. The master will transmit it's data and end the transmission with a STOP CONDITION or start a new transmission with a repeated start condition.
Choose the I2C library: You are using the SlowSoftI2CMaster library because it is architecture independent. As you are a beginner, you should use the SlowSoftWire library, which is a Wire-like wrapper library. It gives you the same interface, as the Wire library. That is good for beginners, since this hides some of the complexity and most examples and tutorials use the Wire library (so you can often copy the code structure). You have to install both libraries (SlowSoftI2CMaster and  SlowSoftWire) in your libraries folder, but you only need to include the SlowSoftWire library. Please look at the examples, that come with that library. I will refer to that library in the following points.
Using the SlowSoftWire library: You can declare and initialize the library as in it's simpleSlowWire.ino example. For transmitting a new value to the DAC, you have to first use beginTransmission() to configure the library for a master write transaction. Then place the data bytes in the libraries buffer with write(). And finally do the transmission with endTransmission() (this is the only place during this process, where the real I2C action happens on the bus). When you begin the transmission with beginTransmission() you must provide the correct address of the DAC. This is meant without the direction bit. The address of the MCP4725 consists of the device code 1100, the hardwired address pins A1 and A2, and the variable address pin A0. The hardwired address pins are most likely both zero, unless the manufacturer was ordered to program it otherwise (You can check the address with the scanner example). So, if you wire A0 to ground, the address will be 0b1100000. If you wire A0 to 3.3V, it will be 0b1100001. The direction bit will be handled by the library - you don't have to worry about it.

4.The MCP's data protocol: You cannot simply send the values from the ADC to the DAC. It except's a special data format, which includes command bits to determine it's mode of operation. I think, I have already described how the data is build up in principle and code pretty well in my answer to this question. If there is something special, that you don't understand, you can ask a new question and refer to that answer in it. Also I think, you should use the type unsigned int for the dac_value, since values from an ADC and values for a DAC both are positive only.
Please keep in mind, that building such projects needs some time investment, until you understand, what actually is happening there. If you use any chip, the datasheet of that chip is always a must read. I personally never haven't worked with the MCP4725. I just have read the datasheet. All information is already there.

Excellent description. That you said that the conversion of adc to analog can not be done easily, should the lookup table be used as adafruit examples? Or no?
So the code I wrote is not correct!

I don't know, what adafruit example you mean. Please provide a link. I don't see, where you would need a sine lookup table here, since you are just transmitting the signal from the ADC to the DAC. The DAC will output, what the ADC have read. A sine lookup table is only needed, if you want to generate a sine wave ftom the esp

this example link

I want to reconstruct the DAC  output using ADC value . . . . . . . .

Adc side wave form -->link

To just replicate the analog signal you don't need a lookup table

look this example : link

@navid And what should I see in that example? Also they are using an Arduino (most likely the Uno), not the ESP as you. So most likely you cannot simply use the same library

Ah, I shouldn't be disappointed ..


text:
Object Sensor on conveyor belt (want to record the data in EEPROM for testing)
void setup ()
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED_Blue_pin, OUTPUT);
pinMode(LED_White_pin, OUTPUT);

Serial.begin(9600);
digitalWrite(LED_Blue_pin, LOW);
digitalWrite(LED_White_pin, LOW);

void loop()
{
    long duration, cm;

    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(trigPin, LOW);

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);

    cm = microsecondsToCentimeters(duration);
    long distance = 70 - cm ;

    if (distance < 20) {
        Serial.println("NO ITEM");
        digitalWrite(LED_White_pin, HIGH);
    } else {
        digitalWrite(LED_White_pin, LOW);
    }

    if (distance > 20 && distance < 70) {
        digitalWrite(LED_Blue_pin, HIGH);
        Serial.print("Item : ");
        Serial.print(item++);
        Serial.println(" stk");
    } else {
        digitalWrite(LED_Blue_pin, LOW);
    }

    delay(1500);
}

long microsecondsToCentimeters(long microseconds)
{
    return microseconds / 29 / 2;
}

The code above is for the Ultrasonic Sensor HC-SR04. The sensor detects items that passes through and counts them along the way. The Blue Led indicates that the sensor detected an item while the White Led detects none. How can I store the data from HC-SR04 to EEPROM? The reason is, I just want to test it out before I sent the data from EEPROM to a database server. I'm still a novice at this.

You can use the EEPROM.write() function. There is a useful tutorial on the Arduino site.
The sample code from that tutorial is shown below:
/*
 * EEPROM Write
 *
 * Stores values read from analog input 0 into the EEPROM.
 * These values will stay in the EEPROM when the board is
 * turned off and may be retrieved later by another sketch.
 */

#include <EEPROM.h>

/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int addr = 0;

void setup() {
  /** Empty setup. **/
}

void loop() {
  /***
    Need to divide by 4 because analog inputs range from
    0 to 1023 and each byte of the EEPROM can only hold a
    value from 0 to 255.
  ***/

  int val = analogRead(0) / 4;

  /***
    Write the value to the appropriate byte of the EEPROM.
    these values will remain there when the board is
    turned off.
  ***/

  EEPROM.write(addr, val);

  /***
    Advance to the next address, when at the end restart at the beginning.

    Larger AVR processors have larger EEPROM sizes, E.g:
    - Arduno Duemilanove: 512b EEPROM storage.
    - Arduino Uno:        1kb EEPROM storage.
    - Arduino Mega:       4kb EEPROM storage.

    Rather than hard-coding the length, you should use the pre-provided length function.
    This will make your code portable to all AVR processors.
  ***/
  addr = addr + 1;
  if (addr == EEPROM.length()) {
    addr = 0;
  }

  /***
    As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an
    EEPROM address is also doable by a bitwise and of the length - 1.

    ++addr &= EEPROM.length() - 1;
  ***/

  delay(100);
}


text:
How to control segments with SevSeg library
The SevSeg library by Dean Reading seems to have a keyword to control individual segments on SSD's. I am using four common cathode, single digit displays. Does anyone know how to program individual segments?
#include "SevSeg.h";

SevSeg sevseg;

void setup() {
  // put your setup code here, to run once:

  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,
    resistorsOnSegments,
    updateWithDelays, leadingZeros, disableDecPoint);

}

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

  sevseg.setSegments();
  //sevseg.setNumber(1234,0);
  //sevseg.setChars("");
  //sevseg.blank();
  sevseg.refreshDisplay();

}

why did you not put a parameter into the setSegments() function call?

Because i don't yet know what parameter to put, or how to use the function.

tried that. displays a bunch of gibberish.

It is always the same if you just enter 1, or 2, or 25 etc.. I don't think that's how the function works. Displaying numbers with the setNumber function works perfectly however, so my displays are wired correctly.

what is unclear here https://github.com/DeanIsMe/SevSeg/blob/9cdc6d03d820ffbc18174921fb7bd0a3d030fd8b/SevSeg.cpp#L435

You can't with that library. The author has not provided any public methods that will do the job.
There are private methods (segmentOn and segmentOff) that might be usable, but you would have to modify the library to be able to access them.

Are 4 and 2 just arbitrary numbers you chose?

Yes. They are the segment number you want to turn on or off.

How would you specify which digit?

Probably with different numbers. Experiment and find out.

Last question.. Where should those functions be placed within the code? I'm getting "private within this context".

Actually, that looks like that might be the case. I have never used this library, so I was just reading the source code. It looks like the actual answer might be "You can't with that library". Damn.

The simple answer is probably to use a different library.

I wonder why he included the setSegment() function then. And yeah using a different library doesn't seem like a bad idea either.

He probably uses it internally.


text:
i2c high speed and pull-up resistors
hello guys i want to ask about 2 things
first one is i'm connecting and arduino uno attached to a usb host sheild and transferring data of a mouse coordinates to 10 arduino leonardo
i'm using the standard speed 100
normal mode
my wires is all about 10 cm long

i need to speed up the comm to fast mode
how to make this ? and the line of code where to put it in the code and in the master or slave ?

what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ? does it needs to disable it and put my own pull up resistors ?
i’m using wire library

i need to speed up the comm to fast mode how to make this

Wire.setClock(400000);

and the line of code where to put it in the code

Just after Wire.begin() in setup().  Wire.begin() sets the speed to 100,000 and you need to then override that afterwards to set it to 400,000 (or whatever speed you want to run at).

and in the master or slave ?

In the master, since it's the master that generates the clock.

what about the pull-up resistors ? does arduino uno includes built in pull-up resistors ?

Yes, but they're too high for reliable I2C operation. You should add your own resistors in the region of 1kΩ.

does it needs to disable it and put my own pull up resistors ?

No, yours will just be in parallel with them, with the net result of a small reduction of overall resistance.

so i need a total of 2.2k ohm ? is it good enough ? so i will check in the data sheet the internal one and calculate to be in the total 2.2 ?

Each of SCL and SDA need a pullup in the region of 1kΩ to 4.7kΩ. I use 1kΩ. That's 1kΩ each, not two 1kΩ resistors in series. The internal pullups are so big you can ignore them.

even if i’m having 10 slaves arduino leonardo i will put a1kohm on each scl and sda ?

There is only 1 scl and 1 sda.

yes i know that , i mean the external resistor is depending on the number of devices of slaves and the distance between them and the seed of clock so if there’s 10 slaves of leonardo of 50k ohm each internal resistor sobthe number is huge

With 11 devices each with 30-50kΩ pullups internally the total resistance without adding any external pullups will be between 2.2kΩ and 4.7kΩ approximately. You may get away without adding any external pullups in that case.


text:
Control multiple WS2812B strips with different leds count
First of all, my English is not that good so sorry if I made any mistake.
I'm using the WS2812FX, an awesome WS2812 effect library base on Adafruit NeoPixel library to make a small controller for the lightning in my bedroom.

The question here is how do I use this library to control multiple WS2812b led strip with different leds count, like one strip with 30 leds the other with 55 leds but the effect will just cycle through each individual led of each strip.IF somehow I can add one more output pin to this.
Example : There is an effect call "Larson Scanner" will light up one led then it run from the first led to the last led and go back, I want it to do the same on both strips, on the 30 leds strip it goes from first led to 30th led then go back & on the 55 leds strips it goes from first led to the 55th led at the same time.
Hope you guys understand what I'm asking :(
Link to the library : https://github.com/kitesurfer1404/WS2812FX

If you want the effect to be syncronized between the strips (Start and stop for both strips in the same time) you can use the same signal line to control them. In the last part, where only one strip has LEDs, only this one would light up

Which Arduino are you using?

goes from first led to the 55th led at the same time ... are you saying that both strips have to scan from end to end in the same amount of time?

You might also look at the FastLed library.
I used it to control 4 rings of 43 lights here
https://www.youtube.com/watch?v=CGOxbehyoM4
https://github.com/FastLED/FastLED

The WS2812 chip requires highly timing dependent pulses to work, as I describe on my page about Neopixels. We are talking about pulse widths of 350 ns.
I suggest it would be impossible to add another strip "if I can add one more output pin to this". It's not a question of adding pins, it's being able to output pulses that fast. You can't do it, at least not on the AVR Arduinos, and I doubt that the ones with faster chips would do it either.
What you could do is connect the various strips together so it is really one long strip (assuming they aren't too far away from each other). The different strips could usefully have their own power supplies, but the data and ground would need to go from the Arduino into the first strip, then out to the second one, and so on.
Something like this:

As for synchronizing the strips, well that is just programming. If you want the first LED on the 30-LED strip to light at the same time as the first LED on the 55-LED strips, then you actually would need to light LED #1 and LED #31 at the same time.

Possible alternative
Actually what might work would be to send to strip #1 first, and then strip #2 after changing pins. That means you would have to interleave the sends. For example to make a pixel seem to run backwards and forward on two strips you make it move one pixel on the first strip, then one pixel on the second strip, and so on.
I'm not sure if the library you mentioned supports that, since the LED count is in the constructor. It looks like it might, as you can change the number of LEDs and the pin number.
You might be able to make two instances of the library object (with different names), initialize them both, and then interleave the sends between them.

Your alternative approach works, if you don't need the effects too fast and precise. I've done this with 5 strips (each in its own pin) with 240 LED strips. But this also depends on how complex the calculation of your pattern is.

i had some animations that were choppy, then i tried on an ESP32 and whooaa nelly, I had to manually delay() it down. best led driver ever...

The library repo itself already describes "segments". So you simply connect the 55-part strip's data-in to the data-out of the 30-part strip. Instantiate as one 85-part strip, and then define the segments and set patterns on each as appropriate.

I had the same question!
=> Use an arduino per LED strip :)
and, if it is necessary to interconnect them to synchronize them
In short, work around the problem
translated by Google :(


text:
4 digit 7 segments display wrong number
I'm an Arduino newbie having problems with 4 digit 7 segments display.
I want to display some thousands to 4 digit 7 segments display but it display only 0000.
I want to receive data from serial with string. And display the data to 4 digit 7 segments display... So test make String = '2575'... but it's not work.
What's wrong in my codes?
Any suggestions here will be a great help. thanks
int segments[] = {A0, A1, A2, A3};

byte digits[10][7] =
{
  { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }  // 9
};

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

  for(int i=2;i<10; i++) {
    pinMode(i, OUTPUT);
  }

  for(int i=0; i<4; i++) {
    pinMode(segments[i], OUTPUT);
  }
}

void loop() {
  String IncomingData = "2575";

  for(int i=0; i<4; i++) {
    digitalWrite(segments[i], LOW);
    int digit = atoi(IncomingData[i]);
    displayDigit(digit);
    delay(5);
    digitalWrite(segments[i], HIGH);
  }
}

void displayDigit(int num){
  int pin = 2;
  for(int i=0;i<7;i++){
    digitalWrite(pin+i, digits[num][i]);
  }
}

Are  you sure you  have a common cathode display? Do you have current limit resistors on each segment pin?   Also, why do you have int for everything, when byte is all that is needed for a 0,1 or 0 to 9?  Try adding a Serial.print after this line int digit = atoi(IncomingData[i]); to see that digit is breaking out what you think it is.

use common anode display.  and int number display very well like displayDigit(5) but the code did not work... thanks

Code is setup for common cathode; low on the cathode to select the digit, high on the segments to turn them on.  If you are using common anode, then reverse the logic; high on the digit to select one, low on the segments to turn them on.

I use common cathode, sorry... and how can i fix it? Serial.print shows 00000000... I think use int for function displayDigit(int num)...

Fix it by reversing the logic:  High to turn on a digit, Low to turn it off. Flip all the 0s to 1s, the 1s to 0s in the digits array.

Change displayDigit(digit); to displayDigit(3); to see if the problem is in the string parsing, or in the led-displaying part.

displayDigit(3); works... string parsing problem... thanks

You call atoi() with a char. Parameter of atoi is const char*. To convert ASCII code of digit to the digit use
int digit = IncomingData[i] - '0'

i can't understand that... anyway apply IncomingData[i] - '0' ... it's not works... thanks

@김태정, int digit = IncomingData[i] - '0'

you do not know what is ASCII code? how characters are encoded? or you don't know why IncomingData[i] is char and can't be used with itoa?

woww@.@ it works! thanks a lot! How can I understand the theory...! Have a nice day!

how can i accept the answer?...


text:
Addressable LEDs vs Multiplexing for a Matrix
I would like to building a 8x64 RGB Matrix and connect it to my Arduino.
As this form factor does not really exist I would need to build one myself but now I am wondering if I should use addressable LEDs like WS2813 or APA107 and use FastLED or rather use 'dumb' LEDs and just multi-/charlieplex them using a MAX7221 or comparable chip.
What are some pros and cons I should consider with each one? I read that to many WS2813 can make problems but APA107 seem to fix that. But on the other hand most bigger matrices just use multiplexing........

the WS2813 would require way less hardware for interfacing

Cost would be one factor. Durability is another. When one of the addressable leds fail, all the leds after it would fail too (though the WS2813 has a BIN pin to "fix" that). I heard they aren't as reliable as dumb leds with separate drivers.

The smart RGB LEDs will be brighter. Each device has its own control chip that controls the 256 PWM level for each of the 3 LEDs. So for an 8x64 array, you send in 3 bytes/device, 8x64x3 = 1535 btyes, pause a few microseconds, and the array updates itself.
Going the multiplexing route, you would do something like have 64x3 = 192 anode drivers (or up to 192, if not all are LEDs are lit up) to enable the LEDs across the display, and then 8 common cathode drivers to turn on each row one at a time for 1/30 to 1/24 of a second for minimal flicker. So 192 LEDs, 20mA each, the common cathode needs to be able to sink 3.84A
On the otherhand, 8x64 LEDs, each needing up to 60mA at full on, = 30.72A.

You are assuming common cathode leds here. There are also common anode RGB leds. Secondly 643 x 8 isn't the only configuration possible. You could wire it as if it's a 323 x 16 matrix etc. The latter would require fewer chips, but would be less bright.

Any kind of multiplexing will be less bright. Common anode, common cathode, turned in rows, turned on as columns.


text:
How do I serial print a constant single string and a changing variable within it?
I want to print a single line including the variable "val" only once rather than looping or repeating of the same line and within it the val will change according to the reading. Is it possible? If so, how?

#define trigPin 5
#define echoPin 6

float distance(uint8_t T, uint8_t H);

void setup()
{
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    Serial.begin(9600);
    Serial.print("The object is: ");
}

void loop()
{
    float val = distance(32, 68);
    Serial.print(val);
    Serial.println(" cm away");
    delay(500);
}

Welcome to SE/Arduino! Please take the [tour] and read "[ask]". Then come back and [edit] your question. Please show us some code that you have. It can be the code that you want to run and that does not work. Tell us what you expect and what you get instead.

What? Sorry, I don't understand, what you mean

You want to print something like “result: 123”, and the replace “123” with other values within the same line, without printing other lines. Did I correctly guess what your question is about? PS: People shouldn't have to guess, you should put your best effort into making the question clear enough.

@EdgarBonet, what's the fun in that? Don't you want to play 20 questions? :)

within it [the already printed line] the val will change according to
the reading

This “within it” makes little sense. “Printing” is just sending bytes
through the serial port, and you don't choose where these bytes are
going: you just send them one at a time. The program you use as a
“serial port monitor” then displays those bytes in whatever manner it
sees fit. You cannot control from the Arduino where things get
displayed.
Or maybe you can...
If your monitor program can emulate an old school terminal, then
it can understand special control sequences, including escape codes,
that instruct it to perform specific actions, such as moving the cursor
or erasing part of the screen. Suitable terminal emulators include
screen on Linux and MacOS, and Putty on Windows. You may find
something appropriate for your mobile platform. Notably, the Arduino
serial monitor is not a terminal emulator, and doesn't interpret those
control sequences.
Assuming you are using a suitable terminal emulator, the simplest
solution to your problem is to just repeat the whole sentence “The
object is: xx.xx cm away” for every measurement, but do so by
overwriting the current line instead of moving to the next one. You thus
replace Serial.println() by Serial.print(), and precede each
sentence by a carriage return character (ASCII CR = 0x0d = '\r'),
which is interpreted as the command “move the cursor to the start of the
line”:
void loop() {
    float val = distance(32, 68);
    Serial.print("\rThe object is: ");  // note the '\r'
    Serial.print(val);
    Serial.print(" cm away");  // no println()
    delay(500);
}

There is a caveat here. If you overwrite a sentence (say “The object is:
10.07 cm away”) by a shorter one (“The object is: 9.92 cm away”, one
character less), the previous sentence will not be completely
overwritten, so you may end up with “awayy” showing on the display. This
can be overcome by ensuring a fixed-length formatting of the numbers
displayed, by padding with spaces, or by sending an “erase current line”
command to the terminal.
As a side note, what Serial.println() does is print what you
requested, followed by a CR character, and then a line feed character
(ASCII LF = 0x0a = '\n'). The line feed is interpreted by the
terminal as the command “move the cursor to the next line, without
changing its horizontal position”.
If you find it annoying to repeatedly print “The object is:”, you can
instead use more advanced control sequences. For instance:

“<ESC>[16G” means “move the cursor to column 16”
“<ESC>[K” means “clear from the cursor to the end of the line”

where <ESC> is the escape character:
void loop() {
    float val = distance(32, 68);
    Serial.print("\x1b[16G\x1b[K");  // "\x1b" is the escape character
    Serial.print(val);
    Serial.print(" cm away");
    delay(500);
}


text:
How to make Serial.read() return an integer instead of an ascii value?
I want Serial.read() to return an integer instead of an ASCII value. For example, in the below code if I input 2, I want the output as 2 instead of 50
void setup(){
    Serial.begin();
}

void loop(){
    if(Serial.available()){
    int t = Serial.read();
    Serial.println(t);
}

your code does not compile because of a syntax error

Serial.read() returns a byte ... what that byte means to you, is not realted to that fact

If it's a single digit:
if (t >= '0' && t <= '9') {
    int numeric_value = t - '0';
} else {
    // Handle the input error.
}

You can use an alternate method like this
void setup()
{
Serial.begin(9600);
}
void loop()
{
 if(Serial.available()){
    String a = Serial.read();
    int b = a.toInt();
    Serial.println(b);
}


text:
I want to create 10 levels with one button but this code shows only level 1?
#include <Adafruit_NeoPixel.h>
const int PIN = 4;
const int NUMPIXELS = 10;
const int BUTTONPIN = 6;
int buttonState = 0;
int PINState = 0;
int level = 1;
int dt = 100;
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.begin();
  pinMode(BUTTONPIN, INPUT);
  Serial.begin(9600);
}

void loop(void) {
Serial.println(buttonState);
  buttonState = digitalRead(BUTTONPIN);
  if (digitalRead(BUTTONPIN) == HIGH) {
    if (buttonState == 0) {
      buttonState = 1;
    } else {
      buttonState = 0;
    }
  }

  if (buttonState == 1) {
    opdracht(level);
  }
  else {
    if (level >= 10) {
      level++;
    } else {
      level = 1;
    }
    pixels.clear();
  }
}

//level 1
//void opdracht1() {
//  pixels.setPixelColor(0, pixels.Color(150, 0, 0));
//  pixels.setPixelColor(5, pixels.Color(0, 0, 150));
//  pixels.show();
//}

void opdracht(int x) {
  if (x == 1) { //level 1
    pixels.setPixelColor(0, pixels.Color(150, 0, 0));
    pixels.setPixelColor(5, pixels.Color(0, 0, 150));
    pixels.show();
  }

  if (x == 2) { //level 2
pixels.setPixelColor(8, pixels.Color(150, 0, 0));
pixels.setPixelColor(6, pixels.Color(150, 0, 0));
pixels.setPixelColor(1, pixels.Color(0, 0, 150));
pixels.show();
  }

I think if (level >= 10) { should be if (level < 10) {?

Your button reading code doesn't work. It only registers a button press if the button is pressed, when the code is exactly between the two digitalRead lines. Which is very unlikely. Try adding a few more variables, instead of trying to use the buttonState for three different purposes. Hint: use buttonState for the current state of the button; use something like oldButtonState for the state of the button in the last loop; and use something like buttonPressed to indicate when the button is first pressed down (which you then use to increment the level)

thank you! I will try to use the oldButtonState and buttonPressed.

You forgot to ask a question. So I will assume the intended question is
“Why does this code always show level 1?” and I will try to answer that.
The variable level is defined here:
int level = 1;

Its initial value is 1. Then it is updated here:
if (level >= 10) {
  level++;
} else {
  level = 1;
}

The first time this section of code runs, level has its initial value,
namely 1. The condition in the if evaluates to false, then the
statement
level = 1;

is executed, which assigns the value 1 to level (which has no effect,
as that was already its value anyway).
The next time that section of code runs, level has still the vale 1,
and the effect is the same as the previous time.

oow i understand it thank you!! what do i have to change to change the value?

@louisemoons: Under what condition do you want level to be incremented? Can you complete the sentence “level should be incremented if ...”?

Another, stronger hint. Your current code says "if level is greater than or equal to 10, increment it." It starts at 1, and no other code changes it, so that if statement will never be true. Don't you want to increment it if it is less than 10?

@EdgarBonet level should be incremented if pressing buttonpin


text:
Adding time in Serial Monitor
I need help in my Arduino project. I am trying to add the current time in Serial Monitor but i couldnt make it happen... I was also trying to do something like this...
Here is my current code right now...
// Purpose: To monitor the room temperature
// Programmer: Emmanuel Quiambao Sr.
// Date: Nov. 26, 2019

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// set the current time
// Set temperature parameter
const int hot = 85;
const int cold = 70;
const int motorPin = 7;
int switchState = 0;

void setup () {

  pinMode(A0, INPUT); // Temp sensor
  pinMode(10, OUTPUT); // Green Led
  pinMode(9, OUTPUT); // Yellow Led
  pinMode(8, OUTPUT); // Red Led
  pinMode(motorPin, OUTPUT); // Fan
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  Serial.begin(9600); // opens serial port
  Serial.println("Time Voltage Temperature");

 }

void loop(){

  int sensor = analogRead(A0);
  float voltage = (sensor / 1024.0) * 5.0;
  float tempC = (voltage - .5) * 100;
  float tempF = (tempC * 1.8) + 32;
  int reading = analogRead(A0);
  unsigned long curMillis = millis( );  // get current time

  Serial.print(" ");
  Serial.print(voltage);
  Serial.print(" \volts");
  Serial.print(tempF);
  Serial.print(" \F");

  Serial.print(curMillis);
  Serial.println( );
  delay(100);

  if (tempF < cold)            // Too cold
  {
  digitalWrite(10, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
  lcd.setCursor(1,0);
  lcd.print(" Too Cold "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd
  }

  else if (tempF >= hot)      // Too hot
  {
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, HIGH);
  lcd.setCursor(1, 0);
  lcd.print(" It's Hot "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd
  }

  else                        // Desired temperature
  {
  digitalWrite(10, LOW);
  digitalWrite(9, HIGH);
  digitalWrite(8, LOW);
  lcd.setCursor(1, 0);
  lcd.print(" It's Fine "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd

   switchState = digitalRead(9);
  if (switchState == HIGH) {
    digitalWrite(motorPin, HIGH);
  }
  }

  delay(5000);
}

What would be the time source for your Arduino? Do you have an RTC hooked up?

Sir, I just want to add the current time. also if possible maybe you can help me in fixing the columns of it like the one in the photo that i attached. i would like if possible to be "TIME VOLTAGE TEMPERATURE". I appreciate your prompt response.

I attached the temp sensor only. I apologize for my ignorance I am new to this project; what is RTC?

A real time clock. It's a device that can tell your Arduino what time it is.

Ow, i do not have that in my kit... just a question do I need an RTC if i just want to add the time in Serial Monitor? I just want to record the change of temperature every 10 secs?


text:
MPU-9250 compass always returns to zero
I am trying to build a 9-DOF IMU using the MPU-9250 chip which contains a gyro, accelerometer and compass. I have successfully realized 6-DOF sensor fusion using the DMP chip and Sparkfun's library, but I still have some yaw drift which is why I want to use its onboard compass for 9-DOF.
The DMP unfortunately can't do that so I tried kriswiner's work on 9-DOF sensor fusion which seemed to work but after I rotate the PCB, the yaw moves in the correct direction but it then slowly returns back to where it started, without me moving the PCB any more. This happens with many different sensor fusion libs, some more some less severe.
I have also tried just reading the raw mx and my values and reading the heading using atan2(my, mx) which made things a little better but still a 360° real-life rotation did not correspond at all to a 360° rotation on the chip.
Is this a known problem with the MPU-9250 and I am missing something completely obvious, or what could be wrong here?
Thank you for any help!

Ok, I have finally found the issue, and I am feeling very, very stupid.

I needed to calibrate the magnetometer with the figure-8 movement
I put a gigantic solid-metal 18650 Li-ion cell right next to the magnetometer chip...

EDIT: after replacing the 18650 with a polymer battery that is far away from the chip, things got a little better but both sensors in both devices still return garbage values.


text:
ESP8266-01S Stopped responding after second launch
Here's the code:
#include <SoftwareSerial.h>
#define RX 6
#define TX 5

String AP = "...";
String PASS = "...";

SoftwareSerial esp8266(RX,TX);

void setup() {
  Serial.begin(9600);
  Serial.println("Setup started");

  esp8266.begin(115200); // Change this to the factory baudrate used by ESP8266
  delay(1000);

  Serial.println("Setting BAUDRATE to 9600");
  esp8266.println("AT+IPR=9600");
  esp8266.begin(9600);
  delay(500);
  Serial.println("Setup finished");

  reset();
  connectWifi();
}

//reset the esp8266 module
void reset() {
  Serial.println("Resetting...");
  esp8266.println("AT+RST");
  delay(3000);

  if (esp8266.find("OK"))
    Serial.println("Module Reset");
  else
    Serial.println("Module Reset Failed!!!");
}

//connect to your wifi network
void connectWifi() {
  Serial.println("Connecting to Wifi...");
  String cmd = String("AT+CWJAP=\"") + AP + "\",\"" + PASS + "\"";
  esp8266.println(cmd);
  delay(4000);
  Serial.println("Checking Wifi...");
  int ctr=0;
  while(!(esp8266.find("OK"))) {
    if(esp8266.find("ERROR")) {
      Serial.println("Cannot connect to wifi...");
      break;
    }
    delay(50);
    ++ctr;
    if(ctr>10){
      Serial.println("Cannot connect to wifi...");
      break;
    }
  }
  Serial.println("ConnectWifi finished");
}

The ESP8266-01S wires are as follows:

GND to arduino ground
3v3 to arduino 3v3
RX to arduino pin 5
TX to arduino pin 6
EN to arduino 3v3

The thing worked for one time, and when I re-compiled and sent it again without any changes or even button presses, it stopped working. Furthermore, if I connect ESP module directly through arduino rx and tx and connect arduino reset to ground, I still don't get anything. The led on the esp is blinking during data transfers, but everything else doesn't change and I get no response at all.

You need to re-flash your AI Thinker firmware. AT+IPR kills certain versions of the firmware.
Install the latest version of the firmware and use AT+UART_DEF=9600,8,1,0,0 and AT+UART=9600,8,1,0,0. (The former sets the default baud rate, the latter the current baud rate).
You can read more here.

After resetting everything works through direct connection to PC, but when using a SoftwareSerial I get:
Setting BAUDRATE to 9600
Response Received:
Q⸮⸮E}⸮ʂb⸮b⸮,F⸮⸮⸮P%U⸮IT=N⸮⸮⸮L0
Qi⸮C!⸮CC⸮
============
Command Sent: AT
Response Received:
⸮⸮⸮⸮

Here's my setup:
void setup() {
Serial.begin(9600);
ESP8266.begin(115200);
delay(1000);
Serial.println("Setting BAUDRATE to 9600");
ESP8266.println("AT+UART_DEF=9600,8,1,0,0");
ESP8266.println("AT+UART=9600,8,1,0,0");
ESP8266.begin(9600);
}
`

Welcome to the wonderful world of dodgy at firmware. I would suggest you program the esp8266 to perform the task you require of it and not rely on the awful at firmware.


text:
Waking Arduino from sleep by holding button for more than 3 seconds
I am working on a battery powered Arduino project, where I need to put a standalone Arduino in sleep mode (to save some battery).
My aim is to put Arduino in sleep mode by holding a button for 3 seconds or more on pin 2 (hardware interrupt) and wake it up by holding the same button by 3 seconds or more.
I can put the Arduino to sleep by holding button more than 3 seconds, but I can't wake it from it by holding the button for 3 seconds.
Below is my code:
#include <avr/sleep.h>
const int led1 = 44;
const int led2 = 45;
const int led3 = 46;
const int usbState = 12;
float pressLength = 0;
const int button = 2;
int optionOne = 100;
int optionTwo = 3000;

void setup() {
  pinMode(button, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(usbState, INPUT);
  Serial.begin(9600);
}

void loop() {
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    sleepNow();     // sleep function called here
  } else if (pressLength >= optionOne) {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);
    while (1) {} //Keeps LEDS HIGH
  }
}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable(); // enables the sleep bit in the mcucr register
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  sleep_mode(); // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    SleepNow(); //Back to sleep fucntion
  } else if (pressLength >= optionOne) {
    sleep_disable();
    // first thing after waking from sleep: disable sleep...
    resetFunc();//Resetting
  }
}

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

Please help. Thanks.

with 2 resistors and a capacitor you can do that without code.

^How, where to attach cap and resistors and what values.?

You won't manage it without external circuitry.
The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.
For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

simulate this circuit – Schematic created using CircuitLab
In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.
Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.
To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.
If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.
R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.
This method is basically a very extreme form of debouncing.

There is no need at all for electronics here: you can perform all in software.
When you press the button, check it after 3 seconds. If it's still pressed => set the wakeup interrupt and then sleep.
Similarly. When you press the switch during sleep, you will wake up. Before doing anywhing, check after 3 seconds if the button is still pressed. Still pressed? => wake up (i.e. enable peripherals, etc), otherwise go to sleep.
Using electronics when you have already a MCU is wasteful.

@next-hack Read paragraph 2 of the answer. Anyway, waking the MCU for a few seconds may not be what is wanted since it will increase power consumption while the decision is being made - and this is only a couple of passives anyway, with zero idle current.

@next-hack Anyway, you're second guessing the OPs requirements. Yes, as in many things, there are multiple ways of performing the same or similar task. However the OP asked specifically about waking the MCU after 3 seconds of button press, not waking the MCU immediately then 3 seconds later deciding whether or not to stay awake. Personally I wouldn't do either, but would use an external small XLP MCU (such as a PIC10LF320) as a power management controller.

my fault, I missed the "However you could then sleep again if the button is released within 3 seconds.".
About second guessing, you're right too, still, sometimes, suggestions can be useful, e.g. to make someone realize that 3 seconds in which the MCU is active (possibly in a lower power-state, using a lower clock frequency, with everything disabled), will not have any noticeable impact in most cases.


text:
Visual Studio integration with Arduino
I use Visual Studio 2015 extensively for work, so it would seem like a logical choice for getting started with Arduino programming (though my C/C++ is rusty, that may take some time to get back). From what I understand the Visual Micro Plugin is popular. Is that sort of the de facto choice for those who come from VS? Does it tie into everything so that I can handle debugging, breakpoints, deployment etc from Visual Studio? Much obliged!

I think it is the de facto standard for VS (of course the default Arduino IDE is used most).
However, I think some advanced features (like breakpoint if I recall right) is only temporarily for free and you have to pay later for a subscription.
Note however, that debugging/breakpoints are not used often anyway since mostly it's more realtime controlled than PC applications.
If you need breakpoints etc. probably the easiest is to make stubs for some libraries and first develop the application not using Arduino and later use the Visual Micro plugin. [Update: it seems breakpoints are possible with vMirco, I never got them to work though].

OK well it's only $20 for a student license so I guess if I find I like that feature I could buy it. But it does output to Visual Studio right? Like if I write print("Jello World") in my code, does that get outputted to the Visual Studio Immediate Window?

I tried it just a few times (without breakpoints) but it worked perfectly ... I have the free version (not being a student). I don't think the output is write to the immediate window but to a specific window from vMicro.

You're not going to be able to use breakpoints except in some sort of simulator (if offered) or by buying a suitable hardware interface - they won't work with just they the everyday Arduino USB port interface.

It's been about a year, but the last I checked vMicro's breakpoints worked just fine (most of the time). It works by injecting code into your debug builds IIRC.

Use Atmel's Atmel Studio 7. Uses the visual studio shell and is supported by Atmel. Also allows you to import your Arduino Sketches. Once I used it, I stopped using the Arduino IDE.

How does debugging work? Are you able to attach to the process running on the andruino and step through it? What about print() commands, how are they outputted? Thanks!

For debugging you will need a debugger like the Atmel Ice which uses debug wire and interfaces with the Atmel Studio.  It's worth the money if you do a lot of coding. As for printf, there are tutorials on how to hook standard I/O into your code. The IDE is irrelevant that that case.

so I'm confused then, what is the benefit of this plugin if it doesn't support debugging out of the box? Not even println() statements?

Its not a plugin. Is an IDE built off the Visual Studio Shell. Its free. If you want to step up your game, use Atmel Studio and buy the Atmel ICE. IMO Visual Micro is junk.

I use Visual Micro and my opinion so far is that it works better than Atmel Studio, which I cannot get to work so far (at least to compile something with libraries without any problem).

Atmel Studio uses the same vMicro plugin that VS does to get Arduino support, so there's literally no difference here unless OP is interested in doing "raw" avr development.

@RubberDuck Atmel Studio doesn't use a plugin. It's built on the visual studio shell.

@PhillyNJ in order to get Arduino support it uses the vMicro plugin. Unless I'm thinking of v6 and they added it native in v7.

@RubberDuck AS7 has been out for over a year and it's built in


text:
Code to obtain PWM output
I tried code to obtain 100KHZ PWM output with a 41.66% duty cycle by reading an analog value from A0, which is compared with a reference 5V value for obtaining PWM value.
Can someone help me with the code? Any help is very much appreciated.
Here is my code.
int Pwmpin=9;//Pwm Output Pin
int Fchange= A0;//Frequency change through Potentiometer

void setup() {
  pinMode(Pwmpin, OUTPUT);//Pwm pin as Output
  Serial.begin(9600);
  TCCR1A=_BV(COM1A1)|_BV(COM1B1);//Non-inverted Mode
  TCCR1B=_BV(WGM13)|_BV(CS11);//Prescalar 8
}

void loop(){
  float freq=0;
  float count=10000,countt=0,Pinput=0;
  while(1){
    ICR1=count;//variable Frequency
    countt=16*count;
    freq= int(16000000/countt);
    OCR1A=int(count/2);
    Serial.print("Pwm Freq =");
    Serial.println(freq);
    count=10000;
    Pinput=analogRead(A0);//Read input value
    Serial.print("adc value is:");
    Serial.println(Pinput);
    Pinput=(Pinput/0.0113);
    Serial.print("pwm value is:");
    Serial.println(Pinput);
    count=count+Pinput;
    if(count>=100000) {
      count=10000;
    }
    delay(1000);
  }
}

And the question is?

It is difficult to help when we do not how the ADC value should relate to the PWM output.  However, keep in mind that ADC conversions are normally noisy and likely should employ techniques to reduce the noise.  Also, you might want to look at the micro processor's specifications for the specific processor on your specific Arduino (there are many different types).  The PWM values you stated may not be obtainable due to the granularity of the processor's PWM hardware.

You could get 41.6̅% duty cycle with a 12 MHz Arduino (do these even exist?). The closest you can get with a 16 MHz Arduino is 41.875%.

You appear to be trying to model an analog PWM generator circuit with an MCU - this is probably a bad idea, and would need a higher performance ADC at least.  If it all possible, simply using the internal timer to generate PWM digitally would be best.

Read the datasheet.
Figure out which pen mode works for you and which prescaler and top you need.
Set timer1 to that mode.

After that all you need is to load the duty cycle register with the desired value.
For your application leave the top value alone.
Your code is far from that.