text:
strip.clear() is not clearing/turning off the NeoPixel strip after resetting the ESP8266
In the code below which is running on a WEMOS D1 (ESP8266), a NeoPixel strip turns on 1 LED in red which moves left to right and then right to left whilst the board attempts to connect to Wi-Fi in the while (WiFi.status() != WL_CONNECTED) loop.
If I hold down the button 'SW' connected to the pin D7 and click the reset button, the code turns on the 7 segment display, however the LED on the NeoPixel strip which was last lit remains on (as though it is 'frozen'). Once I exit the while(configRPM > 0){ loop, all goes back to normal and the NeoPixel strip unfreezes.
I thought strip.clear() would clear the NeoPixel strip near the start of setup() but that does not appear to work. I thought adding a delay might fix it and it hasn't. Why is the NeoPixel strip not turning off when the board is reset and how do I fix it?
Here is the code:
#include <ESP8266WiFi.h> // Include the ESP8266WiFi library.
#include <ELMduino.h> // Include the ELMduino library.
#include <Adafruit_NeoPixel.h> // Include the Adafruit NeoPixel library.
#include <Encoder.h>
#include <TM1637Display.h>
#include <EEPROM.h>

// Define the addresses where you want to store your variables in EEPROM
#define ADDR_MINIMUMRPM 0
#define ADDR_MAXIMUMRPM (ADDR_MINIMUMRPM + sizeof(int))

#define CLK D1
#define DT D2
#define SW D7

#define CLK_TM1637 D5
#define DIO_TM1637 D6

TM1637Display display(CLK_TM1637, DIO_TM1637);
Encoder encoder(CLK, DT);

int configTriggered = 0;
int buttonReleased = 0;
int configRPM = 0;
int minimumRPM = 2500;
int maximumRPM = 6000;
int currentPosition = minimumRPM - 100;
int oldPosition = -1000;
int newPosition = 0;

// WiFi credentials and server details
const char* ssid = "WIFI_OBDII"; // Set the SSID of the ELM327.
WiFiClient client; // WiFiClient is a class that defines how to create objects that represent WiFi clients. client is an object of this class, allowing the ESP8266 to function as a WiFi client.
ELM327 myELM327; // Creates an object named myELM327 of the ELM327 class. This object represents an instance of the ELM327 OBD-II interface, allowing the program to interact with it using methods provided by the ELM327 class.

const int neopixel_Count = 16; // Indicates that there are 16 NeoPixels in the strip, with IDs ranging from 0 to 15.
Adafruit_NeoPixel strip(neopixel_Count, D8, NEO_GRB + NEO_KHZ800); // Initializes a NeoPixel strip object with 16 NeoPixels connected to pin D2, using the color order Green-Red-Blue and a data transmission frequency of 800 KHz.

const int potentiometer_Pin = A0; // Sets the constant variable potentiometer_Pin to A0, being the ID of the analog pin

int rpm = 0; // RPM variable which is taken from the car and used in the code.

void setup() { // Setup function to initialize NeoPixels and establish WiFi and ELM327 connections.
  pinMode(SW, INPUT_PULLUP);
  Serial.begin(9600);
  display.clear();

  strip.begin(); // Initialize NeoPixels.
  delay(100);
  strip.clear(); // Initialize all pixels to 'off'.

  EEPROM.begin(sizeof(minimumRPM) + sizeof(maximumRPM));
  EEPROM.get(ADDR_MINIMUMRPM, minimumRPM);
  EEPROM.get(ADDR_MAXIMUMRPM, maximumRPM);

  if (digitalRead(SW) == LOW){
    configRPM = 1;
    display.setBrightness(0x0f); // Set brightness to maximum
    delay(50);
  }

  while(configRPM > 0){
    if (digitalRead(SW) == HIGH) {
      buttonReleased = 1;
      delay(50);
    }

    if (digitalRead(SW) == LOW && buttonReleased == 1 && configRPM == 1) {
      buttonReleased = 0;
      configRPM = 2;
      minimumRPM = currentPosition;
      Serial.println("Value saved for minimum RPM is " + String(minimumRPM));
      currentPosition = maximumRPM;
      display.showNumberDec(currentPosition);
      delay(50); // Debounce delay
    }

    if (digitalRead(SW) == LOW && buttonReleased == 1 && configRPM == 2) {
      buttonReleased = 0;
      configRPM = 0;
      maximumRPM = currentPosition;
      Serial.println("Value saved for maximum RPM is " + String(maximumRPM));
      display.clear();

      EEPROM.put(ADDR_MINIMUMRPM, minimumRPM);
      EEPROM.put(ADDR_MAXIMUMRPM, maximumRPM);
      EEPROM.commit();
      EEPROM.end();

      delay(50); // Debounce delay
    }

    newPosition = encoder.read();

    if (newPosition != oldPosition) {
      if (newPosition > oldPosition) {
        currentPosition += 100; // Increase by 100 for each clockwise turn
      } else {
        currentPosition -= 100; // Decrease by 100 for each counterclockwise turn
      }

      // Limiting the current position within 0 to 9990
      if (currentPosition < 0) {
        currentPosition = 0;
      } else if (currentPosition > 9900) {
        currentPosition = 9900;
      }

      display.showNumberDec(currentPosition);
      oldPosition = newPosition;
    }
  }

  Serial.println("Connecting to " + String(ssid)); // Print the SSID in the serial monitor.

  WiFi.mode(WIFI_STA); // Set the Wi-Fi mode as 'station' where the ESP8266 act as a client of a network.
  WiFi.begin(ssid); // Initates the process for connecting to the Wi-Fi network of the ELM327.

  while (WiFi.status() != WL_CONNECTED) { // While the Wi-Fi status of the ESP8266 is not connectied to the ELM327 Wi-Fi network, execute the following code.
    movePixels("right", neopixel_Count, 100); // Move from the left most LED to the right most LED with a delay of 100 milliseconds.
    movePixels("left", neopixel_Count, 100); // Move from right most LED to left most LED with a delay of 100 milliseconds.
    Serial.print("."); // Print "." in the serial monitor.
  }

  Serial.println("\nConnected to Wifi. The IP address of the ESP8266 is: " + WiFi.localIP().toString()); // Print the IP address of the ESP8266.

  if (!client.connect(IPAddress(192, 168, 0, 10), 35000)) { // This line tries to connect the client object to a server at the IP address 192.168.0.10 and port 35000. If the connection fails, it executes the code inside the if block.
    Serial.println("Connection to ELM327 failed. Resetting and restarting the ESP8266."); // If the connection fails, print this line.
    ESP.reset(); //  completely resets the ESP8266 microcontroller, disconnecting it from any Wi-Fi network and restarting its setup process defined in the setup() function.
  }
  myELM327.begin(client); // Initialize ELM327.
}

void loop() { // Loop function to continuously read RPM and update NeoPixels.
  rpm = myELM327.rpm(); // Read the RPM from the ELM327.

  if (myELM327.nb_rx_state == ELM_SUCCESS) { // Check for ELM327 communication status. If successful, do the following.
    Serial.print("RPM: " + rpm); // Print the RPM to the serial monitor.
    updateNeopixels(rpm); // Update the NeoPixels based on RPM.
  } else if (myELM327.nb_rx_state != ELM_GETTING_MSG) { // Check if the ESP8266 is not currently receiving a message from the ELM327.
    myELM327.printError(); // Print ELM327 error if communication is not successful.
  }
}

void updateNeopixels(int rpm) { // Function to update NeoPixels based on RPM
  strip.clear(); // Clear all NeoPixels.

  if (rpm >= 2500 && rpm < 5900) { // If the RPM is between the two values, do the following. The max RPM for this loop is higher to make all LEDs red for between 5800 and 5900.
    // Specifying the number of LEDs on the left and right to create a converging effect.
    int leftIndex = map(rpm, 2500, 5800, 0, neopixel_Count / 2 - 1); // Map the RPM from 2500 to 5800 to the range of 0 to 7.
    int rightIndex = neopixel_Count - 1 - leftIndex; // Take the leftIndex from 15.

    // For example, if the RPM is 5800, leftIndex = 7 and rightIndex = 8.

    // Map RPM to colors
    int red = map(constrain(rpm, 2500, 5800), 2500, 5800, 0, 255); // Map RPM to the amount of 'red' of the LEDs. The higher the RPM, the more red.
    int green = map(constrain(rpm, 2500, 5800), 2500, 5800, 255, 0); // Map RPM to the amount of 'green' of the LEDs. The higher the RPM, the less green.

    // For example, if the RPM is 5800, red = 255 and green = 0. This will apply to all LEDs to be lit.

    // Left side of the strip
    for (int i = 0; i <= leftIndex; i++) { // The loop increments i by 1 whilst i <= leftIndex, moving towards the right end of the strip. i++ is done after the body of the loop completes.
      strip.setPixelColor(i, strip.Color(red, green, 0)); // Set the color of the NeoPixel matching the ID of i.
    }

    // Right side of the strip (mirroring the left side)
    for (int i = neopixel_Count - 1; i >= rightIndex; i--) { // The loop decreases by 1 whilst i >= rightIndex, moving towards the left end of the strip. i-- is done after the body of the loop completes.
      strip.setPixelColor(i, strip.Color(red, green, 0)); // Set the color of the NeoPixel matching the ID of i.
    }

  } else if (rpm >= 5900) { // If the RPM is at least 5900, do the following.
    for (int i = 0; i < neopixel_Count; i++) { // The loop increments i by 1 whilst i < neopixel_Count (16) as you can't send a single command to change the colour of all LEDs.
      strip.setPixelColor(i, strip.Color(255, 0, 255)); // Set the color of each NeoPixel to purple.
    }
  }
  strip.setBrightness(map(analogRead(potentiometer_Pin), 0, 1023, 0, 255)); // Map the potentiometer value to brightness range (0-255) and set the strip brightness accordingly. 1023 is the max value obtainabled from the analog-to-digital (ADC) converter.
  strip.show(); // Update the NeoPixel strip.
}

void movePixels(String direction, int numPixels, int delayTime) { // Function to move NeoPixels from left to right and then right to left.
  for(int i = 0; i < numPixels; i++) { // The loop increments i by 1 whilst i < numPixels (16).
    int index;
    if (direction == "right") { // If direction is equal to 'right'...
      index = i; // Set index to i.
    } else if (direction == "left") { // If direction is equal to 'left'...
      index = numPixels - 1 - i; // Set index to numPixels (16) - 1 - i.
    } else { // Handle an invalid direction input (neither right or left).
      return; // Exit the function with no response.
    }
    strip.setPixelColor(index, strip.Color(255, 0, 0)); // Set the LED which shares the ID of index as red.
    strip.setBrightness(map(analogRead(potentiometer_Pin), 0, 1023, 0, 255)); // Map the potentiometer value to brightness range (0-255) and set the strip brightness accordingly. 1023 is the max value obtainabled from the analog-to-digital (ADC) converter.
    strip.show(); // Update the NeoPixel strip.
    delay(delayTime); // Adjust the delay based on potentiometer value.
    strip.setPixelColor(index, 0); // Turn off the LED at the current position.
  }
}

I thin you need to call strip.show() also when using clear

We can have a look at the clear() function inside the Adafruit_Neopixel library. In Adafruit_Neopixel.cpp you can find at line 3396 (searching for clear(void) will get you there):
void Adafruit_NeoPixel::clear(void) { memset(pixels, 0, numBytes); }

This is a very short function. memset() sets all bytes in a defined range to the provided value. So all bytes in pixels will be set to zero. Though this is only the libraries internal memory. There is no IO action here, no code sending data to the Neopixels.
That means: clear() only acts on the libraries internal representation of the strip, just like setPixel() and its siblings. To actually send the data to the Neopixels you still need to call strip.show(), which then takes the libraries internal representation of the strip and sends the data out through the digital pin to the Neopixels.
I want to encourage people to look into the source code of libraries, they use. When you learn how to read them, you can get quick answers even without understanding the actual full implementation of the library.

Thank you very much for your response @chrisl, much appreciated!


text:
Elegoo Nano timer prescaler problem
I am trying to use Timer2 on an Elegoo Nano to produce a "tick" interrupt every 10uS. My plan was to set Timer2 to CTC mode with a /8 prescaler (to get a timer clock of 2MHz from the 16MHz chip clock) and a compare value of 19 (to reset the timer every 20 counts) which should trigger the compareA ISR at 100KHz (every 10us). The problem is that only prescale values of 64 or greater work as expected. Setting the prescaler  to any value lower than 64 actually results in the "tick" interval getting much longer (10 times the interval or more). I have carefully studied the ATmega628 datasheet to see if I am configuring every register correctly, but I don't see anything wrong with what I am doing. Here is my code...
void initTimer() {

    // ---Disable interrupts during timer initialization
    cli();

    // ---Counter compare value (make CTC interrupt fire every 10uS)
    OCR2A = 19;

    // ---Clear TCCR A register (not used)
    TCCR2A = 0;

    // ---Enable CTC mode with divide-by-8 prescaler
    TCCR2B = _BV( WGM22 ) | _BV( CS21 );

    // ---Enable Timer2 CTC interrupts for compare A match
    TIMSK2 |= _BV( OCIE2A );

    // ---Initialize timer 2 to zero (not really needed in my situation)
    TCNT2 = 0;

    // ---Turn interrupts back on
   sei();
}

SIGNAL( TIMER2_COMPA_vect ) {

    /*
    ** This should execute every 10uS, but for prescaler values
    ** below 64 the interval is many times longer than expected.
    */
}

Can anyone point out my mistake?

Ok, I figured it out. It wasn't my timer initialization that was wrong, it was when I was doing it. Although I didn't show it in my original code sample, my initialization function actually returns a dummy boolean value so I could call it automatically if the .cpp file containing the function and the ISR is included in the project, like this...
bool initTimer() {

    // ---Set up the timer for CTC interrupts with a 10uS period
    ---
    ---
    ---

    // ---This return value is necessary, but ignored
    return true;
}

bool dummy = initTimer();

That final line calls initTimer() during Arduino boot just by including this source file in the project. It's a nice way to "auto-configure" utility objects without needing to explicitly call an initialization function. The boolean dummy return value from initTimer() is needed since C/C++ compilers choke on calling functions this way without storing a return value.
void initTimer() {

    // ---Do stuff...
}

// ---The compiler can't digest this...
initTimer();

Anyway, I have used this technique many times over several decades in desktop and mobile applications, so I did it in this Arduino project without giving it too much thought, but I failed to consider that it would execute the timer2 initialization BEFORE the Arduino setup routines. Anything I did to timer2 was being overwritten by the Arduino boot code which ran after my initTimer() function. My initialization was having some effect on the operation of timer2 because the Arduino boot setup assumes the timer2 config registers are starting off empty (zeroed) so it just sets config bits without clearing everything first. Any bits I turn on stay on, but Arduino boot up sets additional bits so the resulting timer configuration is unpredictable. The solution was simple... call the initTimer() function from the standard Arduino setup() function instead to ensure it executes LAST.

Can anyone point out my mistake?

Your mistake is in thinking that it's possible to do more than you can within a 10uS period.
At 16MHz each instruction takes 63ns (for single-clock instructions). 10nS gives you a maximum of (10,000 / 63) 156 assembly instructions.  Into that you have to fit the preamble and postamble to store the registers to the stack and retrieve them again.
The remaining clock cycles (maybe no more than 100) won't give you much time to do complex things. And given that many of the Arduino API calls are quite heavyweight, even just something as "simple" as a digitalWrite() can overflow that many times over.

Thanks Majenko, I had considered that, but since my ISR just decrements a few countdown variables I figured I could probably get away with it. See the answer I posted to my own question... I was configuring the timer correctly but I was doing it in a way that it was happening before the Arduino boot setup code had run so my settings were being overwritten when the Arduino routines configured timer2. After I changed my code to call the my timer2 initialization from setup() instead, a 10uS ISR interval is working fine.

source: Stack Exchange

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

sort: votes


text:
If/Else Statements on Arduino not executing
I have a bit of code below, the problem is only the first 'if' statement will execute when called on. When I call on u, q, or any of the other if statements it will go straight to the else and not execute. Tried switching the following ifs to 'else if' but got the same result.
#include "Arduino.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include "DHT.h"

DHT dht1(3, DHT11);
DHT dht2(2, DHT11);

void setup()
{
  pinMode(13,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(4,OUTPUT);
  digitalWrite(13,LOW);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(9,LOW);
  digitalWrite(8,LOW);
  digitalWrite(7,LOW);
  digitalWrite(6,LOW);
  digitalWrite(5,LOW);
  digitalWrite(4,LOW);
  Serial.begin(9600);
  dht1.begin();
  dht2.begin();
}

void loop()
{
  float DHT11_t = dht1.readTemperature(true);
  float DHT21_t = dht2.readTemperature(true);

  if(Serial.read() == 'u')
  {
    Serial.println();
    Serial.print(DHT11_t,1);
    Serial.println();
    Serial.print(DHT21_t,1);
    Serial.println();
  }

  if(Serial.read() == 'c')
  {
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
    Serial.print("NDX");
    Serial.println();
    Serial.print("u");
    Serial.println();
  }

  if(Serial.read() == 'q')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
    Serial.print("STX");
    Serial.println();
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    Serial.print("NDX");
    Serial.println();
    Serial.print("u");
    Serial.println();
  }

  if(Serial.read() == 'w')
  {
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
  }

  else if(Serial.read() == 'e')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
  }

  if(Serial.read() == 'r')
  {
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
  }

  if(Serial.read() == 't')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
    delay(30000);
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    delay(750);
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
    delay(30000);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
  }

  if(Serial.read() == 'y')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
    delay(30000);
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    delay(750);
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
    delay(30000);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
  }

  else
  {
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
  }

}

