text:
I am trying to up the frequency everytime button is press by 100 Hz, I am using the Input pull registor
The frequency should be increased by 100 Hz whenever an external push-button on UNO digital pin 5 is depressed and then released. I think I might missing something critical.
#define LEDPIN 3
float highTime;
float lowTime;
int freq;
float period;

//uint16_t val2= pulseIn(4, HIGH);

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1 (the 16-bit timer) using channel A output compare

TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 100 Hz increments
OCR1A = 9999; // = 16000000 / (8 * 100) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
 TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
interrupts(); // enable global interrupts:
}
void loop() {

highTime =(pulseIn(4, HIGH));
lowTime=(pulseIn(4, LOW));
period = highTime+lowTime;
freq=1000000/period;       //getting frequency with totalTime is in Micro seconds
Serial.print(freq);
delay(1000);

Serial.print("\n");

Basically I want to turn the above code which display "100" in serial monitor with raises the frequency by 100 by a button press.
#define LEDPIN 3
const int buttonPin = 5;    // the number of the pushbutton pin

//uint16_t val2= pulseIn(4, HIGH);
// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
  Serial.begin(9600);
  pinMode(LEDPIN, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  // initialize Timer1 (the 16-bit timer) using channel A output compare

  TCCR1B = 0; // same for TCCR1B
  TCNT1 = 0; // initialize counter value to 0
  // set compare match register for 100 Hz increments
  OCR1A = 9999; // = 16000000 / (8 * 100) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 8 prescaler
  TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei(); // allow interrupts
  interrupts(); // enable global interrupts:

}
void loop() {
  int reading = digitalRead(buttonPin);
   // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
    lastButtonState = reading;

    Serial.print(reading);
    delay(1000);
    Serial.print("\n");

  }
}

It might be a good idea to explain what happens instead of the 100Hz frequency increase you seem to be expecting. One issue is already very obvious to me: There's nothing in your loop() that changes the frequency. Just some debounce code and something that changes the variable called ledState (but nothing that actually changes the state of the LED). Where did you get this code from?

I suggest using the Bounce2 library for the button presses. It makes the handling way easier and does all the debouncing.

Your button input pin is set to INPUT_PULLUP mode so that pin will always read HIGH unless you ground it. Your button should connect the pin to ground when it is pressed.
If you do that, then the pin will read HIGH when the button is not pressed, and LOW when the button is pressed. Near the bottom of your loop() function, you test the button and toggle the LED with:
  if (buttonState == HIGH) {
      ledState = !ledState;
  }

But this toggles the LED when the button is released. Is that really what you meant?

Basically, I want it I want frequency to be increased by 100 each time I press a button

I see two sketches in your question. I was looking at the second one. How are the two related, and which one are you trying to debug?

Sorry about the confusion, basically I have to combine and edit 1st code with the button debounce code from the library function. The first code is just displays "100" hz and the second code I have use my first code to up 100 hz each time a button is pressed.

Then I believe you want to use the second code, but reverse the buttonState test - test it for LOW instead. Inside the 'if' block, where you toggle the LED, is where to put the code that increases the frequency.

I am still new to this. Can you please explain piece by piece what I need to change?

What you need to change? Take a new/clean Arduino project and first reliably read the button press. Then, you use the "tone()" function instead of manually setting registers. Build it yourself (based on examples), so you understand why/what code is there instead of copying it from the internet.

I does really seem like you're trying to learn to do too many things at once. Learn to manage the button until you're satisfied you've got it right and understand it. Then do the same thing with frequency - learn to set or change it in steps, maybe 1 second apart, using delay() to measure the 1 second. Then apply what you know to a sketch that watches the button and changes the frequency, both jobs using code you've already written (without the delay(), of course). It's much easier to learn the pieces one by one before you start putting them together.


text:
What is the purpose of putting a data type in brackets before a calculation?
sorry for the nooby question but I can't seem to find the answer to this anywhere, probably because I'm unsure what to search for with this problem!
I'm just wondering what the reason is for including a data type in brackets before a calculation takes place? In the code below, all the variables have already been declared at the top of the program, so I'm unsure what the reason / effect of including the (float) has. acc_y and angle_pitch_acc have been declared as floats and acc_total_vector has been declared as long
angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;

Thanks!

It's called casting. It changes the data type temporarily. In this instance it's being used to change an integer type into a floating point type, which means that the whole calculation is done using floating point mathematics. However acc_y is supposedly already a float, but maybe it wasn't at the time the author wrote that line. Maybe things, as they often do in a program, evolved. Only the author knows.

The OP wrote, that acc_y is declared as float. So the calculation would already be a floating point one, I think

@chrisl I stopped reading at "I wonder..."

Ok thanks, that makes sense.

source: Stack Exchange

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

sort: votes


text:
What is the pinout of the Arduino MKR motor carrier when using external power supply, not the Li-Po battery
I see there is a blue terminal connector an the tags below the PCB Vin, 5V, 3,3V and GND, but I am unsure where should I supply voltage to power up the board.
Also, in the product page it says the power can range from 6.5 to 11v, so what is those 5V and 3.3V all about?
Thanks

Vin means "Voltage Input". That's where you provide your power. That is the input to the voltage regulator.
5V and 3.3V are what the board uses internally and are provided for you to also use should you want to. These are outputs from the voltage regulators.
It's exactly the same (though more efficient and higher current) as almost every other Arduino.

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


text:
Random artifacts on SSD1306 OLED screen
I'm having a really strange problem with my screen. It's connected in i2c to my Arduino Nano and I'm using a rotary encoder to navigate through a menu.
At startup everything is fine, but when I change menus a couple of times, there are flickering artifacts that start showing up in the bottom right corner. Did anyone ever get that kind of localized noise?
I thought maybe it would be my refresh rate that was a bit too high, I only had 10ms. But I cranked it up to 50 and it didn't change a thing.
https://youtu.be/riwLRgtHG0g
EDIT: Thank you for your feedback! I tried a different approach, like you suggested, and got rid of all the calls to displayMenu() and the multiple while loops. The artifacts are smaller now, but they're still there...
They used to occur all the time and now they're just appearing during chooseValue() and action3() now. As if it was linked to the "value" variable. I don't get it...
Here's the updated code:
#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_I2CDevice.h>
#include <math.h>

#include <RotaryEncoder.h>
#include <ButtonStates.h>

#define SCREEN_WIDTH    128
#define SCREEN_HEIGHT   64
#define OLED_RESET      -1                                                  // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS  0x3C

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

RotaryEncoder encoder(A2, A3);                                              // Rotary encoder connected to A2 and A3
ButtonSwitch button(2);                                                     // Rotary encoder button

int value = 0;                                                              // Value changed in one of the menus
int selection = 0;                                                          // Encoder position

struct menuItem {                                                           // Structure defining a menu item
  const char *name;                                                         // Item name
  void (*action)();                                                         // Pointer pointing to the function handling the action
};

struct menu {                                                               // Structure defining a menu
  char *name;                                                               // Menu name
  int items;                                                                // Number of items in the menu
  struct menuItem *collection;                                              // Array containing all the menu items
};

struct menuItem menu1collection[5];                                         // Array for the menu
struct menuItem item1, item2, item3, item4, item5;                          // Items of the menu
struct menu menu1 = { "Today's menu", 5, menu1collection };                 // Structure holding all the menu's info

struct menuItem menu2collection[4];
struct menuItem item6, item7, item8, item9;
struct menu menu2 = { "Tomorrow's menu", 4, menu2collection };

struct menu currentmenu = menu1;

enum screens { MENU, CHOOSEVAL };
enum screens screen = MENU;

void chooseValue(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.write( 17 );
  display.setCursor(45, 20);
  display.print(selection);
  display.print("g");
  display.setCursor(115, 20);
  display.write( 16 );
  display.display();
}

void displayMenu(){                                                         // Function displaying the menu passed in argument
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 5);
  display.println(currentmenu.name);                                        // Display menu title

  int div = floor((selection-0.5)/4);                                       // Handle menus with more than 4 elements

  for(int i=(4*div+1), j=0 ; i<=currentmenu.items && j<4 ; i++, j++){       // Cycle through 4 menu items
    if(i==selection){                                                       // Highlight selected item
      display.fillRect(0, 18+10*j, 128, 10, SSD1306_WHITE);
      display.setCursor(20, 20+10*j);
      display.setTextColor(SSD1306_BLACK);
      display.println(currentmenu.collection[i-1].name);
    }
    else{
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(20, 20+10*j);
      display.println(currentmenu.collection[i-1].name);                    // Display item
    }
  }
  display.display();
}

ISR(PCINT1_vect) {                                                          // Interrupt routine for the rotary encoder
  encoder.tick();                                                           // Check the state of the encoder
}

// Functions handling the actions for each menu item ------------------------------------------------------------------
void action1(){
  screen = CHOOSEVAL;
}

void action2(){
  currentmenu = menu2;
  encoder.setPosition(1);
}

void action3(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(45, 20);
  display.print(value);
  display.println("g");
  display.display();

  delay(1000);
}

void action4(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.println("Action 4!");
  display.display();

  delay(500);
}

void action5(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.println("Action 5!");
  display.display();

  delay(500);
}

void action6(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.println("Action 6!");
  display.display();

  delay(500);
}

void action7(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.println("Action 7!");
  display.display();

  delay(500);
}

void action8(){
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.println("Action 8!");
  display.display();

  delay(500);
}

void action9(){
  currentmenu = menu1;
  encoder.setPosition(1);
}
// -------------------------------------------------------------------------------------------------------------------

void handleMenu(){
}

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

  // Creating a menu requires the following ----------------------------------------------------------------------------
  item1.name = "Choose a value";
  item1.action = action1;
  menu1collection[0] = item1;

  item2.name = "Go to menu 2";
  item2.action = action2;
  menu1collection[1] = item2;

  item3.name = "Display value";
  item3.action = action3;
  menu1collection[2] = item3;

  item4.name = "Item 4";
  item4.action = action4;
  menu1collection[3] = item4;

  item5.name = "Item 5";
  item5.action = action5;
  menu1collection[4] = item5;

  item6.name = "Item 6";
  item6.action = action6;
  menu2collection[0] = item6;

  item7.name = "Item 7";
  item7.action = action7;
  menu2collection[1] = item7;

  item8.name = "Item 8";
  item8.action = action8;
  menu2collection[2] = item8;

  item9.name = "< Back";
  item9.action = action9;
  menu2collection[3] = item9;
  // -------------------------------------------------------------------------------------------------------------------

  PCICR |= (1 << PCIE1);                                                  // This enables Pin Change Interrupt 1 that covers the Analog input pins or Port C.
  PCMSK1 |= (1 << PCINT10) | (1 << PCINT11);                              // This enables the interrupt for pin 2 and 3 of Port C.

  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {              // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);                                                              // Don't proceed, loop forever
  }

  // Init display
  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 20);
  display.println("Loading...");
  display.display();

  delay(500);
}

void loop() {
  switch(screen){
    case MENU:
      selection = encoder.getPosition();                                      // Get the encoder's position

      if (selection < 1) {                                                    // Stop the encoder on the min position
        encoder.setPosition(1);
        selection = 1;

      } else if (selection > currentmenu.items) {                             // Stop the encoder on the max position (number of items minus 1)
        encoder.setPosition(currentmenu.items);
        selection = currentmenu.items;
      }

      displayMenu();

      if (button.triggerSingle()){
        currentmenu.collection[selection-1].action();                         // If a click is detected do the item's action
      }
      break;
    case CHOOSEVAL:
      selection = value + encoder.getPosition() * 10;

      if (selection < 1) {                                                    // Stop the encoder on the min position
        encoder.setPosition(1);
        selection = 1;
      }

      chooseValue();

      if (button.triggerSingle()){
        value = selection;
        encoder.setPosition(1);
        screen = MENU;
      }
      break;
  }
}

You called the displayMenu method at all over the program and  recursive in itself. Why? Also, you use an eternal while (1) { in the display method. I suggest to remove the 'while(1)' loop. The only call to displayMenu that make sense, is the one in the loop() method. remove all others. I would also copy the code that starts actions from the display to the loop. Don't use delay() in the display method that stops the whole system. Use millis() (the example Blinlking LED without Delay shows you how.

Remove the while from the chooseValue method too.  Then move it to the loop function. I'm not sure I have seen all problems, but that would be a good start. If it does not hel, edit the question wit the new observations.

It looks to me like your stack is smashing into your heap.

Thanks for your feedback @PeterPaulKiefer! I updated my code in the original post.

I don't get the reference @Majenko, what do you mean?

The fact that the corruption is in the bottom right means it's at the end of the screen buffer. That will be (one of) the last thing on the heap. The stack is above the heap and grows down into it. Too many nested function calls and local variables will cause the stack to grow downwards until it overlaps with the heap, and the end of your screen buffer, corrupting the screen buffer in the bottom right of the screen. Flatten your program. Reduce RAM usage.

Ooh right! Jeez, I just turned all "ints" into "uint8_t" and it's almost gone. I think maybe my strings might take up a lot of memory. How can I optimize this? I mean, I'm used to JavaScript handling those... and here I don't know how to make it flexible and usable at the same time.

Where is ButtonStates.h from? As Majenko said, you are getting very close memory exhaustion.  I wasn't able to actually detect that that is actually happening but then I wasn't running your exact code.  Ultimately whatever the cause you may want to switch to something like u8g2 to avoid the 1kbyte malloc that the Adafruit library is doing.  So far as I can tell, you have about 130 bytes left when running your originally posted code.

For a start use F(...) around all string literals in print(...) calls and such.

ButtonStates is a library I've written to debounce buttons and recognize double clicks and long clicks. You can find it on platformio. It should be quite low consuming in RAM though. It would seem the artifacts are gone now, but I will try u8g2 in a future version! Many thanks!!

This is a solution that I accidentally came up with. I had a problem of strange artifacts corruption in bottom right corner of my SSD1306 display when I tried to print scrolled row of text.
It does its job, so if anyone come by this topic in the future feel free to test it:
int x, minX;
oled_dispMidTextScroll(F("SETPOINT REACHED! LONG PRESS LEFT TO SET UP A TIMER"));

void oled_dispMidTextScroll(String str){
  char text[50];
  int size = 1;
  str.toCharArray(text, 50);
  display.setTextSize(size);
  minX = (-1 * size * 6) * strlen(text);  // 12 = 6 (px/char) * 2 (textsize)
  display.setCursor(x,28);
  display.print(text);
  x -= 4; // speed
  if (x < minX) {x = display.width();}
}


text:
Make an LED less bright
As an exercise to learn rather then the most efficient way to accomplish a goal.... (i'm a hands on hardware guy, but I need to get my Sh!T together and learn some coding)
I would like to make an LED less bright within a project.  I have a nano set up to control a relay to control a dc load when a momentary switch is pressed (this is kinda needlessly complicated solely to allow me to use a particular momentary switch I wanted to use for a bunch of not that great reasons ;-)
Anyway... the code i'm using is this:
int pbuttonPin = 2;// connect output to push button
int relayPin = 10;// Connected to relay (LED)

int val = 0; // push value from pin 2
int lightON = 0;//light status
int pushed = 0;//push status

void setup() {
  // Robojax.com code and video tutorial for push button ON and OFF
  Serial.begin(9600);
  pinMode(pbuttonPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
 digitalWrite(relayPin, HIGH);// keep the load OFF at the begining. If you wanted to be ON, change the HIGH to LOW
}

void loop() {
// Robojax.com code and video tutorial for push button ON and OFF
  val = digitalRead(pbuttonPin);// read the push button value

  if(val == HIGH && lightON == LOW){

    pushed = 1-pushed;
    delay(100);
  }

  lightON = val;

      if(pushed == HIGH){
        Serial.println("Light ON");
        digitalWrite(relayPin, LOW);

      }else{
        Serial.println("Light OFF");
        digitalWrite(relayPin, HIGH);

      }

// Robojax.com code and video tutorial for push button ON and OFF

  delay(100);

The above code is straight up cut and paste... i'm clueless
I have a LED cathode on pin 10, (so i know the relay is on more easily from a distance).  however the application is on a boat, and at night it is too bright and distracting.  So i want to make the LED dimmer... I know I could add a larger value resistor, but i want to expand my understanding and would like suggestions on other ways PWM maybe....
cheers:

What's your Arduino? If you can connect the LED to the Arduino (=if the Arduino provides enough power), you can connect it to a PWM pin and use analogWrite(10, brightness); to change the brightness. Of course, you'd have to initialize it in the setup and replace brightness with a number in the range of 0-255.

If using the relay is your only option, here is an discussion about it in the Arduino forums.

add a resistor, don't waste resources of the MCU for this

Yeah, use Jurajs method if you want to change it just once to a lower brightness.

You could add a second relay, with a resistor, like Juraj suggested. Connect that in parallel to the cathode of the led. You can then switch between the two relays for two different brightness levels. But I think it would be better, depending on the LED you used, to swap out the relay for a mosfet. Then you can change the brightness using PWM. Add a light sensor, to automatically switch between day, and night mode, to somehow justify using an Arduino in the first place ;-p

My preferred approach is to wrap the LED in tape to make it dimmer. :) It's easier than soldering a resistor! :) j/k

There are two methods of dimming a LED : by PWM or by a limiting current resistor.

PWM code
 `//Initializing LED Pin
 int led_pin = 10;
 void setup() {
 //Declaring LED pin as output
         pinMode(led_pin, OUTPUT);
 }
 void loop() {
         analogWrite(led_pin, 127); // half intensity
         delay(5);
 }`

Hardware. Use following schematic

This soulution doesn't consider the LED needs more power than the Arduino can provide.

not all POTs will like all LEDs. while a fire is a remote chance, losing the POT isn't.

Unless you have regulated current (which would be the third option) you need a current limiting resistor in any case. No matter if you're going to dim using pwm afterwards. Your answer is misleading in that point. Also, how are you dimming the led in the second example? Isn't this pwm as well?

If you want to decrease the brightness in general, the easiest solution would in deed be to use a high value resistor.
If you want to use PWM - for example to change brightness programmatically - you just need to replace the calls to digitalWrite(HIGH|LOW) with calls to analogWrite(x) (ref), where x represents the duty cycle/brightness. The range of x depends on your microcontroller.
Note, that PWM (which is used by analogWrite()) only works on dedicated pins.
On the other side, there are microcontrollers wich have analog pin with a "true" analog output. On such an analog pin - though it is possible to use analogWrite() - the brightness will not be linear and have an offset, which makes it pretty much useless for dimming an LED.

"...the brightness will not be linear and have an offset." I don't know what you mean when you say the brightness will have an offset. It won't. It just won't be linear is all, but all PWM values > 0 will indeed produce light. There isn't a "dead band" in PWM as there is with potentiometers and joysticks, for instance.

That point referes to true analog outputs - I'll make this more clear. If I remember right, those analog pins are also used with analogWrite() on the respective arduinos, but show a much different behaviour than a PWM pin.

Oh, I see what you're saying. PWMing an output voltage which is > Vthreshold when HIGH always produces light on an LED, but if it's a true analog output there will be a deadband, or "offset", equal to the threshold voltage before the LED starts producing light. This is one of the benefits of PWM pseudo-analog output for driving LEDs over using true analog output for driving LEDs. PWM, in this case, is probably actually better.

It was a bit unclear what I meant, I guess.

Follow this tutorial. It doesn't get any better than this.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Fade


text:
SIM phone DTMF Signal Frequency Problem
Is there a DTMF signal detection method in the smartphone [SIM] call?ex) keypad value or signal value [not frequency signal]
If you press the keypad button while you're on the phone with two iPhones, you don't hear the signal. So does the SAMSUNG phone.Please let me know how to detect DTMF signals after installing the aduino SIM.
Quectel EC25

And the manual says what?

The SIM telephone [smartphone NO] operates with the program and many telephones are automatically dialed and the voice guidance is given. Here, guide is heard and client presses the consultation -1 denial -2 number.I call my smartphone, so I need to read the DTMF signal from the received smartphone. The latest smartphone seems to be unable to read the signal.

Yes, we know what DTMF is and what it's used for. What does the manual for the Quetcel EC25 say about receiving DTMF tones?

I bought a product that used this component. I need to call, voice, and read the DTMF signal. I read the signal on the wired phone.How do we solve this?

The signal of the received Smart phone has to be read.

you are not answering the question that @Majenko is asking ... it is irrelevant why you want to detect the DTMF signal

@jsotola I have given up asking. I think he's saying it works when he uses a landline but doesn't when he uses his smartphone.

I suspect that because you're going mobile-to-mobile it's assuming it should use rfc2833  and not DTMF.

A way to get the keypad number if you press your keypad. Phone on mobile

We need to get the ivr [DTMF] signal from our customer's smartphone. It's a problem because we don't get it now. How?

How can you read the mobile touch tone?


text:
Windows Driver for Arduino error code 22
I'm trying to use avrdude to load an Arduino program with the console, but I have a Windows 7 x86 Professional with Service Pack 1 (old PC).  When I install the Arduino driver that comes with the IDE manually, with pnputil.exe, in the Windows 7 on PCs that have these processors:

Intel(R) Pentium(R) 4 CPU 2.80GHz
Intel(R) Core(TM)2 Duo CPU E6400 @ 2.13GHz
Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz

I see that the drivers don't work properly.  I get error code 22 in some cases.  And in other cases, the Windows system disables the Arduino in the Windows devices and prevents enabling the COM device.
But, if I install the Arduino IDE or manually install the Windows driver on Core i3, Core i5 and i7 in Windows 7, 8 , 10, the response is perfect.  But, in the others I get error code -22 or Windows doesn't allow to enabling the device.
Has anyone had the same problem and how did you solve it?
Thanks.

Did you install the drivers as administrator? Does the user with that you installed them have full admin privileges?

Yes i install the driver as administrator


text:
Wemos Mini & Pro Micro Serial connection
While using a 3.3v Pro Mini & Wemos mini to communicate via Serial was successful, when tried with a 5v Pro Micro it fails.
To overcome different logic level I used a 10K + 20K resistors to lower Pro-Micro's 5v to 3.3v successfully to Tx and Rx pins. Also since they are on the same PCB, GND pins are connected and RAW to 5V at wemos mini  is also connected. At the moment, it is powered up using MCU's USB input ( tried to connect to Pro-Micro only, Wemos Only, and both ).

What might be the problem ?

It sounds like you have tried to put level shifting on both the TX and the RX pin. You want it only between the Arduino's TX pin and the ESP's RX pin. Not between the ESP's TX and Arduino's RX.

@Majenko see added schematic.

Yes, I thought you might have. ESP TX to Arduino RX needs to be a simple wire, nothing more.

Also you may find that your resistors are too high value. I use 1k/2k.

@Majenko - OK.. Now I get it :)

@Majenko - I followed an on-line tutorial :/

Yeah, you can never trust those online people. =)