We already told you that it is not working: https://arduino.stackexchange.com/questions/56646/simple-timings-in-arduino-code

Serial.read() takes the first byte out of the serial buffer. Once it's executed, this byte is gone, so the Serial.read() in the next if statement will fetch the next byte (if available). What you can do is assign the result of Serial.read() to some variable before the first if statement, and then use that variable instead of Serial.read() in the if statements.

Can you post the fix? I tried defining the var but got 'not declared in this scope'

@nuggetchris Please take a look at the example from https://www.arduino.cc/en/Serial/Read. It should work if you put your if statements after incomingByte = Serial.read(); (inside if (Serial.available() > 0) { }).

And this is also switching Serial.read() == x within the if statement with incomingByte == x?

@nuggetchris: Yes. Sorry, I forgot to mention it.

Ok, it seems to work as long as I define a data type before incomingByte. Since it's only letters, I went with char. Only problem now is, the serial.printed letters the program produces, such as in the 'u' in the if statements, it doesn't seem to recognize. It only prints the 'u' but does not execute what the 'u' is stated to execute in the first if statement

Technically could insert logic directly in place of the call but if I could streamline it as planned would be much better

@nuggetchris: I'm not sure why it doesn't recognize characters in the if statements. You are using == inside if(), right? Try the following minimal example: https://pastebin.com/raw/tFrRYceK. I've tested it, and it works ok.

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


text:
7 segment multiple display, only display 1 digit
I try to create a display so that when I press the button, the counter is increased by one. The problem is only one of them light up and it is not showing the correct output, it is showing the combination of both digit (e.g. 01 showing 0, 02 showing 8). Here is my full code.
const int a = 8;  //For displaying segment "a"
const int b = 9;  //For displaying segment "b"
const int c = 4;  //For displaying segment "c"
const int d = 5;  //For displaying segment "d"
const int e = 6;  //For displaying segment "e"
const int f = 2;  //For displaying segment "f"
const int g = 3;  //For displaying segment "g"
const int D1 = 7;
const int D2 = 13;

bool bPress = false;
const int IncbuttonPin = 10;

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonPushCounterD1 = 0;
int buttonPushCounterD2 = 0;

int IncbuttonState = 0;
int lastIncbuttonState = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(a, OUTPUT);  //A
  pinMode(b, OUTPUT);  //B
  pinMode(c, OUTPUT);  //C
  pinMode(d, OUTPUT);  //D
  pinMode(e, OUTPUT);  //E
  pinMode(f, OUTPUT);  //F
  pinMode(g, OUTPUT);  //G
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);

  pinMode( IncbuttonPin , INPUT_PULLUP );
  Serial.begin(9600);

}

void loop() {

   IncbuttonState = digitalRead(IncbuttonPin);

   checkIncButtonPress();

  if( bPress ){
    bPress = false;
     turnOff();
     lightDigit1(buttonPushCounterD1);
     delay(5);
     lightDigit2(buttonPushCounterD2);
     delay(5);
  }
}