@timemage - I see you are a keen follower for my endless mistakes ( Majenko 2 ) :)

@Majenko - to avoid my next question, as timemage suggested in my last question, when I2C between 3.3 and 5v - will I need a both resistors ?

For I2C you really want an active I2C level shifter. I2C is not push-pull like serial, but open drain. However you can probably just ignore it since the Arduino's internal pullup resistors will limit the current to such a tiny amount that the ESD diodes in the ESP8266 won't care (and there are somewhat unsubstantiated rumours that it's 5V tolerant anyway).

@Majenko - Jumpering 10K resistor did not solve the problem :(

Is your usb power coming from a computer?

@Majenko - Wrongly jumpered the Rx @ Pro-Micro. Now when Tx is has 10K and 20K and Rx is connected directly + Juraj's Serial1 - Problem is now SOLVED

You don't need a logic level conversion between 5 V Micro Arduino and 3.3 V Wemos D1 mini. The 5 V ATmega 328p reads 3.3 V as HIGH and the esp8266 can tolerate 5 V logic level for tests. For long term connection you can add logic level conversion with a voltage divider to convert the 5 V of ATmega TX to 3.3 V of esp8266 RX.
RX/TX pins on Arduino Mini are Serial.
RX/TX pins on Arduino Micro are Serial1.
Serial is only USB on Micro.

But it has Tx and Rx actual pins, which are use Serial.begib(9600) the same way

This I know. Does it change Majenko’s answer?

@Guy.D, the logic level difference is not the problem. so I guessed you used the same sketch with Serial for Mini and Micro, instead of using Serial1 for Micro. you don't need to use level shifting for a test.

yes, same code was used.

@Guy.D, then I guessed right and that was the problem. for Micro use Serial1 to communicate with the Wemos

Changing to Serial1 all Serial instances did not solve the problem. Nor Majenko's solution.

Nothing transferred... what / how would you suggest to try?

Only when applying Majenko's + your solutions, solved the problem. please update

Taking off the RX ( at PRO-Micro side ) side. It didn't work when it was installed


text:
Not Receiving HC-05 data
I've been trying to use this HC-05 bluetooth module for a project, where the data would be sent to a Max/MSP/jitter program. Initially, every time I connected my bluetooth device to my computer, it stayed connected for about 10 to 20 seconds then disconnect. I'm not sure if it's a voltage thing, but from what I read on other forums, it should work fine. My setup:
1- Powering Arduino on a wall wart (Input: 100-240V AC, 50/60Hz 0.3A ; Output: 12V DC 1A);
2- Bluetooth's Tx to Arduino's Rx (D3) and Bluetooth's Rx to Arduino's Tx (D4)
3- APDS9960 sensor also connected on the same breadboard (the sensor I should be receiving the data from, and I do, when connected on an USB cable port)
4 - HC-05 configured to be 115200 baud (AT+UART=115200,0,0), which seems to be the appropriate bps for HC-05 to Max (??)
But then... Once I logged into Max, and printed the data from this serial port (which should send data in a continuous fashion), some lines were printed and then it stopped. So I go on to check the Arduino Serial Monitor and – though everything seemed to be working fine and I received the data properly – there's nothing showing up.
#include "SoftwareSerial.h"
#include <Arduino_APDS9960.h>

SoftwareSerial blue(3,4); //rx tx, qualquer 2 portas digitais sem ser 7 e 8

void setup() {
  // put your setup code here, to run once:
 Serial.begin(115200);
 blue.begin(115200);

  Serial.println("mensagem do computador");
  blue.println("mensagem do módulo bluetooth");

   if (!APDS.begin()) {
    blue.println("Error initializing APDS9960 sensor.");
  }
}

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

    while (! APDS.colorAvailable()) {
    delay(5);
  }
  int r, g, b;

  // read the color
  APDS.readColor(r, g, b);

  // print the values
//  blue.print("r = ");
  blue.println(r);
//  blue.print("g = ");
  blue.println(g);
//  blue.print("b = ");
  blue.println(b);
//  blue.print();

  // wait a bit before reading again
  delay(100);
}


text:
Arduino mega PinChangeInterrupt with 16 bit timer
With reference to this question ::I have written a program by using 16-bit timer,
The program is as follows .
volatile uint32_t ovfCount = 0;

struct Pulse {
  uint32_t last_toggle;
  uint32_t width;
  bool stateHigh;
  uint32_t get_width() {
    noInterrupts();
    uint32_t width_copy = width;
    interrupts();
    return width_copy;
  }
};

Pulse ch1, ch2, ch3, ch4, ch5, ch6;

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

  pinMode(13, OUTPUT);

  /*
     Pin Change Interupt for
     measuring the pulse width
     from the receiver

  */

  DDRK = 0; // A8:A15 -> direction as Input
  PORTK = B00111111; // A8:A15 -> pullupResistor

  PCIFR = 0; // resetting the flags
  PCIFR  = _BV(PCIF2);
  PCMSK2 = B00111111; // activating from A8:21 :: 6
  PCICR = B00000100; // activating 2 nd PCINT

  /*
     16 bit timer setup for counting
     timer 3 is used
  */
  TCCR3B = 0x00;
  TCCR3A = 0x00; // wave generation is normal:: all zeros
  TCNT3 = 0x00;
  TIFR3 = 0x00; // resetting all flags
  TIMSK3 = 0x01; //timer overflow enable
  TCCR3B = 0x01; // no prescaling

}