void checkIncButtonPress()
{
   // compare the IncbuttonState to its previous state
  if (IncbuttonState != lastIncbuttonState) {
    // if the state has changed, increment the counter
    if (IncbuttonState == LOW) {
      // if the current state is HIGH then the button went from off to on:
      bPress = true;
      buttonPushCounter++;
      buttonPushCounterD1 = buttonPushCounter / 10;
      buttonPushCounterD2 = buttonPushCounter % 10;
      Serial.println("on");
      Serial.println(buttonPushCounterD1);
      Serial.println(buttonPushCounterD2);

    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastIncbuttonState = IncbuttonState;

}

void lightDigit1(byte digit) {
  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  displayDigit1(digit);
}

void lightDigit2(byte digit) {
  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  displayDigit2(digit);
}

void displayDigit1(byte digit)
{
 //Conditions for displaying segment a
 if(digit!=1 && digit != 4)
 digitalWrite(a,HIGH);

 //Conditions for displaying segment b
 if(digit != 5 && digit != 6)
 digitalWrite(b,HIGH);

 //Conditions for displaying segment c
 if(digit !=2)
 digitalWrite(c,HIGH);

 //Conditions for displaying segment d
 if(digit != 1 && digit !=4 && digit !=7)
 digitalWrite(d,HIGH);

 //Conditions for displaying segment e
 if(digit == 2 || digit ==6 || digit == 8 || digit==0)
 digitalWrite(e,HIGH);

 //Conditions for displaying segment f
 if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
 digitalWrite(f,HIGH);
 if (digit!=0 && digit!=1 && digit !=7)
 digitalWrite(g,HIGH);
}

void displayDigit2(byte digit)
{
// digitalWrite(D1, HIGH);
// digitalWrite(D2, LOW);
 //Conditions for displaying segment a
 if(digit!=1 && digit != 4)
 digitalWrite(a,HIGH);

 //Conditions for displaying segment b
 if(digit != 5 && digit != 6)
 digitalWrite(b,HIGH);

 //Conditions for displaying segment c
 if(digit !=2)
 digitalWrite(c,HIGH);

 //Conditions for displaying segment d
 if(digit != 1 && digit !=4 && digit !=7)
 digitalWrite(d,HIGH);

 //Conditions for displaying segment e
 if(digit == 2 || digit ==6 || digit == 8 || digit==0)
 digitalWrite(e,HIGH);

 //Conditions for displaying segment f
 if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
 digitalWrite(f,HIGH);
 if (digit!=0 && digit!=1 && digit !=7)
 digitalWrite(g,HIGH);
}

void turnOff()
{
  digitalWrite(a,LOW);
  digitalWrite(b,LOW);
  digitalWrite(c,LOW);
  digitalWrite(d,LOW);
  digitalWrite(e,LOW);
  digitalWrite(f,LOW);
  digitalWrite(g,LOW);
}

when I remove the code
     lightDigit1(buttonPushCounterD1);
     delay(5);

It is showing the correct output, but only for 1 digit.
Anyone can help me on this? Thanks.

You aren't multiplexing your displays properly.
At the moment you are doing:

Do nothing until the button is pressed
Switch on display 1
Turn on the segments for digit 1
Wait 5ms
Switch off display 1
Switch on display 2
Turn on the segments for digit 2
Wait 5ms
Go to 1

For about 5ms you will get a brief flash on one digit, but since you don't turn off the segments you turned on for that digit they are just added to for the second digit - which you display for an extended period.
To multiplex properly you must:

Turn off segments that are no longer used for the current display (best to turn them all off)
Repeatedly display both digits all the time.

Ideally your method would be:

Turn off all segments
Turn on segments for digit 1
Turn on digit 1
Delay 5ms
Turn off digit 1
Turn off all segments
Turn on segments for digit 2
Turn on digit 2
Delay 5ms
Turn off digit 2
Go to 1 (usually the loop() handles that for you).

And separate to that you handle your button press and changing the value to display.
Also note the turning off of a digit before arranging the segments for the next digit. This prevents ghosting where you get a faint impression of the previous digit overlaid on the current digit.


text:
How do I use PlatformIO to flash ESP-12F (ESP8266MOD)
In PlatformIO while creating a project , in the board selection there is no ESP-12F in the boards. While there is ESP-12E. I can flash ESP-12F while choosing ESP-12E from the boards without any flashing issue. But there are some runtime issues, the one that I noticed is the LED doesn't blink when flashed from PlatformIO , but works fine, when flashed using Arduino IDE using the same code.
So there may be some difference in the configurations.

C:\Users\USER\.platformio\platforms\espressif8266\boards

In this directory I found the esp-12e board which is a JSON format.
{
  "build": {
    "core": "esp8266",
    "extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP12",
    "f_cpu": "80000000L",
    "f_flash": "40000000L",
    "flash_mode": "dio",
    "ldscript": "eagle.flash.4m1m.ld",
    "mcu": "esp8266",
    "variant": "nodemcu"
  },
  "connectivity": [
    "wifi"
  ],
  "frameworks": [
    "arduino",
    "simba",
    "esp8266-rtos-sdk",
    "esp8266-nonos-sdk"
  ],
  "name": "Espressif ESP8266 ESP-12E",
  "upload": {
    "maximum_ram_size": 81920,
    "maximum_size": 4194304,
    "require_upload_port": true,
    "resetmethod": "nodemcu",
    "speed": 115200
  },
  "url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
  "vendor": "Espressif"
}

How do I add ESP-12F to the PlatformIO boards and flashing without any issue.

Ask platformIO... it's their responsibility to keep their boards packages up to date for their platform...

@Majenko Thanks for the direction!! :)

At the PlatformIO community I asked the same question, and pfeerick  suggested to add a build flag.

It’s most likely the onboard LED is on GPIO2, not GPIO1 so try adding
build_flags = -D LED_BUILTIN=2 to your platformio.ini … hopefully that
  kicks in before the pins_arduino.h defintion.

But It didn't did the trick.
And the compiler throws a bunch of warnings.
What I did to make it work is to ignore LED_BUILTIN constant and use 2 instead.
#include <Arduino.h>
void setup() {
 pinMode(2, OUTPUT);
}

void loop()
{
  digitalWrite(2,LOW);
  delay(200);
  digitalWrite(2,HIGH);
  delay(200);
}

The build flags shouldn't have a space after the "D".
build_flags = -DLED_BUILTIN=2


text:
ESP8266 Software serial to ATmega 328 is not properly working
Thanks in advance..
We are having esp8266-12E chip and Atmega328 connected as follows,
ESP 12 pin as Tx,13 pin as Rx && Atmega328 13pin as Rx, 12pin as Tx. Everything works fine, but while communicating via serial some low pulse is being generated. We couldn't find the issue with multimeter anyway but got it by oscilloscope signal.
When this false low pulse during communication happens Atmega328 connected pins also getting low for the same duration.
We tried using separated logic execution for ESP and Atmega and both were worked perfectly, but only during communicating via Software serial its flickers getting started.
Please help us getting this resolved.

esp8266 SoftwareSerial doesn't work reliably

@Juraj: Thanks. Can I use default Tx and Rx? are those reliable?

yes of course. esp8266 has second hw Serial interface, but only TX of it can be used

That means I can transmit data to Atmega328 but could not get it back.

low pulse is being generated where is it being generated?

@jsotola, I read that esp8266 SoftwareSerial doesn't work reliably , but I never tested it. perhaps this 'low pulse' is an indices why it doesn't work. but I don't have time to investigate it

i did not ask a clear question .... the question is which pin generates the low pulse?

@jsotola, I wasn't clear too. connect an Uno to esp8266 over SoftwareSerial and you will know.

@jsotola, I did not say it will not work. It will work perfectly, but is not reliable

Don't use SoftwareSerial in esp8266. Connect the 328p's SoftwareSerial pins to Serial interface pins of the esp8266. ESP8266 has second Serial interface named Serial1. It has only TX (io 2), but it is enough for debug prints.
To change the firmware or sketch in esp8266 you can use ArduinoOTA library, but you should be ready to disconnect the esp8266 Serial pins from the 328p and use them for Serial upload if the OTA upload fails.
You should use logic level converter from 5 V to 3.3 V to protect the esp8266 RX pin.

Many thanks Juraj. It’s solved our problem. Many many thanks as we are struggling with this quite many days.


text:
ATMega328 AU bootloader burning issue using Nano
We are trying to burn bootloader into ATMega328P-AU SMD. We have taken the reference of the link and did the same. We checked wire connections and all looks fine and we tried with two chip with two separate boards and we got same result.
But we tried many times and got the same error as follows,
Could someone help us on this?
    /data/install/arduino-1.8.8/hardware/tools/avr/bin/avrdude -C/data/install/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

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

         System wide configuration file is "/data/install/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/sankar/.avrduderc"

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x15
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : Arduino
         Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
         Hardware Version: 4238814
         Firmware Version: 24405360.0
         Topcard         : STK502
         Vtarget         : 1.8 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

avrdude done.  Thank you.

Error while burning bootloader.

did you research the error?

in your output two avrdude processes run parallel. let one finish before starting again. do you use "Arduino as ISP"? https://www.arduino.cc/en/Tutorial/ArduinoISP

@Juraj yes. We uploaded ArduinoISP to nano first, then we change options to Arduino as ISP to burn bootloader. When that happens only we get error.

try a capacitor to suppress the auto-reset of Nano. in the link in my first comment see the instructions for Mega as programmer on how to add the capacitor. other option is to make this change in programmers.txt https://github.com/arduino/ArduinoCore-avr/pull/56/commits/a901b081aed0c60e97777c9c92350d354b721094

@Juraj: It’s working fine after changing the programmers.txt. Can you put it as answer so that I will accept..?

@per1234, this is for you to answer


text:
Bootloader difference between Atmel328p(through hole) and Atmel328p au(smd)
It’s been bugging me lot that Can’t we burn the same bootloader for both 328p and 328p au?
I got confused when I see this linksmd 328p au bootloader burn.
Will there be any impact on performance or any other impact if I use same bootloader for both?

AFAIR the bootloader is the same for both chips.

My question is, I read if we burn 328p bootloader to smd 328p au, it might not perform well. That’s how I got this url as a reference. Because Uno is having through hole chip with 28 pins and smd 328p is having 32 pins. I’ll update where I read that smd chip 32 pins might not perform well if we upload 328p through hole chip bootloader.

Your link does not mention explicitly, which bootloader is used. The IDE allows to choose different boards, which refers to different sections in boards.txt There the address of the appropriate bootloader is found. Uno and Nano should refer to the same optiboot/optiboot_atmega328.hex

@DataFiddler, the tutorial is before Nano had a bootloader selection.

The bootloader doesn't care about how many pins the device has. All it cares about is the UART pins, and they are the same.
Internally the two chips are the same, it's just the packaging that is different. They take the same silicon chip and mount it on a different lead frame and encapsulate it in epoxy. Which is why the only pin differences are a couple of extra power and ground pins, and two dedicated ADC pins that they don't connect in the DIP package.  Even the pins are in the same order around the chip if you examine the pinouts in the datasheet.
Whether you use the DIP (Uno) or the SMD (Nano) bootloader it makes no difference (the two bootloaders are the same anyway). There can be no "perform better" anyway, since that isn't a valid concept. Either it is compatible, in which case it will work, or it's not, in which case it won't.
The only real thing of concern is to ensure that your fuses are set correctly for your chosen clock source, and that the bootloader you install is compiled to run at the speed of your chosen clock source. That has nothing at all to do with which chip it is you are using, but how you have designed your circuit.

I got the clarity now. Thanks. By the way I’m am using it with 16Mhz and 22pf capacitors as a normal Arduino simple circuit nothing super.

I was in an impression of two different bootloaders for them. Thanks again for clarifying.

Two different bootloaders are used for ATmega328p. One is used in Uno, it is based on Optiboot 4. Second is used in Arduio Nano and is based on Atmel bootloader. Arduino replaced the old Nano bootloader with the Uno Optiboot bootloader in 2018, but Nano clones and old Nanos still in use have the old bootloader. In current AVR boards package version there is a bootloader selection in Tools menu.
With the burn of bootloader fuses are written to set the bootloader area size.
The old Nano bootloader is 2 kB large. The Optiboot bootloader is 0.5 kB large (small). But Arduino didn't change for Nano the size of the flash memory reserved for bootloader so 1.5 kB of flash memory is lost because of inaccurate fuse setting.
The old Nano bootloader didn't reset the watchdog flag. If your sketch setup the watchdog for some short time, after the reset the watchdog did reset the MCU while still in bootloader ending in endless reset loop.
The tutorial in your question would flash the Nano bootloader, because the author of the tutorial has Nano as target board while burning the bootloader. In 2017 it would be the Old bootloader.
So the Uno bootloader is recommended for ATmega328p with Uno fuse settings for bootloader size. After uploading the "Arduino as ISP" sketch and before activating "Burn bootloader" change the board selection to Uno.
Notes:

For ATmege328p with different frequency then 16 MHz the bootloader must by build with the required frequency.
there are newer versions of Optiboot (7 is current) with additional options. Some of the options result in larger bootloader.


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

image: "docker:latest"

services:
  - docker:dind

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

search:
  script:
    - arduinocli lib search hi

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

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

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

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

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

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

test:
  script:
    - echo 'run a script'

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

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


text:
Why is Wire.endTransmission(true) returning 10?
Question:
The follow code is printing 10 over and over again (with spaces in between). I have an I2C device connected at 0x60, and nothing connected at 0x61. I'm confused by this because the Wire.endTransmission(bool) docs say the only valid return types are 0,1,2,3, and 4. These return types are further supported by the Wire.endTransmission(), and the source code of the twi_writeTo function calls.
Code:
```
#include <Wire.h>

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

}

void loop() {
  // put your main code here, to run repeatedly:
  shieldConnected(0x60);
  Serial.println("\n");
  shieldConnected(0x61);

  delay(2000);

}

/**
 * Checks if an I2C device is connected at shieldAddr. This effectively checks if a
 * motor shield exists at that location.
 *
 * Note, this only works when everything's imported for some reason.
 */
void shieldConnected(uint8_t shieldAddr){
  Wire.beginTransmission(shieldAddr);
  Wire.write(1);
  uint8_t end = Wire.endTransmission(true);
  //shieldAddressValidator(shieldAddr);
  Serial.println(end);
}

```

Which arduino board do you use? Is that a working sketch? Are there spaces in between or new lines? Can you print it as a int.

Genuino 101, Yes, yes, and I can change it to printf if that's what you mean?

I'm sorry but I have bad news. The Arduino/Genuino 101 uses a Intel processor and it was a shame. There are different parts (serial, i2c) that never became fully compatible. There might be no solution to your problem or any problem with the 101. Buy a normal board that is compatible with the adafruit motor shield v2.


text:
How can I discover attached motor shields in code?
I'm using the Motor Shield v2 and I'm looking for a way to automatically discover the addresses of attached motor shields.

research how to discover i2c devices

If you configure each I2C device to have a unique address, then it's easy to determine which ones are connected.
This sketch is derived from the I2C Scanner sketch found here: I2cScanner
// This sketch tests the standard 7-bit addresses.
// Devices with higher bit address might not be seen properly.
#include <Wire.h>
byte shieldOneAddress = 0x27;
byte shieldTwoAddress = 0x32;
byte error, address;

void setup(){

  Wire.begin();
  Serial.begin(9600);
  Serial.println("Scanning for shields...");

  for(address = 1; address < 127; address++){

    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if(error == 0){
      if(address == shieldOneAddress){
        Serial.println("Shield One is connected.");
      }
      if(address == shieldTwoAddress){
        Serial.println("Shield Two is connected.");
      }
    }

  }
  Serial.println("Scan complete.\n");
}

void loop(){}

This code detects a device connected at address 112. This is the all call address. It doesn't detect the individual address of a motor shield (0x60 in my case).

So ^that is true when the motor shield library isn't imported, but when the motor shield library is imported it works fine. Maybe they do some setup, not sure.


text:
Running ADC triggered by TIMER1_COMPB
I'm trying to run ADC on channel 0 triggered by TIMER1_COMPB.
Everything seem to work ok but basic arithmetics is not working and variables inside ISR and even main loop don't get updated (x == 2 all the time)
Can somebody explain me why is it so? Even volatile variable was not changing...
Arduino UNO,
IDE v 1.8.6
#define SAMPLES_SIZE  205

const int adc_channel = 0;
const uint16_t t1_load = 0;

// 250 corresponds to 8kHz
const uint16_t t1_comp = 25000;

uint16_t samples[SAMPLES_SIZE];
volatile uint8_t samplePos = 0;

static int x = 0;

void initADC() {
  // Init ADC free-run mode; f = ( 16MHz/prescaler ) / 13 cycles/conversion
  ADMUX  = adc_channel; // Channel sel, right-adj, use AREF pin
  ADCSRA = _BV(ADEN)  | // ADC enable
           _BV(ADSC)  | // ADC start
           _BV(ADATE) | // Auto trigger
           _BV(ADIE)  | // Interrupt enable
           _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // 128:1 / 13 = 9615 Hz
  ADCSRB = _BV(ADTS2) | _BV(ADTS0);              // Timer/Counter1 Compare Match B
  DIDR0  = _BV(adc_channel); // Turn off digital input for ADC pin
}

void initTimer() {
  // Reset Timer1 Control Reg A
  TCCR1A = 0;

// Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

// Set prescaler to 8
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B &= ~(1 << CS10);

// Reset Timer 1 and set compare value
  TCNT1 = t1_load;
  OCR1B = t1_comp;

// Enable Timer 1 compare interrupt
  TIMSK1 = (1 << OCIE1B);
}

void setup() {
  cli();
  initADC();
  initTimer();
  sei();

  Serial.begin(115200);
}

void loop() {
  while(ADCSRA & _BV(ADIE)); // Wait for audio sampling to finish
  cli();
  x = x + 2;
  Serial.print(samples[0]);
  Serial.print("\t");
  Serial.println(x);
//  for (int i = 0; i < SAMPLES_SIZE; i++) {
//    Serial.println(samples);
//  }
//  samplePos = 0;

  ADCSRA |= _BV(ADIE);       // Resume sampling interrupt
  sei();
}

ISR(ADC_vect) {
  int16_t sample = ADC;

  samples[0] = sample;
//  samplePos++;
  ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off

  if(samplePos >= SAMPLES_SIZE) {
    ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off
  }
}

//ISR(TIMER1_COMPB_vect) {
//}

Thanks in advance

I don't think the manual ADC conversion during initialization is _BV(ADSC)  | // ADC start should be there. Also samples should be volatile. I won't comment on the rest of the code, as it seems to be a work in progress.

Timer1 CTC mode requires you to put the CTC TOP value in OCR1A (see Table 15.5 in 328P datasheet). You didn't, so the timer is running all the way from 0 to 0xFFFF.
Timer1 ADC trigger mode requires you to put the ADC trigger value in OCR1B, which you did, so every time that the timer passes by your trigger value (t1_comp), it triggers an ADC conversion.
In short, you need to set both OCR1A and OCR1B to t1_comp.

I've found the solution, it's strange since I enabled CTC mode, but it started to work normally as soon as I reset Timer 1:
ISR(TIMER1_COMPB_vect) {
  TCNT1 = 0;
}


text:
WS2812B LED Stripe going crazy with Arduino and External Power Supply
I have a simple connection here:

A WS2812B 5m 300 leds strip 5V;
A Power Supply MS-150-5 150W 5V;
Arduino with a simple code to blink 10 first leds;

TEST:
If I connect my power supply to my LED with a wireless controller with some saved presets, everything works fine. Colors, red, blue, white ( some voltage downhere ), but ok, working.
If take off the wireless controller and connect the LED to the Arduino, GND,+5, DATA, with a simple code, it's ok, 10 leds blinking, working fine.
BUT if I connect only the data to Arduino and connect the power to my power supply, now all the stripe go crazy, show no sense colors.
The Arduino code is ok, voltage is ok. Power supply is big enough. Even say to blink only one light is turning on all leds.
I was with a differente power supply before, same but 70w and was working ok. Now with 150w is not working. Why is not working with this one that is bigger? Maybe any noise ?
I'm connecting the power supply directly to the LED and only using the Arduino Data.

So... you don't connect the grounds together?

The Arduino GND and the power supply? No.

Well there is your problem, they need a common ground forthe signal to get through correctly.

Tks guys. I'm using the USB power for the Arduino and the external power supply for the LED. I'll try to use all the same source power and post here the result.

the source need not be the same, and usually isn't, the ground (aka common) needs to be, well, common.

Just make sure the Gnd from the Arduino and power supply are connected together - otherwise it would cause a common issue. Another recommendation would be to include a capacitor, usually a size of 1000uf is recommended.

Tks! Now is working like a charme. Was the GND between Arduino and the Strip.

Tks for reply guys. Thats correct. I have connected the GND of the external power supply with the GNC of Arduino and everything is fine.


text:
Arduino pins not working
I'm building my first arduino project and I encountered a strange problems;
I build a haunted house based upon that instructables tutorial:
https://www.instructables.com/id/Control-Your-Halloween-Decorations-With-Arduino/
Every prop works, I tried to light them on and off (it works), but when I try to use all of them, a few doesn't work.
There is my code; Is it something I'm doing wrong?
int propSqueDans = 4;
int propClownImmo = 5;
int propClownJambes = 6;
int propSqueBal = 7;
int propSqueMini = 8;
int propSpider = 9;
int propChauSou = 10;
int propFantChai = 11;

int SensorPin = 3; // sensor connected to analog pin 3
int SensorVal = 0; // variable to store the value read

void setup() {
  pinMode(propSqueDans, OUTPUT);// sets the digital pin as output
  pinMode(propClownImmo, OUTPUT);
  pinMode(propClownJambes, OUTPUT);
  pinMode(propSqueBal, OUTPUT);
  pinMode(propSqueMini, OUTPUT);
  pinMode(propChauSou, OUTPUT);
  pinMode(propFantChai, OUTPUT);
  pinMode(propSpider, OUTPUT);
  Serial.begin(9600);

  }

void loop() {
    SensorVal = analogRead(SensorPin); // read the input pin

    if (SensorVal >100) {
    Serial.write("Danse + Clown Immo \n");
    digitalWrite(propSqueDans, HIGH);
    digitalWrite(propClownImmo, HIGH);
    delay(10000);
    Serial.write("Spider + Fangtôme + Clown jambes \n");
    digitalWrite(propSpider, HIGH);
    digitalWrite(propFantChai, HIGH);
    digitalWrite(propClownJambes, HIGH);

    delay(5000);
    Serial.write("Squelette balance + sque mini \n");
    digitalWrite(propSqueBal, HIGH);
    digitalWrite(propSqueMini, HIGH);

    delay(5000);
    Serial.write("Chauve souris \n");
    digitalWrite(propChauSou, HIGH);

    delay(20000);

    digitalWrite(propSqueDans, LOW);
    digitalWrite(propClownJambes, LOW);
    digitalWrite(propSqueBal, LOW);
    digitalWrite(propSqueMini, LOW);
    digitalWrite(propChauSou, LOW);
    digitalWrite(propFantChai, LOW);
    digitalWrite(propSpider, LOW);
    digitalWrite(propClownImmo, LOW);
    delay(5000);
    }

  }

Thank you for your help !

Please show us your circuit (schematic). Also describe further, what is connected to the pins. Do you try to drive any motor or servo directly from the pins?

My best guess (not knowing what the pins are driving) is that your trying to draw too much current from the Arduino gpio.
Ref: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations

Hello Andre, I guess you're right; could you tell me if a better arduino will have more current ?

Uno and Mega are pretty much the same. I would suggest using a relay module.


text:
TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307
Been working on this project for some time now, like title states when I un-comment setSyncProvider(RTC.get) in the setup the program fails to get any of the Alarm.timerOnce to run.
I have been stuck for a while and couldn't find anything while just googling so I thought I might enlist the minds of stack.
#include <Wire.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

//#define DS1307_I2C_ADDRESS 0x68 // the I2C address of Tiny RTC
//byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

int curPin = 7, //  Current sense (middle terminal) connected to analog pin A7
  prePin = 6,     //  Pressure sense (green terminal) connected to analog pin A6
  ignPin = 7,     //  Igniter output pin D7
  solPin = 8,     //  Solenoid output pin D8
  genPin = 9,     //  Generator output pin D9
  tonePin = 11,   //  Tone output pin D11
  ligPin = 3,     //  Light sense pin A3
  intPin = 3,     //  Interupt pin D3 runs double bang

  runTime = 20,   //  minutes to run for

  state = 0;      //  state of operation

bool operate = false, // True if within operating time
   timeIsSet = false; // true if time till next opperation is set
double cur;

void setup() {
  Wire.begin();
  pinMode(13,OUTPUT);
  pinMode(ignPin, OUTPUT);
  pinMode(solPin, OUTPUT);
  pinMode(genPin, OUTPUT);
  Serial.begin(9600);
  //setSyncProvider(RTC.get);  //******************************************
  Alarm.alarmRepeat(dowMonday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowTuesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowWednesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowThursday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowFriday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSaturday,8,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSunday,10,0,0,OnAlarm);
  Alarm.alarmRepeat(20,0,0,OffAlarm);
  tone(tonePin, 31, 1000);
  randomSeed(analogRead(0)); // nothing connected to 0 so read sees noise

  OnAlarm();
}

void loop() {
  if ((analogRead(ligPin) > 30) && operate == true)
  {
    if (timeIsSet == false)
    {
      tone(tonePin, 58, 500);
      int randm = random(27,36);
      Alarm.timerOnce(randm,operation);
      Serial.println(randm);
      timeIsSet = true;
    }
  }
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

void operation(){
  tone(tonePin, 100, 1000);
  Alarm.timerOnce(12,after20m);
  digitalWrite(genPin, HIGH);
}

void after20m(){
  digitalWrite(genPin, LOW);
  Alarm.timerOnce(5,after5s);
  digitalWrite(solPin, HIGH);
  tone(tonePin, 494, 1000);
  timeIsSet = false;
}

void after5s(){
  tone(tonePin, 200, 1000);
  digitalWrite(solPin, LOW);
  Alarm.timerOnce(1,after1s);
}

void after1s()
{
  digitalWrite(ignPin, HIGH);
  Alarm.delay(500);
  digitalWrite(ignPin, LOW);
}

void OnAlarm() {
  operate = true;
}

void OffAlarm() {
  operate = false;
}

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  //Serial.print(operate);
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Problem existed in the TimeAlarms library,
Q: How many alarms can be created?
A: Up to six alarms can be scheduled.
The number of alarms can be changed in the TimeAlarms header file (set by the constant
dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

so how I fixed it was to edit #define dtNBR_ALARMS 6  // max is 255 to #define dtNBR_ALARMS 14   // max is 255 in the TimeAlarms.h file.

should this be an answer or add-on? you can edit the question

Looks like an answer to me. :)


text:
Can anyone please help me to modify the code so that it runs faster?
this is a program for a blindspot detection system using 4 ultrasonic and 2 ir sensors.
can someone help me in modifyng the code so that this runs faster?
#include<LiquidCrystal.h>
#define trigbl 14
#define echobl 15
#define trigbr 16
#define echobr 17
#define trigfl 18
#define echofl 19
#define trigfr 8
#define echofr 9
#define bl 10
#define br 11
long durationbl;
long durationbr;
long durationfl;
long durationfr;
int distancebl;
int distancebr;
int distancefl;
int distancefr;
int irr;
int irl;
int a;
int b;
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
void setup()
{
  lcd.begin(16, 2);
  pinMode(trigbl, OUTPUT);
  pinMode(echobl, INPUT);
  pinMode(trigbr, OUTPUT);
  pinMode(echobr, INPUT);
  pinMode(trigfl, OUTPUT);
  pinMode(echofl, INPUT);
  pinMode(trigfr, OUTPUT);
  pinMode(echofr, INPUT);
  pinMode(bl, INPUT_PULLUP);
  pinMode(br, INPUT_PULLUP);
}
void loop()
{
  digitalWrite(trigbl, LOW);
  delay(2);
  digitalWrite(trigbl, HIGH);
  delay(10);
  digitalWrite(trigbl, LOW);
  durationbl = pulseIn(echobl, HIGH);
  distancebl = durationbl * 0.034 / 2;
  int a1=distancebl;
  digitalWrite(trigbr, LOW);
  delay(2);
  digitalWrite(trigbr, HIGH);
  delay(10);
  digitalWrite(trigbr, LOW);
   durationbr = pulseIn(echobr, HIGH);
   distancebr = durationbr * 0.034 / 2;
  int a2=distancebr;
  digitalWrite(trigfl, LOW);
  delay(2);
  digitalWrite(trigfl, HIGH);
  delay(10);
  digitalWrite(trigfl, LOW);
  durationfl = pulseIn(echofl, HIGH);
  distancefl = durationfl * 0.034 / 2;
  int a3=distancefl;
  digitalWrite(trigfr, LOW);
  delay(2);
  digitalWrite(trigfr, HIGH);
  delay(10);
  digitalWrite(trigfr, LOW);
  durationfr = pulseIn(echofr, HIGH);
  distancefr = durationfr * 0.034 / 2;
  int a4=distancefr;
  irl =digitalRead(bl);
  irr =digitalRead(br);
  lcd.setCursor(1, 0);
  lcd.print("RL  RR  FL  FR");
  if (a1<30 && irl==0)
  {
  a=0;
  }
  else
  {
    a=1;
  }
   if (a2<30 || irr==0)
  {
  b=0;
  }
  else
  {
    b=1;
  }
   if  (a==1 && b==1 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("No Obstacle    ");
  }
  else if ( a==0 && b==1 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX            ");
  }
  else if ( a==1 && b==0 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX        ");
  }
  else if ( a==1 && b==1 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("        XX    ");
  }
   else if ( a==1 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("            XX");
  }
  else if ( a==0 && b==0 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX        ");
  }
  else if ( a==1 && b==0 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX  XX    ");
  }

  else if ( a==0 && b==1 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX      XX    ");
  }
  else if ( a==0 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX          XX");
   }
  else if ( a==1 && b==0 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX      XX");
  }
  else if ( a==0 && b==0 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX  XX    ");
  }
  else if ( a==1 && b==1 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("        XX  XX");
  }
  else if ( a==1 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX      XX");
  }
  else if ( a==1 && b==0 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX      XX  XX");
   }
  else if ( a==1 && b==0 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX  XX  XX");
  }
  else if ( a==0 && b==0 && a3<30 && a4<30)
  {
        lcd.setCursor(1, 1);
        lcd.print("Call Help ......  ");
  }
}

Remove the delays...?

@Majenko those delays are to generate pulses for ultrasonic sensors.

hint: observe the result of these two commands to give you an idea how to shorten all the else if blocks ...... lcd.print("abc");  lcd.print("123");

You may want to check the datasheet of your sonar sensors to see what is
the recommended trigger pulse duration. On a typical HC-SR04, it is ten
microseconds, not milliseconds. So use delayMicroseconds(10);.
If your program runs really slowly, the culprit is most probably
pulseIn(). This function will wait for an incoming pulse and, if there
is no incoming pulse, it waits one full second before timing out. This
can be simply fixed by providing a third argument to pulseIn(), which
is the desired timeout in microseconds. Set it to something reasonable,
maybe around 25,000 µs for a maximum detection range of 4 m.


text:
How to know which event fired first?
I want to automate the chicken coop of my grandmother. To do so, I want to use Arduinos and NodeMCUs, respectively. I want to check if all chickens are in the coop at night and then close a little door. I was trying to use RFID technology and tag the chickens with a little RFID tag but the read range I got was too short to get it working properly. Now, I am trying to implement a light gate with two small lasers and two receivers. I want to detect the direction (in or out) of the chickens. I got the lasers working and I get a signal (1  and 0 = light gate interrupted). I have to know which of the two laser detectors first detected a 0 (zero). I have no idea how to implement this in code. I was trying to use timers to no avail. I also was trying to use interrupts (see small code fragment).
I hope I made clear what I am trying to achieve. Please tell me if and how I can improve this question. Any google fu was to no avail. Every hint/help is greatly appreciated.
#include <Arduino.h>

// Functions
void pin_ISR();

const int detectorPin = 3;     // the number of the detector pin
const int ledPin =  13;      // the number of the LED pin
const int Laser = 6;
// variables will change:
volatile int buttonState = 1;         // variable for reading the status

void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(detectorPin, INPUT);
pinMode(Laser, OUTPUT);
digitalWrite(Laser, HIGH);
// Attach an interrupt to the ISR vector
attachInterrupt(digitalPinToInterrupt(3), pin_ISR, CHANGE);
}

void loop() {
Serial.print(buttonState);
delay(100);
}

void pin_ISR() {
Serial.println("There was an interrupt!");
buttonState = digitalRead(detectorPin);
digitalWrite(ledPin, buttonState);
}

You have only one light gate in your code. Add the second.

Do the light gates both get active together, or one active then inactive, followed by the other? I.e., do you have a sequence of "HH -> LH -> LL -> HL -> HH" or do you have "HH -> LH -> HH -> HL -> HH" for the gates?

Consider using quadrature encoding to detect travel direction using two light beams. A method used in older mechanical mouse pointer devices and track balls. Using an Arduino to decode quadrature encoding is talked about in many places on the web.
Place beam A and beam B such that a chicken waling out of the coop will activate beam B first and beam A second.

Because the activation of beam B occurs first we know the chicken is walking out of the coop.  If beam A occurred first we know the chicken is walking into the coop.
The shape of a chicken is irregular and a chicken may change its mind half way out of the coop.  These and other unexpected anomalies may lead to unexpected results.  Consider supplementing the beams with a PIR sensor outside the coop to confirm there are no chickens left outside.

Thanks for all your help and efforts. @juraj, I was aware that I just implemented one light gate. It was just in order to deliver sample code for showing how I was using interrupts. st2000, Thanks for your big help, but I am not the lightest light in the room, so the quadrature encoding was a little to complex for me. I finally figured out that I have to search for "people counter arduino" or "bidirectional counter".  Here, I found a really similar project and I can adapt much of the code from there.

Don't sell your self short.  The program you linked to is using quadrature encoding. They just don't say it.  Perhaps it would help to think of the clock wise rotation of the wheel to be a chicken going into the coop and the counter clock wise rotation of the wheel to be a chicken going out of the coop.

@Strohmi, I asked you to add the second light gate, because  then it would be easy to add evaluation of which one triggered first


text:
Increase and Decrease Motor Speed
I'm a newbie on Arduino and I'm doing an exercise about the Motor controller
"Increase the motor speed from zero to maxium (255) and then decrease slowly from the maximum to the minium."
Here's my code. I don't know whether it's true or not. So, can anyone help me to check it and give me some advice how to do better on Arduino ?
int i;
void setup()
{
   pinMode(motor, OUTPUT);
}

void loop()
{
   for (i=0; i<=255; i++)
   {
   analogWrite(motor, i);
   }

   for (i=255; i>=0; i--)
   {
   analogWrite(motor, i);
   }
}

I also have one other problem :D that I don't know what will happen if I set the analogWrite value to 300.
Thank you so much.

@per1234 Per, why unclear?

It's unclear because there is no question in it, just a "check my code please"...

"check my code please" is a valid question according to https://arduino.stackexchange.com/help/on-topic

It won't work, as you don't give it any time to do anything. The PWM works about 1kHz and motor needs much more time to start rotating. And you are sending values as fast as possible (it means microseconds for every analogWrite)
And analogWrite(300) without changing the Arduino default settings means it overflows to value 300 % 256 = 44. All Timers are set near to 1kHz and 8bit resolution by Arduino core.


text:
Short battery life concern with Arduino Pro Mini
I am using an Arduino Pro Mini with a L293D H-bridge driver to drive a bi-directional motor. The system takes input from a capacitive sensor which is constantly looking for a trigger. I don't have any low power optimization in the code. I was using Arduino UNO before which lasted for one day with a 9V battery. I switched to Arduino Pro Mini for longer battery life but the battery lasted for one day in that case as well.
Can anyone please help me understand what could be the possible reason for higher power consumption than normal for Arduino Pro Mini?
Thanks in advance for your help!
Niloy

Are you powering the motor and driver from the 9V battery too? Does the Pro Mini still have it's power LED soldered on?

Please provide entire circuit schema and source code. I can't help you without knowing more details.

a 9V battery consists of six AAAA cells .... that is way less power than AA cells

The battery life was the same (1 day).  So why did you say "higher power consumption"?  2) Arduino processors usually run at 3.3V or 5V.  So there is a energy eating linear power regulator wasting power by eating the voltage difference on most Arduino boards.  3) Those square 9 volt batteries do not contain many mA/hours.  4) Extending the life of portable battery operated devices is not an easy task.  It gets harder and harder for each additional morsel of time.