ISR(TIMER3_OVF_vect) {
  ovfCount++;
}

ISR(PCINT2_vect) {
  uint8_t tcnt3 = TCNT3;
  uint32_t ovf_count = ovfCount;

  if ( bit_is_set(TIFR3, TOV3) && tcnt3 < 32768 ) {
    ovf_count ++;
  }

  uint32_t time = ovf_count << 16 | tcnt3;

  pinChangeFunction(&ch1, time, PK0);

}

void pinChangeFunction(Pulse *channel, uint32_t time, uint8_t pin) {
  bool input_is_high = bit_is_set(PINK, pin);
  if (input_is_high && !channel->stateHigh) {
    channel->stateHigh = true;
  } else if (! input_is_high && channel->stateHigh) {
    channel->width = time - channel->last_toggle;
    channel->stateHigh = false;
  }
  channel->last_toggle = time;
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(200);

  Serial.println(ch1.get_width() / 16e3, 5);

}

The output for the same is attached below,
999.42663
999.43060
999.42645
999.42614
999.42730
999.42889
1003.52416
999.41473
999.42681
999.42211
999.42077
999.42718
999.42016
1003.52447
999.41802
999.42480
999.42541
999.43603
999.42767
1003.52075
999.42199
999.42767
999.41876
999.42816
999.41143
999.41998
1003.52429
999.42730
999.42950
999.41149
999.42028
999.42700
1003.50775
999.43743
999.42858
999.42584
999.41381
999.42852
999.43347
1003.52490
999.41925
999.41540
999.42510
999.42895
999.42980
999.42883
1003.52526
999.43658
999.43707
999.42889
999.41284
999.42401
1003.52343
999.42901
999.42950
999.42822
999.43481
999.42718
999.41986
1003.52398
999.42303
999.41442
999.42498
999.42950
999.42547
1003.51074

When I observed the output , I am seeing 999 millis almost instead of 1000 as expected and  in-between  1003 is coming instead either of 999/1003.
Also if we look carefully it can be observed that ,999 is coming 6 times then one 1003 is coming and is going 2 times like that then 5 times 999 then 1003
so I want to know what mistake I am making in my program , and what is the reason behind these kind of behaviour .

Please answer  @edgar-bonet .

TCNT3 does not fit in a uint8_t.

Thanks . Its working


text:
Can I Control My Android Game with Arduino Gamepad
I have a project that I need to make a game(guitar hero like rhythm game) on unity for android and develop a custom controller for it that works on mobile game. I decide to use Arduino and hc05 module for communication via bluetooth. But every tutorial that I watched on internet that phone used as a controller, I want to make it reverse. I want to use Arduino as a gamepad on Adnroid. Is that possible?

Not with a HC-05, unless you want to write your game to use serial communication specifically (i.e., be 100% custom with the control interface). HC-05 cannot be a game controller. Only serial.

Majenko is right, though there are other bluetooth boards, that support the HID protocol. You could search or them. Or you need to implement serial communication into your game for it working with the HC-05

So ESP32 can be a solution?


text:
DHT-sensor-library-master
I only uploaded the library to check whether it has installed correctly. It's installed and i am having this error. Using library DHT-sensor-library-master at version 1.4.1 in folder: C:\Users\Mcniven\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:29: fatal error: Adafruit_Sensor.h: No such file or directory
#include <Adafruit_Sensor.h>
exit status 1
Error compiling for board Arduino/Genuino Uno.

Did you install the Adafruit_Sensor.h library?

Did you install the library by just copying it to the “libraries” folder without checking dependencies (looks like it) or did you install it from the Arduino IDE?


text:
Getting different numbers after sending an unsigned int 8-9 times between Arduinos via Serial
I am trying to transfer unsigned int values between 2 Arduinos. When sending 61805 for the first 8-9 times, I am getting 61805.  But after then after these numbers: 61937 28013 61937.
Sender's code:
unsigned int s = 0;

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