@jose can u c  Yes, I am powering the motor and driver from the 9V battery too. Yes, the Pro Mini have a power LED which is on all the time.

@Filip Franik I believe I understood the problem. Thank you so much for offering your help. :)

@jsotola thanks for the information. I did not know specifics of 9V battery.

@st2000 I meant that I expected Arduino Pro Mini to last way longer than Arduino UNO with similar setup. Thanks for pointing out about the linear regulator and low mA/h of a 9V battery. I started researching using those references and I realized how my 9V battery was draining so quickly. Thanks a lot again.

A standard alkaline 9V battery has a capacity rating of around 500mAh (milliAmp-hours). That rating is probably based on a current consumption of around 10mA. However, if the current consumption is higher, the apparent capacity drops. At 100mA, most 9V batteries have a capacity rating of about 300mAh, and at 500mA current draw, the apparent capacity drops down to 170mAh.
This means, if you are drawing 100mA of current constantly, a 9V battery will last (0.3Ah / 0.1A) = 3h.
A typical Arduino pro mini will draw current at around 20mA.
500mAh / 20mA = 20h

This is not even counting the motor and driver.
A standard alkaline AA battery has a nominal voltage of 1.5V and a capacity of about 2000mAh, and 3 of them will provide a voltage between 4.5V (fully charged 1.5V x 3) and 2.7V (fully discharged 0.9V x 3)
With that voltage range, you could operate the Arduino pro mini in 3.3V mode, with no linear regulator, at a reduced clock frequency, such as 8Mhz, which will reduce power consumption even more.
Being able to put the chip in power-saving mode, and periodically check for necessary activity will help even more.
See http://www.gammon.com.au/power for a description of many practical methods.
That said, the Arduino is going to be a pretty small contributor to power draw compared to a DC motor, so your overall run time will heavily depend on how often the motor is turned on.

Thank you so so much! I am new to Arduino Programming and little experience about batteries. Your response is very helpful to me. I will switch to AA batteries and I will follow other practical methods.


text:
Converting hexadecimal string to floating point value
I am reading data from an energy meter over modbus protocol and I am getting hex values from there. I want to convert that hex string to floating point value.
For example - 0x416f0000 denotes a value of 14.9375.Reference
Can anyone please help me how to do it on Arduino IDE?

You mean Modbus ASCII, right? Non-ASCII Modbus doesn't use hex.

If you do indeed have an ASCII string of hexadecimal numbers (and not a
raw binary float), then your best option may be to do the conversion in
two steps:

convert the string to a 32 bit unsigned number using
strtoul()
reinterpret the binary pattern of this integer as a float.

For example, the following program:
void setup() {
    const char modbus_data[] = "416F0000";
    union {
        uint32_t i;
        float f;
    } data;
    data.i = strtoul(modbus_data, NULL, 16);

    Serial.begin(9600);
    Serial.println(data.f, 4);
}

void loop(){}

prints 14.9375.
Note that for strtoul() to function properly, the hex string must be
followed by a character that is not a valid hex digit (a \0 in the
example above).


text:
3V Arduino options
I have an Arduino Mega board to test 3V devices. Which is the simplest way to connect those 3V devices to the Arduino Mega (it works at 5V) without burning them? I saw the Adafruit Trinket works at 3V, could be an option? Since I need many input/outputs (around 50), Arduino Mega is the most suitable in terms of input/outputs pins.
What do you suggest me to do?