void loop()
{
  s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

Receiver's code:
unsigned int upperByte, lowerByte, r=0,p=0;

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

void loop ()
{
  if (Serial.available() > 1)
  {
    upperByte = Serial.read();
    lowerByte = Serial.read();
  }

  r = (upperByte << 8) + lowerByte;
  Serial.println(r);
}

There's no flow control on the Uno and Nano serial and you are sending fast enough that bytes are being dropped, and there's no way your protocol or lack of one demarcates separate messages (separate numbers).
This will become more clear if you write your numbers in hexadecimal:

Dec
Hex

61805
0xf16d

61937
0xf1f1

28013
0x6d6d

61937
0xf1f1

Adding a delay between messages can serve to separate the messages if the receiving side makes use of a timeout and can prevent the receiving side from being overwhelmed with data.
If you don't want to use time to slow down and separate your data, you can change what is sent instead.  One idea is to have the receiver actively request data when it's ready to receive some. The receiver should expect only entire messages between requests, and if anything gets garbled, it can just read whatever data has come in and throw it out before the next request.
Your messages can also be separated by some characters that aren't part of the messages themselves.  A common way to do that is just to encode your numbers as separate text lines, the line terminator \n serving as the separator between messages.
I have not tested these yet, but here are some very minimal modifications to your code that approach having a protocol with fewer of these problems:
Sender:
void setup () {
  Serial.begin(9600);
}

void loop() {
  // await message request
  while(Serial.read() != '.') {
  }

  //
  const unsigned int s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

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

void loop () {
  // request message
  Serial.write('.');

  // await two-byte response
  const unsigned long request_sent = millis();
  while (Serial.available() < 2 && millis() - request_sent < 1000) {
  }

  if (Serial.available() != 0) {
    if (Serial.available() == 2) {
      // two byte response receive
      const unsigned upperByte = Serial.read();
      const unsigned lowerByte = Serial.read();
      const unsigned r = (upperByte << 8) + lowerByte;
      Serial.println(r);
    }  else {
      // Something went wrong, too or too few bytes received;
      // throw them out and start over.
      delay(100);
      while (Serial.read() != -1) {}
    }
  }
}

It's a long way from doing it properly, but it should behave at least better than what you started with.  There's a lot to designing even simple protocols.  Typically there are start and end frame bytes, a checksum or CRC, a message number counter, etc.

thanks brother it worked .....thanks a lot....

We use to send 8,N,2 and receive on 8,N,1. That gave us an extra bit time to adjust for clock skew.

This line of the receiver's code:
Serial.println(r);

is transmitting 7 bytes (5 digits, CR and LF). At 9600/8N1, each byte
takes 1.04 ms, so the whole message is transmitted in 7.28 ms. In the
meantime, the sender is sending 2-byte messages at full speed (no pause
between the bytes). The receiver thus gets a new message every 2.08 ms.
So, this receiver is given a new message to relay every 2.08 ms, and it
needs 7.28 ms to relay each message. Something has to give...
The reason it works in the beginning is that the receiver has a buffer
where it stores the bytes that have been received, and another one for
the bytes that have been made ready for transmission. As long as there
is room in those buffers, everything works fine. The transmit buffer
fill-up first, as it gets 7 bytes to transmit every 2.08 ms. Once it's
full, Serial.println() becomes a blocking function: it has to wait
for the buffer to have enough room. Your loop() then slows down to
match the speed of the transmission, which means you do not read the
receive buffer often enough. Then the receive buffer fills up, and you
start loosing bytes.

thanks brother for you effort.... nicely explained... got the point


text:
Directly synthesising an OOK modulated LF signal using a CSV file
I'm looking to transmit some data (CSV files) from a measurement instrument underground to a receiver on the surface. I've learned that in order to penetrate the limestone, low frequencies have to be used (around 80-130kHz). There are various methods to achieve this including ground-spike antennas that use the earth between two electrodes to help form a large antenna by injecting current into it, and magentic loop antenna pairs that essentially work as an inductor by transmitting and receiving the magnetic (H) component of the RF transmission rather than the low power E field component.
With that put aside, I've noticed that there aren't any existing RF modules that transmit at these frequencies. Because of that I've considered the posibility of directly synthesising a modulated signal using an Arduino (UNO or Nano). As far as I understand it I need a direct digital synthesis (DDS) IC to generate a reference frequency. From there I understand the Arduino can be used to calculate a waveform that simulates the modulation of that carrier in the mentioned frequency range. I've identified that on-off keying (OOK) would be a suitable modulation method due to its simplicity and resistance to noise.
This is where I need some help. How do I take a CSV file, use its contents to OOK modulate a carrier wave and then directly synthesise this waveform using Arduino? Are there libraries that already exist to enable this? If so, how would I use them? I don't have extensive programming knowledge so I'd appreciate any help I can get.

I've noticed that there aren't any existing RF modules that transmit at these frequencies. -- because of licensing. You're not allowed to in most places unless you have that frequency band allocated to you by the regulatory body for your area.

what hardware are you using? ... a library is useless if you have nothing for the library to control

You can just use raw Serial data for OOK control - that way it does all the start/stop framing for you.

@Majenko how can I do this? Do I mix the serial data with the carrier by analogue means at the output? Or am I missing some theory an experienced Arduino user has?

Serial will give you a digital on/off signal. Use that as the data input to your modulator circuit.


text:
Can ESP32 used for mobile game controller?
I have a term project: I need to develop a mobile game(Guitar Hero Like rhythm game) probably on Unity  and I need to develop a custom controller for this game that works on android device. There will be 3 buttons for notes and Bluetooth connections between android device and controller. My question is can I use ESP32 as a mobile game controller. If it's yes, which model that you suggest me?

Yes you can, Pick the most inexpensive one that supports Bluetooth, you only need 3 inputs.

Anything that supports BT/BLE could be used.


text:
This website in Arduino lists language references like functions and structures. What makes structures there different from functions?
https://www.arduino.cc/reference/en/
Language Reference
Arduino programming language can be divided in three main parts: functions, values (variables and constants), and structure.
functions
For controlling the Arduino board and performing computations.
variables
Arduino data types and constants.
structure
The elements of Arduino (C++) code.
I find it really confusing that they had to separate the structures but also call them functions in their descriptions. I kind of want to get a visualization or organization of the different language references present in Arduino, but this just confuses me. Are structures in the website also functions, and mainly syntax can be classified into functions and variables? Can someone present a organization of language references that doesn't involve terminologies being mixed up?

please provide an example of what confuses you

perhaps it may clear your thoughts if you review C++ programming

They're playing loose with terms.  If you want a clearer understanding of C++ the C++ standard itself is a better reference.

What the website names "Structures" are code building-blocks for the programs you write. The main part there are conditional (if-else) and loop instructions (for, while) as well as mathematical operators. You use these constructs within your functions to control program flow or compute results. Functions, on the other hand, are sub-programs you can call to have certain tasks done. They might be pre-defined (such as the ones described on the language reference page) or written by yourself.
Now there are two exceptions to this rule, and maybe that's what's a bit confusing in the documentation: The functions setup() and loop(). These are functions, but make up the structure of your program. They are the main building blocks of an Arduino sketch, and that's probably why they're mentioned under "Structures".

Yes, this is the kind of explanation I am looking for. Someone who has a clear visual of their own with how the hierarchy of how the types of code are. It makes it really clear that under programs, we can put functions and under that we can put structures. Yes, the set up and loop is confusing but I would prefer categorizing it as functions because you can put structures inside.
I'd like to ask, what references do you use for Arduino? You seem to have a good personal grasp on terminologies.

Actually, I use exactly that page for things that are arduino-specific, and any other resources I find for any C++ issues I come across. The Arduino compiler is a full-featured C++ compiler, with almost all the features the normal GCC also has. The library functions are also all there, so if you need help for things like malloc or free just use your preferred search engine. (One exception here: STL support is not available out-of-the-box).


text:
Deactivate pushbuttons at initial stage
Pl someone answer my question. I have 4 pushbuttons namely add/reject/start & finish. I want to
1.Deactivate add/reject buttons at initial stage until start button pressed &
2.Once add/reject activated, again should deactivate once finish button pressed &
3.Again if start button pressed, add/reject should be released.
with following code I able to do 2 & 3. However I still lack at 1.pl help on this.
const int bt_Select = 2; // #define BUTTON_PIN 2
const int bt_Reject = 3;
const int bt_Start = 7;
const int bt_Finish = 8;

boolean decision=false;

int bt_Select_state=0;
int bt_Reject_state=0;
int bt_Start_state;
int bt_Finish_state;

int selected;
int rejected;
int started;
int finished;

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(bt_Select, INPUT_PULLUP);
    pinMode(bt_Reject, INPUT_PULLUP);
    pinMode(bt_Finish, INPUT_PULLUP);
    pinMode(bt_Start, INPUT_PULLUP);
    Serial.println("Welcome to Nano");
    delay(1000);
  }
//========================================================================
      void loop() {

        started=bt_Start_pressed();
        selected =bt_Select_pressed();
        rejected=bt_Reject_pressed();
        finished=bt_Finish_pressed();
        decision=Stop_Main();

          int x=0;
          int Lx=0;

       if (selected&&decision){x=1;}
       if (rejected&&decision){x=2;}
        if (started&&decision){x=3;}

       if (x!=Lx){
        switch(x) {
          case 1:Serial.println("Selected");delay(250);Serial.print("");
                 break;
          case 2:Serial.println("Rejected");delay(250);Serial.print("");
                 break;
          case 3:Serial.println("Started");delay(250);Serial.print("");
                 break;

          /*case 3://do something when var equals 1
                 Serial.println("Removed");
                 break; */
             }//switch(x)
                 x=Lx;
      }//eof  if (x!=Lx)

      }
//====================================================================
      int bt_Select_pressed(){
         bt_Select_state=digitalRead(bt_Select);
           if (bt_Select_state == LOW){return 1;}
           else {return 0;}
      }
//====================================================================
      int bt_Reject_pressed(){
         bt_Reject_state=digitalRead(bt_Reject);
          if (bt_Reject_state == LOW){return 1;}
          else {return 0;}
           }
//====================================================================
    int bt_Start_pressed(){
         bt_Start_state=digitalRead(bt_Start);
          if (bt_Start_state == LOW){return 1;}
          else{return 0;}
            }
//====================================================================
      int bt_Finish_pressed(){
        bt_Finish_state=digitalRead(bt_Finish);
          if (bt_Finish_state == LOW){return 1;}
          else {return 0;}
      }
//=====================================================================

      boolean Stop_Main(){
        bt_Start_state=digitalRead(bt_Start);
        bt_Finish_state=digitalRead(bt_Finish);

        if (bt_Finish_state == LOW){decision=false;return decision;}
        if (bt_Start_state == LOW){decision=true; return decision;}

       // else if (bt_Start_state ==HIGH  && bt_Finish_state == HIGH){decision=false;return decision;}
          }

/*  boolean bt_Start_pressed(){
         bt_Start_state=digitalRead(bt_Start);
          if (bt_Start_state == LOW){started=true; return decision;}
          else{started=false; return decision;}
            }   */
    //===================

you are not thinking clearly about the problem ... it is not deactivate button ... it is ignore button ... use a state variable like bt_Start_state ... just ignore add/reject buttons until the state variable is true

Keep a boolean that begins as false. Set it to true when the start button is pressed, and set it to false again when the finish button is pressed. Then you can read and respond to the add and reject buttons only if that boolean is true, and otherwise ignore them.


text:
5V pin out, 8 pins and micropython/circuitpython support: does such a board exist?
For a project, I am looking for a board to connect eight different neopixel-strips to, on eight different data pins. Because of the great length between the board and the first pixels of these strips, I'd like to have a board that operates on 5V instead of 3.3V. Then, the software that I have written to manage the LEDs is made in (micro)python. Finally, for simplicity's sake, I'd like to run this complete project on a single board without too many external components.
So, I have found 5V boards with enough pins, like the Arduino Mega. I have also found boards with enough pins and support for micropython or circuitpython, like the ESP32 or Arduino Zero.
However, I haven't quite found a board that matches all my requirements. The Arduino Mega doesn't support Python (or does it?) and the ESP32 and Arduino Zero operate at 3.3V, not 5V.
Of course, an ESP32 with a level shifter (as shown on https://github.com/Aircoookie/WLED/wiki) would work, but is there perhaps a board out there that fits all my requirements our of the box?
Edit: It seems I misunderstood some things about the hardware - sorry, I'm a software guy, not really a hardware guy :-) I fixed the question above as not to confuse future readers.

which therefore need to be capable of PWM -- Nope. PWM has nothing to do with Neopixels. Think again. ;; Because of the great length of these strips, I'd like to have board that operates on 5V instead of 3.3V -- Nope. The voltage, as long as it's above VIH of the first neopixel, has no effect on the rest of the chain.  Think again.

As many new boards are release every year and many others get discontinued, we cannot really keep track on all boards. I don't know about a board with your requirements. Though for me it is also not clear, why you are setting those requirements. As I remember, driving a Neopixel strip does not require a PWM pin. And what exactly has the length of the strip to do with the signal voltage level? I think each NeoPixel will output the rest of the data on its own, then using its supply voltage (meaning 5V). I can easily drive a small Neopixel strip with an ESP. Should also work with a long one

There are not so many ARM chips with 5V IO (I know only about SAMC20/SAMC21) with memory big enough to run micropython and that much strips. Btw teensy + octoWs2811 shows how could it be done (it's using DMA, several DMA channels connected to several trigger sources from timer)

Yes, @Majenko and chrisl, you were right. I thought again and have updated my question.

Why do you specifically want the strips on different pins?

I'm afraid otherwise the combined strip will be too long, @DaveNewton

Too long for what? How long are the strips?

too long to carry the current, I guess? The thing is that the strips are relatively far removed from the board (±5m) and different strips are also physically located at different positions sometimes a few metres apart themselves again.
I reckon that it's easier to wire each strip to the board instead of each strip to another strip. I'm just the software guy here, though - not in charge of the hardware in this project :-)

Both your "requirements" for the board are non-requirements.

You do not need PWM pins to drive Neopixel strips. The Neopixel uses its own custom protocol that has nothing at all to do with PWM.
Your board only communicates with the first Neopixel. That one then communicates with the second, which then communicates with the third, etc. The length of the strip is completely irrelevant to what voltage you might want to drive it with.

You only care about having enough general IO pins and if the IO voltage is suitable to communicate with one Neopixel.
According to the WS2812B datasheet VIH is 0.7Vdd, which if you are powering the strips from 5V means 0.7 * 5 = 3.5V. However I think that is an overestimation and they are erring on the side of caution there, since I regularly drive WS2812B strips from a 3.3V microcontroller with no problems whatsoever (after all it's only 0.2V difference).
So just use your favourite 3.3V microcontroller that can run micropython and, if you really want to, drop the power supply voltage to the strips a fraction with a diode.

It usually works from 3.3V without any problem. At most I've heard about low temperatures might cause it stops working. However I was thinking about using diode between power ground and MCU ground to add a bit offset (but I've never actually needed it)

Got it, thanks a lot. The PWM was indeed a non-requirement. The 5V comes from the fact that the board will be several meters away from the first neopixel (I misunderstood from our hardware girl, I'm just the software guy), but we'll be using a level shifter anyway now, so we're good.


text:
ESP8266 ESP-01s Not Responding, No LED Blinking, Overheating
I have an ESP-01s that I want to use as a shield so my Arduino Uno project could communicate with my Blynk app through wi-fi. I used this video as reference.
This is the sketch. It is just the ESP8266_Shield example from the Blynk library.
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

char auth[] = "-------";

char ssid[] = "-------";
char pass[] = "-------";

#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2,3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);

void setup()
{
  // Debug console
  Serial.begin(9600);

  delay(10);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  Blynk.begin(auth, wifi, ssid, pass);
}

void loop()
{
  Blynk.run();
}

This is the schematic:

What happens:

The moment the Arduino is connected, the Blue LED flashes for a split second then all LEDs will remain off. No red led, no blue led, really just off.
The ESP-01s becomes very hot to the touch
Tried speaking to the ESP-01s through the Serial Monitor with BareMinimum example @115200 baud rate (Many Sources say that this is the default baud rate of the recent boards) however no response whatsoever.
Running the code above will get this error:

What I've done:

Tried using the HW-131 Breadboard Power Supply to supply the 3.3V (Common GND with Arduin) of the ESP-01s because I read that the ESP-01 could need more current than the Arduino Uno could provide. Still the same effect, no LEDs blinking, (even more) hot to touch, not responding to AT commands.
Attempted to follow a video on how to flash the ESP-01s but when I tried to run the flasher, it could not communicate with the ESP-01s.
Switching Rx Tx ESP-01s but no luck.
Added a 10k ohm resistor from 3.3V to the Vcc and EN pins of the ESP-01s. Not heating up anymore but still no response.

I really thought this is a power problem but could it be the ESP-01s itself is defective?
This is what the ESP-01s look like

Overheating = bad. Sounds like it's dead.

I don't see a pullup on the ESP's reset line. I doubt that is causing your your heating issue but you may get spontaneous reset issues later.

The ESP8266 is (highly likely) dead. The overheating is the giveaway.
Because you haven't mentioned it, please measure the 3.3V coming out of the Arduino with a multimeter. Unlikely to be the issue but it is easy to check.
You will need to buy a new ESP8266 and connect it up and give it a try with a fresh board. If all is good with the new board then the first thing you will notice is that there is no overheating. (If there is overheating, then you need to check your wiring.)
I notice that quite a lot of people add a 10K pull up resistor between the 3.3V line and the Enable pin. It certainly won't hurt to add a 100 ohm resistor between the Tx pin and D2 of the Arduino as a current limiting resistor, just in case.

I forgot all about this thread and yes that was the case :( I got a replacement ESP-01s and it worked.


text:
Stable amplitude of amplified signal
Is there any circuit with opamp where can be (by arduino) set constant output amplitude which doesn't depend on input signals amplitude?

What signal? It sounds like you're asking for an AGC circuit with adjustable level.

NB: AGC = Automatic Gain Control

Yes. AGC will help me in this project. Thank you both.

Just for grins I googled "digital control AGC" and got about 5 million hits. A lot more information is needed to properly answer your question. Please define the input and output signals, level, frequency, etc. Note the rate of change will have a large effect on the AGC filters and Arduino response (partially controlled by your software) will make or break the whole design. Include a proposed schematic, not a frizzy drawing.

Just a word of advice about AGC in general.  There is almost always an issue of attack (how fast the AGC reacts to a sudden increase in signal) and release (how fast it reacts to a decrease).  In most AGC cases you will need to make compromises on these two settings to avoid poor behavior from the AGC... it's not a drop-in solution with pre-determined optimum settings for every purpose.  Depending on the program material, you can get obnoxious artifacts like breathing and pumping for speech and music.  ACG is much better at slow drifting things like signal fade.  I just want you know what you might be getting into...


text:
Raspberry Pi with multiple arduinos using spi
I want to use Raspberry Pi as an aggregator & distributor of messages originating from or destined for a flight simulation program.
I'd like to use arduinos connected via spi as specific hardware controllers, communicating as fast as possible with the raspberry pi to accept messages as they come from the simulation program and at the same time to transmit messages to the simulator when various switches and controls are operated.  At the same time, each arduino might need to control additional spi devices by acting as master, when not operating in slave mode to the raspberry pi.
Can several Arduinos be connected to a Raspberry Pi as a slave devices while acting as a master device for other devices connected to the arduino like an adc, a dac, a multiplexer or motor controller?

yes ...........

Personally I'd use the USB connections... much simpler.

Yes it can be done but it is not to common. It will be a nightmare with the chip selects. The SPI was designed as a local high speed bus for use on a PCB, not communication between modules. This link will help explain what I am trying to say: http://www.eeherald.com/section/design-guide/esmod12.html Remember you will have to use a level translator for the Pi.


text:
Fail uploading any sketch to ATtiny85 USB
I have a Digistump's ATtiny85 (probably a clone ), which fails uploading any sketch, saying: Warning: device with unknown new version of Micronucleus detected. This tool doesn't know how to upload to this new device. Updates may be available. I'm using Ubuntu 20.04 and Arduino IDE 1.8.13.
I used these guides:

Digistump's troubleshooting for linux

Kovo's blog

After using these guides, finally I stop getting this error, but when trying to upload the firmware ( last line at Kovo's ), I get this error:
`guy@desktop:~/tmp/micronucleus/upgrade$ ~/.arduino15/packages/digistump/tools/micronucleus/2.0a4/launcher -cdigispark  --timeout 60 -Uflash:w:~/tmp/micronucleus/upgrade/t85_default.hex:i
Running Digispark Uploader...
Plug in device now... (will timeout in 60 seconds)
> Please plug in the device (will time out in 60 seconds) ...
> Device is found!
connecting: 16% complete
connecting: 22% complete
connecting: 28% complete
connecting: 33% complete
> Device has firmware version 2.4
> Device signature: 0x1e930b
> Available space for user applications: 6522 bytes
> Suggested sleep time between sending pages: 7ms
> Whole page count: 102  page size: 64
> Erase function sleep duration: 714ms
parsing: 50% complete
> Program file is 1594 bytes too big for the bootloader!

Did someone encounter this ?

I'd probably start here: https://github.com/micronucleus/micronucleus/issues/148

from Daves Comment
need to download upgrade-t85.hex (which is not t85_default.hex) from link


text:
I have five pushbuttons that refer to a specific pin number. I need an efficient code to set the variable for the pin with state 1. What can I use?
There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.
We make use of the concept that there can only be one active push button which means the pin of that would have a state of 1 and the rest would be 0. The long method for this would be to use if else and digitalRead(pin) == 1 for everything but that would be so long on code. I've considered using do while or while loops to stop until it reaches the push button with a state of 1, but I was wondering if there was a more efficient code. I was also thinking if there was something that made use of an array?
Though the idea of like having a simple array return the index which results to a corresponding value, like lets say Array[3] ==1 among all the indices from 0 to 4 feels easy to conceptualize, I believe this can be really taxing on the code and might not be able to be done in a short way.
I've also thought of possibly using switch case, where the variable would be the high state and the case values would be the digitalRead for each pin? But that would be wrong probably because I'm not sure but you can't set the switch variable to be a constant. It would be something like
switch (1)
case digitalRead(1):
case digitalRead(2):

what does this mean? but that would be so long on code ... you can use an array ... how do you expect to refer to the array elements without using a loop or multiple if- else if statements?

Array would definitely be used but I was thinking that if else is too long IF other codes like loops like do while, while, for can do the job with less code.

you could use hardware ... search priority encoder

don't be thinking of being fancy with the code by using switch-case form instead of multiple if statements ... the compiler may actually produce the same code

put the button pin numbers in an array ... then you can use a for loop to read each pin and return either the lowest, or the highest pin number (or both)

It is not clear to me, what behavior you want. I understood the following: the user might press multiple buttons, but only the one, which is first in the row of pressed buttons will be registered. So id the user pressed button 3,4 and 6, only button 3 would be registered. Is that correct?

No, let us assume that the user might only press one button. I'm currently working on just a TinkerCAD simulation of this idea, so I will disregard the multiple buttons scenario since virtually your cursor can really only hold on to one push button there.

There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.

Here is a short snippet of what I think, that you want. This is quite a long shot, since your question is not clear enough.
int ActiveButton = -1; // Initialize ActiveButton with -1 (no button is active)
int button_pins[] = {1, 2, 3, 4, 5}; //Array with pin numbers of the buttons

void loop(){
    for(int i=0;i < sizeof(button_pins)/sizeof(button_pins[0]); i++){
        if(digitalRead(button_pins[i])){ //if the i-th button was pressed
            ActiveButton = button_pins[i]; // assign i-th button pin number to variable
            break; // Break, since we have found our pressed button, ignore all following pins
        }
    }
}

This will assign the pin number of the pressed button to the variable. The condition in the for loop
sizeof(button_pins)/sizeof(button_pins[0])

will make the code loop over all elements of the button_pins array. sizeof(button_pins) returns the number of bytes in the button_pins array. Then we divide through the number of bytes in the first element to get the number of elements in the array.

Yes, this kind of code is exactly what I wanted. I needed to use it for lighting up LEDs differently. The problem when I tried this is my lights did not turn off when the buttons weren't pressed and only changed when another button was pressed. I did not indicate this in the original post because I already knew how to do the LED part and wanted to focus on that, but yeah I had to bring it up now. How do you make it so that the loop turns off when the pressed button is unpressed?

That is the only problem. Everything else works. I appreciate your effort. I've tried putting an else condition to set the ActivePushButton to 0 but that didn't seem to do as I intended. For more context, after that code of yours I put a switch function for cases 1 to 5 to execute the custom five functions then the code for the custom five functions after.

Update. I actually did this already by setting the ActiveButton equal to 0 after the switch cases. I just left this question in case you were gonna offer a different suggestion.

Yes, I would have suggested something like that. If it now works, I don't have anything to add.


text:
Where to go after Arduino?
I apologise in advance if this question is not right for this Stack or if it has been answered before but here goes. I have been learning C/C++ using the Arduino Uno and have gotten the hang of it now (I have knowledge of other programming languages so it wasn't too difficult to get in the rhythm). I was wondering how I would go about creating a standalone solution if I wanted to display information on four or five displays similar to These. I would pull data from a network to display on them too so I would also need to accommodate an ethernet or WiFi shield.
I appreciate any help or pointers in the right direction that can get me started on my journey to creating some custom embedded systems (if that is indeed what I am describing).

continue with Arduino for this project

You can use an ESP8266 or ESP32. This makes it easy to transmit data via WiFi. You can also use the Raspberry Pi, which is much more powerful.

There are a lot of much more powerful boards available (especially if you move from ATmega to ARM).  I'm partial to the Teensy boards myself but Adafruit also makes some nice ARM-based boards.  For example, I'm currently developing a multi-user, Arduino-compatible Unix-ish OS on one of the latter (48MHz ARM, 256kB flash, 32kB SRAM) and it runs great.  Honestly, controlling 5 non-graphical LCDs over I²C is should be easily doable on an Uno but if you need more power there are lots of options available.
(No affiliation to either of those companies)

Uno's major limitation is it's 2KB of RAM. If your project can live within that, an Uno can host it.
The display you pointed to is an I2C device and can be bussed, so Uno pin count won't be a limitation. Current might be, and you may need to power the displays independently of the Uno.
The ESP-01 module makes a good Wifi accessory which you can build onto a proto-shield or wire separately. If your Uno is powered at 5v as most are, you'll need to provide 3.3v power to the ESP, and a voltage divider on the ESP's receive pin to reduce the serial input from the Uno to 3.3v.
Update:Upon re-reading, your title suggests you want to move on from an Uno, and you've mentioned a stand-alone solution.
There are many more capable boards available. Arduino Mega is one which would be an easy, almost trivial, transition up from Uno, in flash memory, RAM, and available I/O.
If by "stand-alone" you meant "roll your own", there are any number of how-to projects on the web for rolling your own Atmega 328p-based clone of an Uno.
The direction you take really depends on your project needs and/or your personal preference.


text:
Http Client requests
I am working on a project where the ESP 8266 sends a very long string about 3000 chas over http as client. Likewise sensor data are determined. The loop repeats itself every 250ms. Now I noticed that my server gets the data of the ESP often slower. In rare cases it takes up to a minute until the server receives something.
How do these delays occur and why are they not constantly the same?
Does the length of the string have something to do with it or how much does it affect the delay?
Are calculation and sensors processed only after sending?
The ESP works with this function.
String http_GET(String value){
  String payload = "non_Message";
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
    //WiFiClient client;
    HTTPClient http;  //Declare an object of class HTTPClient
    String send_data = "http://" + web_conect + value;
    //http.begin(client, send_data);
    http.begin(send_data);
    //http.begin("http://" + address + ":" + port + "/" + path +"?" + param + "=" + value);  //Specify request destination
    int httpCode = http.GET();                                  //Send the request

    if (httpCode > 0) { //Check the returning code

      payload = http.getString();   //Get the request response payload
      Serial.println(payload);             //Print the response payload
      cut_time_date(payload);

    }

    http.end();   //Close connection

  }
  return payload;
}

I suspect it could be Strings fragmenting your heap, making it take longer to find free slots as time goes on. Don't use String for long-running or repeatedly-running operations. Take the String usage out and see if it stop slowing down, if so, you found the problem.

I tried it once. Unfortunately, the problem is still there. For me it is not bad, but I would still be interested where these delays come from.


text:
Having trouble compiling in VsCode when including arduino libraries. (Win10)
I recently switched over to Visual studio code and away from the arduino IDE though I am a novice at both. When using VSC and the neopixel library and sample code(strandtest) containing animations such as color wipe, I run into declaration errors. I have insalled the library to the project im working on, it is declared by default in the platformio.ini file as expected. The animation function is in the code as well and the same code works just fine in the Arduino IDE as stated. The standard example files (ie ones other than strand test with no declared function animations) work just fine no declaration issues. When I compile in the arduino ide it works as expected can use the example and immediately upload it no problem.
#include <Arduino.h>

// A basic everyday NeoPixel strip test program.

// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
//   connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
//   a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
 #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN    3

// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 4

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

// setup() function -- runs once at startup --------------------------------

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

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}

// loop() function -- runs repeatedly as long as board is on ---------------

void loop() {
  // Fill along the length of the strip in various colors...
  colorWipe(strip.Color(255,   0,   0), 50); // Red
  colorWipe(strip.Color(  0, 255,   0), 50); // Green
  colorWipe(strip.Color(  0,   0, 255), 50); // Blue

  // Do a theater marquee effect in various colors...
  theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness
  theaterChase(strip.Color(127,   0,   0), 50); // Red, half brightness
  theaterChase(strip.Color(  0,   0, 127), 50); // Blue, half brightness

  rainbow(10);             // Flowing rainbow cycle along the whole strip
  theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant
}

// Some functions of our own for creating animated effects -----------------

// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
  for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //  Set pixel's color (in RAM)
    strip.show();                          //  Update strip to match
    delay(wait);                           //  Pause for a moment
  }
}

// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait) {
  for(int a=0; a<10; a++) {  // Repeat 10 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in steps of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show(); // Update strip with new contents
      delay(wait);  // Pause for a moment
    }
  }
}

// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
  // Hue of first pixel runs 5 complete loops through the color wheel.
  // Color wheel has a range of 65536 but it's OK if we roll over, so
  // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
  // means we'll make 5*65536/256 = 1280 passes through this outer loop:
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      // Offset pixel hue by an amount to make one full revolution of the
      // color wheel (range of 65536) along the length of the strip
      // (strip.numPixels() steps):
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
      // optionally add saturation and value (brightness) (each 0 to 255).
      // Here we're using just the single-argument hue variant. The result
      // is passed through strip.gamma32() to provide 'truer' colors
      // before assigning to each pixel:
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
  int firstPixelHue = 0;     // First pixel starts at red (hue 0)
  for(int a=0; a<30; a++) {  // Repeat 30 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in increments of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        // hue of pixel 'c' is offset by an amount to make one full
        // revolution of the color wheel (range 65536) along the length
        // of the strip (strip.numPixels() steps):
        int      hue   = firstPixelHue + c * 65536L / strip.numPixels();
        uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show();                // Update strip with new contents
      delay(wait);                 // Pause for a moment
      firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
    }
  }
}

The error I run into when compiling is as follows.
> Executing task in folder led pir: C:\Users\Yeee\.platformio\penv\Scripts\pio.exe run --target upload <

Processing nanoatmega328new (platform: atmelavr; board: nanoatmega328new; framework: arduino)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/nanoatmega328new.html
PLATFORM: Atmel AVR (3.1.0) > Arduino Nano ATmega328 (New Bootloader)
HARDWARE: ATMEGA328P 16MHz, 2KB RAM, 30KB Flash
DEBUG: Current (avr-stub) On-board (avr-stub, simavr)
PACKAGES:
 - framework-arduino-avr 5.1.0
 - tool-avrdude 1.60300.200527 (6.3.0)
 - toolchain-atmelavr 1.50400.190710 (5.4.0)
LDF: Library Dependency Finder -> https://docs.platformio.org/en/latest/librarymanager/ldf.html
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 7 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <Adafruit NeoPixel> 1.7.0
Building in release mode
Compiling .pio\build\nanoatmega328new\src\main.cpp.o
src\main.cpp: In function 'void loop()':
src\main.cpp:59:43: error: 'colorWipe' was not declared in this scope
   colorWipe(strip.Color(255,   0,   0), 50); // Red
                                           ^
src\main.cpp:64:46: error: 'theaterChase' was not declared in this scope
   theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness
                                              ^
src\main.cpp:68:13: error: 'rainbow' was not declared in this scope
   rainbow(10);             // Flowing rainbow cycle along the whole strip
             ^
src\main.cpp:69:25: error: 'theaterChaseRainbow' was not declared in this scope
   theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant
                         ^
src\main.cpp: In function 'void colorWipe(uint32_t, int)':
src\main.cpp:81:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
   for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
                 ^
src\main.cpp: In function 'void theaterChase(uint32_t, int)':
src\main.cpp:96:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
       for(int c=b; c<strip.numPixels(); c += 3) {
                     ^
src\main.cpp: In function 'void rainbow(int)':
src\main.cpp:112:19: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
                   ^
src\main.cpp: In function 'void theaterChaseRainbow(int)':
src\main.cpp:136:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
       for(int c=b; c<strip.numPixels(); c += 3) {
                     ^
*** [.pio\build\nanoatmega328new\src\main.cpp.o] Error 1
================================================================================== [FAILED] Took 1.30 seconds ==================================================================================
The terminal process "C:\Users\Yeee\.platformio\penv\Scripts\pio.exe 'run', '--target', 'upload'" terminated with exit code: 1.

Terminal will be reused by tasks, press any key to close it.

add forward declarations of functions. in Arduino IDE the builder does it for you at ino to cpp conversion

@Juraj, if you make that an answer, I'll vote it up, because it points out something relevant to using the Arduino core and libraries with their build environment.  IMO, to be a valid answer it needn't necessarily explain the required C++ aspects, however helpful that might be.  That this is apparently just part of the trade made in choosing to use platform.io, assuming it isn't also capable of running arduino-cli/arduino-builder.

To the extent possible, you can also just arrange your function definitions to appear before their usages.  The definition will serve as a declaration.  If you don't have any mutually recursive functions this is generally something you can do within the context of a single file.


text:
Can you create an array for functions?
Let's say I want to create 10 functions, named Function1, Function2 until 10. Each function is used if a certain variable is equal to its number. Rather than using individual functions, I was wondering if its possible to use some sort of array concept for functions when it comes to naming? I tried reading about it and saw pointers but I honestly didn't understand what I saw about it because I'm not that adept to the language yet.

Of course this is possible, you can make an array of any data type you like. And a function pointer is a data type. But this is a broad issue, so you rather get a good book or online resource on C++ and start to learn.

Here's an example of how to do it:
jump_table.ino
int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5,
                               func6, func7, func8, func9, func10 };

void setup() {
}

void loop() {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

All functions stored in the array must have the same signature.  This simply means that they must return the same type (e.g. int) and have the same arguments (a single int in the example above).

You can do the same with static class methods (but not instance methods).  For example you could use MyClass::myStaticMethod in the array above but not MyClass::myInstanceMethod nor instance.myInstanceMethod:
class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

There's a similar question over on stackoverflow.

Hi, is argument different from arg? But it seems like your code is correct.

@AndroidV11 The value of argument gets passed to the appropriate function where it available as arg (or foo in the class example).  BTW, based on your comment it sounds like you're pretty new to programming.  If that's the case I'd recommend learning more of the basics of C++ before you use this technique; it's fairly advanced and really only makes sense to use in specialized situations (e.g. remote procedure call handlers).

@AndroidV11 I just fixed a rather nasty typo in the code.  C++ uses zero-based array indices so to call the third function index needs to be 2, not 3.


text:
How can I break the loop if it hasn't finished in 10 seconds?
Currently I am using OneButton.h library to code  my push button project.
When I press button1, it will loop for 10sec and print TRIG, and after that it will break the loop.
However, now I want to program it where when I pressed button1, it will jump to void(singleclick) function, but right now, during the 4th seconds (anytime before 10th sec) , I pressed other button, thus Arduino will break the 10sec loop and run other function.
Thus, I need help how to make sure Arduino actively read other button and when pressed, it will break the current loop/function to other related functions.
#include <OneButton.h>

OneButton button1(2, true);
OneButton button2(3, true);
OneButton button3(4, true);
OneButton button4(5, true);

int led1=12;
int led2=11;
int led3=10;
int led4=9;

int flag;

unsigned long mode;

void setup()
{

  Serial.begin(9600);
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led3,OUTPUT);
  pinMode(led4,OUTPUT);

  button1.attachClick(singleclick1);
  button1.attachLongPressStop(longclick);

  button2.attachClick(singleclick2);
  button3.attachClick(singleclick3);
  button4.attachClick(singleclick4);

   digitalWrite(led1,HIGH);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,HIGH);
   digitalWrite(led4,HIGH);

}

void loop()
{
  button1.tick();
  delay(20);

  button2.tick();
  delay(20);

  button3.tick();
  delay(20);

  button4.tick();
  delay(20);

  Serial.println("No button");

}

void singleclick1()
{
   mode=millis();

   flag=1;

   while(flag==1)
   {
     Serial.println("button1");
     digitalWrite(led1,HIGH);
     digitalWrite(led2,LOW);
     digitalWrite(led3,LOW);
     digitalWrite(led4,LOW);

     if(millis()-mode>5000)
     {
      Serial.println("TRIG");
      flag=0;

      button2.tick();
      delay(20);

      button3.tick();
      delay(20);

      button4.tick();
      delay(20);

      return;
     }
   }
}

void singleclick2()
{
   Serial.println("button2");
   digitalWrite(led1,LOW);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,LOW);
   digitalWrite(led4,LOW);
}

You could run a timer that toggles a flag after 10 seconds. Then the loop would check that flag on each iteration.

This is just a rough, incomplete and untested code.
void singleclick1() { startTimer = true; }      // this only sets a flag

void singleclick2() { runTimer   = false;}      // this only clears a flag

void loop() {

   button1.tick();
   button2.tick();

   if startTimer {                 // this occurs once every click 1

      mode        = millis();
      runTimer    = true;
      startTimer  = false;         // run this block only once every click 1

      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW );
      digitalWrite(led3, LOW );
      digitalWrite(led4, LOW );
   }

   unsigned long currentMillis = millis();

   if (currentMillis - mode > 10000) {
      runTimer = false;                      // 10 second timer expired
   }

   if (runTimer) {

      Serial.println("TRIG");

   }
   else {
      // optional stuff to do
   }
}

Thank you so much!


text:
send command to Slave and receive response over I2c
so I have an Arduino mega as the master and an attiny84 as the slave
the master can send a command S to the slave and the slave should respond with TRUE so here is my code:
master:
bool GetOnline(){
      Serial.println("Sending Status Command ");

      if(Address != NULL){
        String res;
        Wire.beginTransmission(Address);
        Wire.write('S');
        Wire.endTransmission();
        Wire.requestFrom(Address, 4);
        while (Wire.available())
        {
          char inChr = Wire.read();
          res += inChr;
        }

        Serial.print("Device responce: ");
        Serial.println(res);
        if(res == "TRUE"){
          return true;
        } else {
          return false;
        }
      }
    }

Slave:
void normalReceive(uint8_t howMany) {
  while(Wire.available())//if wire is avaliable
  {
    char command=Wire.read();//state read the recived command from master, high or low
    MySerial.print("recived: "); MySerial.println(command);
    switch(command){
      case 'A': digitalWrite(LEDReboot,LOW);
       break;
      case 'B': digitalWrite(LEDReboot,HIGH);
       break;
      case 'S': Wire.write("TRUE");
       break;
      case 'R': resetFunc();
       break;
      default: MySerial.print("recived: "); MySerial.println(command);
       break;
    }
  }
}

void normalRequest() {
  MySerial.println("Request SN");
  Wire.write(sn);
  }

now the issue is when I request from the slave it returns the SN rather than the expected TRUE
I am very new to I2C so any help is appreciated.

Are you really using the Wire library on the Attiny84? That chips doesn't have dedicated I2C hardware, so I thought that the Wire library doesn't work with it.

@chrisl well TinyWireS didn't work with AttinyCore and in the examples, from AttinyCore they used Wire

Ah, it seems, that the Wire library as provided by the ATtinyCore incorporates the other libraries and chooses automatically based on the given hardware.

What is sn in the function normalRequest? I can't see it being declared anywhere in the code. Does the Attiny84 recieve the S, can you see it in the Serial Monitor?

@PythonSchlange sn is a char array. the serial number of the Attiny84 device and yes the Attiny84 does receive the S Command

If I understand correctly you're saying that you're getting a value returned over I2C that only the function normalRequest() can return, without ever calling normalRequest()?


text:
I have three pushbuttons where only one can be pushed at a time and want to set a variable for this. How?
Basically I have three push buttons that correspond to pins 1 to 3 and want to set an efficient code that sets a certain variable into the index whose digitalRead is equal to one. Let us assume that only one button can be pressed at a time.
void loop()
    {
    if(digitalRead(1) == 1)
        {
        Variable = 1;
        }
    if(digitalRead(2) == 1)
        {
        Variable = 2;
        }
    if(digitalRead(3) == 1)
        {
        Variable = 3;
        }
    }

Is there are more efficient way to do this, like for example using other loops?
I can't wrap around my head with doing this concept using the other loops such as for, do while, while and switch because the nature of the idea feels so unconventional for their uses.

"Efficient" is very subjective. Using a for loop will decrease code size, but increase execution time. Using discrete ifs like that will increase code size but decrease execution time.

What exactly is the role of the Variable in your code? Can the values be arbitrary, or are they pin numbers, or are they indices of the pressed buttons? You could use a for loop to go other an array of pins and assign the variable with the element of a second array. I'm not sure, what the actual goal is here, so it is difficult to suggest a good way.

And how is this question different from your previous one?

Okay it was pretty much the same, this one can be closed since you gave a good answer to the original question.

If you can only have one button pushed at a time, you can only end up with at most one of the if statements evaluate to true. In your code, you check button 2 and 3, even if button 1 is pressed. Your code can be a bit faster if you do this:
if(digitalRead(1) == 1)
{
  Variable = 1;
}
else if(digitalRead(2) == 1)
{
  Variable = 2;
}
else if(digitalRead(3) == 1)
{
  Variable = 3;
}