You can buffer the IO to/from the 3V devices. 5V down to 3V, use CD74HC4050 powered from 3V.  3V up to 5V, SN74AHCT541 powered from 5V.

There are plenty of non-Arduno boards that both give you more power and 3.3V operation.  Personally I love the chipKIT boards (the Max32 is the chipKIT equivalent to the Mega2560).
If you want to stick with Arduino then consider the Due, which is the same footprint as the Mega2560 but again with more power and 3.3V operation.
For interfacing 3.3V devices to a 5V board, though, that can be done simply with level shifters.  You need to get the right type though:

Basic GPIO, SPI and UART etc can be done with a simple MOSFET shifter (cheaply available on eBay)
I2C requires a special I2C level shifter (I use the PCA9306) which maintains the open-drain and bidirectional operation required for I2C

The devices work exactly at 3V (no 3.3V), The suggested board is suitable? Thanks @Majenko.

What devices are you using that run at exactly 3V?  And yes, most level shifters will go down as low as 1.8V

Are industrial devices. Great!

You will probably find that connectors marked "3V" are actually 3.3V - 3V is a very strange voltage to run on.  3.3V or 2.8V are common, but 3V is almost unheard of in electronics.


text:
How to build a valid HTTP Response. Recv failure: Connection reset by peer
I'm developing an Arduino server that should respond with a message when it receives a POST Request.
If I test my project with a HTTP Client (like insomnia or postman), I get an error:
Error: Failure when receiving data from the peer

I still get a response that I can read but with a final error.
That's my client request:
> POST /SOMETHING/ HTTP/1.1
> Host: [ARDUINO IP]
> User-Agent: insomnia/6.2.0
> Accept: */*
> Content-Length: 0

And this is my Arduino response considered as not valid:
< HTTP/1.1 200 OK
< Connection: close
< [MY MESSAGE]

* Recv failure: Connection reset by peer
* stopped the pause stream!
* Closing connection 2

As you can notice, I just added 2 strings
HTTP/1.1 200 OK
Connection: close

before the real message.
Am I missing something to create a valid response?
Thanks

HTTP requires an empty line after HTTP headers.
First line is status line. Then the header lines. The headers are terminated by an empty line. Then the response body follows. Line terminator for HTTP is \r\n. Arduino println() function uses \r\n.
The response with body should contain Content-type and Content-length header. Alternative to Content-lenght is "chunked" Transfer-Encoding.
ESP8266WebServer library handles HTTP for you.

you don't send content length, so the client doesn't know where the body ends. it waits for more data and you close the connection. browser tolerates it or has some orientation in the body structure (html tags?)

perferct. It works printing always the string.length() in Content-Length. Thanks


text:
How can I tell if sketch is really uploaded
I am trying to figure out how to tell if my sketch upload was really successful.  My Arduino UNO with AVR ISP example loaded and a Chinese AVR ISP programmer board inserted tells me that my sketch was successful but because the memory used in the ATMega328P is lower than I think it should be I can't tell if my sketch really did upload and dumping the file and doing a Windows FC (file compare) just tells me they are different.  The ATMega328P should only have the bootloader prior to my sketch upload.  Looking at the file with an editor tells me nothing other than there are things loaded in memory.
The operating system is Windows 7 using the Arduino 1.8.7 IDE and an Arduino Uno via usb.
Thank you.

If the verification is enabled and successfull, it should be just fine.

I agree with KIIV but if you do need more verification, perhaps print some stuff out and check the serial monitor.

You know it's uploaded if your sketch is working. Is your sketch working?


text:
Arduino Object Array initialization
I just got an Idea of trying to code rain simulation with arduino and Adafruit OLED display. When I finished it was quite messy code so I thought That maybe doing it Object Oriented would help. This code is just a sketch that MAYBE works. The thing is that I need to create an array of objects(drops) and then display them. I have tried to display just one drop and it does not seem to do anything, even Serial wont print the pos_y. I have never wrote an Arduino code with objects so I just made a quick research and tried. here is the code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

class Drop{
  private:
  int pos_x = random(0, 128);
  int pos_y = random(-5, -20);
  int len = random(3, 7);
  int speed = random(6, 13);
public:
 void fall()
{
 display.drawFastVLine(pos_x, pos_y, len, 1);
 pos_y = pos_y + speed;
 delay(5);
 Serial.println(pos_y);
 display.display();
 display.clearDisplay();
}

};

Drop* drop = new Drop[50];

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
}

void loop() {
  drop[1].fall();
}

I will appreciate any suggestion or solution, spent almost entire day doing this "simple thing"..

I tried your code using a dummy implementation of Adafruit_SSD1306 that just prints to the serial port. It seems to work as expected.

can the display show negative y position? becose it start with -5 (you don't initialize random)

Well, cutting out all the display code the program appears to work fine for me.

It may well be then that the display driver hates a negative Y value. Not using that library ever I can't say...  Personally I'd never use an Arduino for anything to do with a display...

do you have 9600 baud set in Serial Monitor? add some prints to see where the code hangs

The code works without the display commands. A problem could be that you start with negative pos_y and use it as parameter for drawFastVLine.
Function random returns first parameter if it is a larger value then the second parameter. random(-5, -20) always returns -5.
To have more random random values, you should call randomSeed in setup().
And you can use global array Drop drop[50];.

I dont think so, the messier version without objects worked fine with negative values :/ And thank you for the clarification with random!

Okay i just used Global array and it seems that it fixed the problem ;). Thank you!

strange. what version of IDE you have. is in Question the same sketch you use?


text:
library mixing log4Esp & Syslog for esp8266
has someone finaly made a new lib combining log4esp and syslog
cf :
SyslogAppender for log4esp
thanks:!

I did a rather dirty (but efficient for my purpose) job : While creating a new logger I declared and attached to it a log4esp formatter in which I sent ... syslog messages
dirty dirty dirty
my config constants are : SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME

My logger.h:
#ifndef Logging_H
#define Logging_H
#include <Log4Esp.h>
namespace Logging
{
void setup() ;
log4Esp::Logger Logger(const char *name);
}
#endif

my logger.cpp:
#include <Log4Esp.h>
#include <Syslog.h>
#include <WiFiUdp.h>
#include <ESP8266WiFi.h>
#include "Logger.h"
#include "config.h"
namespace Logging
{
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udpClient;
// Create a new syslog instance with LOG_KERN facility
Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN);
//new logger
log4Esp::Logger Logger(const char *name)
{
  //new instance
  log4Esp::Logger logger = log4Esp::Logger(name);
  //minimal level
  logger.addLevelToAll(log4Esp::Appender::LOG_LEVEL);
  // formatting for serial logging
  logger.addFormatterToAll([name](Print & output, log4Esp::Appender::Level level, const char *msg, va_list * args) {
    ////////////////////////////////////////
    // serial log format
    // output uptime of this program in milliseconds
    output.printf("%10d", millis());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output free heap space
    output.printf("(%d)", ESP.getFreeHeap());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output logger name
    output.printf("%-4s", name);
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output log level
    output.print(log4Esp::Appender::toString(level, true));
    if (level <= log4Esp::Appender::Level::ERROR) {
      output.print("***");
    } else {
      output.print("   ");
    }
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // determine buffer length for formatted data
    size_t length = vsnprintf(NULL, 0, msg, *args) + 1;
    char buffer[length];
    // output formatted data
    vsnprintf(buffer, length, msg, *args);
    output.print(buffer);
    ////////////////////////////////////////
    // Stop here if wifi is down
    if (WiFi.status() != WL_CONNECTED)
      return;
    ////////////////////////////////////////
    // format for syslog
    uint16_t slevel;
    switch (level) {
      case log4Esp::Appender::Level::FATAL    :
        slevel = LOG_CRIT;
        break;
      case log4Esp::Appender::Level::ERROR    :
        slevel = LOG_ERR;
        break;
      case log4Esp::Appender::Level::WARNING  :
        slevel = LOG_WARNING;
        break;
      case log4Esp::Appender::Level::VERBOSE  :
        slevel = LOG_INFO;
        break;
      case log4Esp::Appender::Level::TRACE    :
      default:
        slevel = LOG_DEBUG;
        break;
    }
    syslog.logf(slevel, "%10d|(%d)|%-4s|%s", millis(), ESP.getFreeHeap(), name, buffer);
  });
  return logger;
}
void setup() {

}
}

Yes:)  i understood now the other thread!  That s also perfect for me, you should GitHub it:)


text:
Having trouble reading directly from VEML6075 UV sensor from its registers(I2C)
I'm kinda new to Arduino and decided to dive deeper into learning abit more about Arduino; So i decided to grab a Sparkfun VEML6075 UV sensor and try to:
1) Initialise it
2) Take readings from it
Without using the Sparkfun libraries at all. Based on what I read in the datasheets, this seems possible by using the I2C communication protocol provided by communicating directly with the registers of the device itself.
However, I can't seem to be able to even initialise the device properly as the readings I have gotten are weird and do not change (I presume this means the device only took one reading and stops at that)
My code is as below:
#include <Wire.h>

byte address = 0x10; // Slave address of the VEML6075
byte UVA_LSB, UVA_MSB;
word UVA_data;
uint16_t UVA_combined;
void setup() {
    Serial.begin(9600);
    Wire.begin();
    VEML6075_init(address);
//    uv.begin();
    Serial.println("Module is detected");
}

void loop() {
    VEML6075_Fetch_UV(address);   // Fetch UVA data *TEST*
    Serial.print("UVA: ");
    Serial.println(UVA_combined);
    delay(1000);
}

// shutdown module and init it; restarting the module
void VEML6075_init(byte address){
    Wire.beginTransmission(address);  // Shutdown command
    Wire.write(highByte(0x00));
    Wire.write(lowByte(0x01));
    Wire.endTransmission();

    Wire.beginTransmission(address);
    Wire.write(highByte(0x00));
    Wire.write(lowByte(0x12));   // Reset command using conf register
    Wire.endTransmission();
    delay(200); // Wait for module to reset
    // Done //
  }

 void VEML6075_Fetch_UV(byte address){
    Wire.beginTransmission(address);   // Begin transmission into I2C line with Slave address
    Wire.write(highByte(0x07));     // Issue command to read UVA data
    Wire.write(lowByte(0x07));
    Wire.requestFrom(address, 2);
    while(!Wire.available()); // Needs refining; read twice for 16 bits
    UVA_LSB = Wire.read();
    UVA_MSB = Wire.read();
    Wire.endTransmission();

    UVA_combined = ((UVA_MSB << 8) | UVA_LSB); // Combine to 16bits
  }

As stated in the datasheet:

The VEML6075 contains a CONF register (00h) used for operation control and parameter setup. Measurement results are stored
  in four separate registers, one each for UVA, UVB, UVcomp1, and UVcomp2 (07h to 0Bh respectively). All registers are accessible
  via I2C communication. Fig. 7 shows the basic I2C communication with the VEML6075. Each of the registers in the
  VEML6075 are 16 bit wide, so 16 bit should be written when a write command is sent, and 16 bit should be read when a read
  command is sent.

I have allocated 16 bits for receiving the data, and have also used the conf address 0x12 to set the timing to 100ms and activate active-force-mode which i presume is the device taking readings automatically. The readings given are way off the accurate readings given when i upload a example code that uses the Sparkfun library, so I'm quite lost at this point. How am I using the I2C protocol wrongly? Thanks!

add Wire.endTransmission(false); to send the written bytes before Wire.requestFrom(address, 2);

after Wire.requestFrom(address, 2); returns, the data are available for read

... thus the line with while(!Wire.available()) can be removed. The highbyte and lowbyte are used in the wrong way. When a 16-bit variable is for example 0x1234, then the highbyte is 12 and the lowbyte is 34. You use already bytes.

Could you explain further about what you mean by I'm using highbytes wrongly and in where? In my intitalisation function I used Wire.write(highByte(0x00));
Wire.write(lowByte(0x12));  to emulate 0x0012 for 16bits conf register. Is that correct?

0x00 is already a byte and 0x12 is already a byte. You can do highByte(0x0012) and lowByte(0x0012). If you already pick the bytes from 0x0012 then you can do Wire.write(0x00); // high byte and Wire.write(0x12); // low byte

Do you use a i2c level shifter?


text:
How to retain the on state of the LED and buzzer if the sensor is triggered?
I'm working on a project which is likely an earthquake alarm. The sketch that I got from the internet does not retain the "on" state of the indicators(LED and buzzer)when it is triggered. I want to modify the sketch that it makes the LED and buzzer retains their "on" state when the sensor(accelerometer) is triggered. Could someone help me ?
Here is the code:
#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis  < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis  < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

i've seen your code before ..... you had someone delete all the LCD code from a sketch that you copied from the web ..... that resulted in a bunch of useless and redundant code being left behind .... one of the useless commands is obvious even for a beginner, i think.... it appears that you have not even bothered to read through the code because you have not deleted the redundant code or at least questioned why it is there ..... how do you expect to learn any programming if you always ask someone else to do it for you

Sorry dude, but I'm just afraid that I will mess up the code. I've been thinking that if i could remove the local variables inside the " void checkseetings; ", coz i think they are related to the LCD code. Could you help me ?

Define a (boolean: bool) variable, set it to false initially.
When the sensor is activated, set the variable to true.
Define something that should be able to disactivate the buzzer/LEDs. And if that happens, set the variable to FALSE. Maybe this is a reset button ?
Than based on this variable set the buzzer and LEDs on or off.

So you get something like a global variable
bool alarmTriggered;

In setup:
alarmTriggered = false;

In loop:
if (AreSensorsTriggered(...)) // Create your own function
{
   alarmTriggered = true;
}
else if (IsResetButtonPressed(...)) // Create your own function
{
   alarmTriggered = false;
}

SetBuzzer(alarmTriggered); // Create a function that enables/disables buzzer
SetLEDs(alarmTriggered); // Create a function that enabled/disables LEDs

Sorry dude, I'm newbie when it comes to programming, could you modify it for me?

How can I say this, but I can't apply it in the sketch, do i just copy/paste in the sketch ? sorry for the trouble dude .

First you need to think how to switch off the LEDs/buzzer.

The leds/buzzer will only turn off when i reset the arduino

That's why you need to think of a trigger also to switch it off (to set the boolean back to false). I cannot invent it, maybe after some time, or a 'reset alarm' button?

I'm okay with the 'reset alarm button'

Ok, than when that button is pressed, set the boolean to False.


text:
Question about browsing the web using arduino
I have got an arduino, a TFT touch screen and a WIFI module. The question is can i visit a specific web site and display it on that screen and interact with it.

no. you would need a html rendering engine like Gecko oe WebKit

yes, but you'd have to use an opera-mini style pre-render process on a middle-man.

As already pointed out in @Kwasmich's answer, you are vastly overestimating the capability of an arduino. Another more powerful board (Such as a Raspberri-PI) could possibly handle those tasks. But Arduino's + your Wifi module are much better suited for allowing remote monitoring and control of simple processes. The coding and hardware that go into displaying a web page with graphics may seem easy these days, but there are some mountains you'll need to climb to understand why its much harder than it seems. Don't let that discourage you though! Mountains can be climbed!

You just have to install Chromium and call the desired page.
No, just kidding. I don't think you will ever fit a parsing and rendering engine on an arduino. Chromium for example takes about 150MiB of storage and depending on the opened page hundreds of MiB of RAM. Both of which is multiple orders of magnitude larger than the Arduino has to offer.
You might want to consider going to use a SBC like the Raspberry Pi for such usecase.
Alternatively you can query the data over network and write your own rendering code for the TFT display.