text:
Serial communication with HC-05 - Arduino UNO
I am new to the site and this is my first question. I'm going to try to describe my issue the best I can.
I got the following code for my project, which consists basically of getting a car to have 2 driving modes, automatic and manual.
As far as I can tell, I got it all working except it's not. I got an HC-05 connected to my L293D motor shield (attached to an Arduino UNO), as well as 2 DC motors, an ultrasonic sensor HC-SR04 and a LED. The circuit part is not the problem, I’ve managed to connect it all and it's working (I tested the obstacle avoiding part by itself, before adding the mode selection code, so I know the motors and sensor do their job). I should also mention that I’m sending the information through the BT from an app I made in App Inventor. The app is working fine, and I do receive the correct data in the Serial Monitor.
What’s puzzling me is, why can’t I get to assign the Serial.read(); value to my response variable (resp)? I’m going to try to explain this a bit further.
In my serial monitor I get the intended chars from the app buttons, however, my “resp” variable doesn’t seem to be getting any value from Serial.read(); for some reason, because when it gets to the switch statement, even though the char is printed on the monitor, the cases don’t start. For instance, and I might be completely off here, once I get ‘1’ on the monitor I should also start getting the distance measurement printed in the monitor and it’s not.
For what I gather, I believe the issue is between the Serial.write() and the Serial.println()/.read();, since the serial.write() seems to be taking priority over all others, since setting these lines as comments don’t affect the writing in the monitor:
if(Serial.available()>0){
//resp = Serial.read();
//Serial.println(resp);

I’m out of ideas, so any help or guidance towards the right direction will be greatly appreciated.
//Incluir librerias para controlar motor shield y sensor ultrasonico.
#include <AFMotor.h>
#include <NewPing.h>
#include <SoftwareSerial.h>

//Definir constantes y variables.
#define TRIG_P A4
#define ECHO_P A5
#define MAX_DIST 300
#define MAX_Vel 200
int led = A0;
int speedSet;
int iteraciones = 5;
float distancia, duracion;
char resp;

//Inicializar objetos del sensor y motores.
NewPing sonar(TRIG_P, ECHO_P, MAX_DIST);
AF_DCMotor motorD(2);
AF_DCMotor motorI(1);
SoftwareSerial BTSerial(A1, A2); // RX | TX

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

void loop() {

  //Lee información del BT y la escribe en el monitor serial.
  if (BTSerial.available()){
    Serial.write(BTSerial.read());
    Serial.write('\n');
  }

  delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

  if(Serial.available()>0){
    resp = Serial.read();
    Serial.println(resp);

    switch(resp){

      case '1':

      delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

      Serial.print("Distancia: ");
      Serial.print(distancia);
      Serial.println(" cm");

      if(distancia!=0 && distancia<=20){
        digitalWrite(led,HIGH);
        ALTO();
        delay(100);
        REVERSA();
        delay(400);
        IZQUIERDA();
        delay(100);
      }else
        digitalWrite(led,LOW);
        ADELANTE();
      break;

      case '2':
      ALTO();

        switch(resp){

          case 'A':
            ADELANTE();
          break;
          case 'R':
            REVERSA();
          break;
          case 'I':
            IZQUIERDA();
          break;
          case 'D':
            DERECHA();
          break;
          case 'O':
            ALTO();
          break;
        }
        break;
       }
    }
 }

  // Inician metodos que definen las acciones del carro.

void ADELANTE(){
   motorD.run(FORWARD);
   motorI.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void REVERSA(){
   motorD.run(BACKWARD);
   motorI.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void DERECHA() {
   motorD.run(RELEASE);
   motorI.run(FORWARD);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void IZQUIERDA() {
   motorD.run(FORWARD);
   motorI.run(RELEASE);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void ALTO(){
   motorD.run(RELEASE);
   motorI.run(RELEASE);
  }

Here is an image of what I get on my serial monitor.

UPDATE:
As suggested by @chrisl, I'm now looking at it from a different approach.
I was sending the BT information to the serial monitor, when the idea in the first place is having the car run around without being connected to the PCat all.
So instead of sending the information to serial monitor and trying to take it from there, I simply assigned the value from BTSerial to my variable and it kinda works as intended now.
"Automatic mode" is working, my switch statement recognises the resp value and starts measuring and prints the distance. However, once I push '2', the first command activates and the motors stop but none of the other instructions work. I even changed my second switch statemate to ifs but that didn't help either.
Here's my new Serial output (9600 / Newline / COM5):
1
Distancia: 46.84 cm
Distancia: 154.74 cm
Distancia: 154.33 cm
Distancia: 154.68 cm
Distancia: 154.33 cm
Distancia: 155.70 cm
Distancia: 13.09 cm
Distancia: 12.74 cm
Distancia: 155.16 cm
Distancia: 155.77 cm
Distancia: 155.22 cm
Distancia: 154.81 cm
Distancia: 155.29 cm
Distancia: 155.22 cm
Distancia: 155.22 cm
2
A
R
I
@
D
O
1
Distancia: 155.43 cm
Distancia: 155.50 cm
Distancia: 155.57 cm
Distancia: 155.50 cm
Distancia: 155.09 cm
Distancia: 155.50 cm
Distancia: 155.09 cm
Distancia: 156.32 cm
Distancia: 155.57 cm
Distancia: 155.16 cm
Distancia: 155.09 cm
Distancia: 155.09 cm
Distancia: 155.50 cm
2

And my updated code:
//Incluir librerias para controlar motor shield y sensor ultrasonico.
#include <AFMotor.h>
#include <NewPing.h>
#include <SoftwareSerial.h>

//Definir constantes y variables.
#define TRIG_P A4
#define ECHO_P A5
#define MAX_DIST 300
#define MAX_Vel 200
int led = A0;
int speedSet;
int iteraciones = 5;
float distancia, duracion;
char resp;

//Inicializar objetos del sensor y motores.
NewPing sonar(TRIG_P, ECHO_P, MAX_DIST);
AF_DCMotor motorD(2);
AF_DCMotor motorI(1);
SoftwareSerial BTSerial(A1, A2); // RX | TX

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

void loop() {

  //Lee información del BT y la escribe en el monitor serial.
  if (BTSerial.available()){
    resp = BTSerial.read();
    Serial.println(resp);
  }

//  if(Serial.available()>0){
//    resp = Serial.read();
//    Serial.println(resp);

    switch(resp){

      case '1':

      delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

      Serial.print("Distancia: ");
      Serial.print(distancia);
      Serial.println(" cm");

      if(distancia!=0 && distancia<=20){
        digitalWrite(led,HIGH);
        ALTO();
        delay(100);
        REVERSA();
        delay(400);
        IZQUIERDA();
        delay(100);
      }else
        digitalWrite(led,LOW);
        ADELANTE();
      break;

      case '2':
      ALTO();

       if(resp == 'A'){
         ADELANTE();
       } else if (resp == 'R'){
         REVERSA();
       } else if (resp == 'I'){
         IZQUIERDA();
       } else if (resp == 'D'){
         DERECHA();
       } else if (resp == 'O'){
         ALTO();
       }
      break;
       }
    }
// }

  // Inician metodos que definen las acciones del carro.

void ADELANTE(){
   motorD.run(FORWARD);
   motorI.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void REVERSA(){
   motorD.run(BACKWARD);
   motorI.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void DERECHA() {
   motorD.run(RELEASE);
   motorI.run(FORWARD);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void IZQUIERDA() {
   motorD.run(FORWARD);
   motorI.run(RELEASE);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void ALTO(){
   motorD.run(RELEASE);
   motorI.run(RELEASE);
  }

I guess the main problem is, that you write your commands from the bluetooth app, but the HC-05 module is connected to BTSerial. Here you are reading from it and forwarding the data to Serial (serial monitor on your PC):
if (BTSerial.available()){
    Serial.write(BTSerial.read());
    Serial.write('\n');
}

You are not doing anything else with the bluetooth serial data, so you cannot change the resp variable over bluetooth. Instead you are doing this with Serial (not BTSerial). But as long, as you don't type the commands into the serial monitor, that code will never run. Thus the distance code will never be executed.
If you want to control the program from the bluetoooth app, you need to actually work with the data from the right serial interface.

Btw: Your serial monitor is configured for a newline as line ending character. Your Serial code does not discard these, so you might get undesired behavior there, when resp becomes \n.

About your new problem: This problem actually existed also with the old code, but you couldn't see it, because the you were reading from the wrong serial interface. Try to read this (compressed) snipped of your (old) code:
switch(resp){
   case '1':
       ...
       break;
   case '2':
       switch(resp){
           case 'A':
               ...

With the first switch statement you are checking the value of resp. If it is '2', you will enter the second case. In there you are again checking the value of resp for the values 'A', ... . But when you already know, that resp is equal to '2', how can it ever be equal to 'A' or one of the other subcommands, since you don't change resp in between. Thus the code inside the second switch statement is unreachable.
What to do now? I guess you want the first switch statement to handle the modes and the second one to handle the move commands, while in second mode. For that you need to restructure your code, in the best case to an FSM (Finite State Machine). I already once wrote a good descriptions of how an FSM works in my answer to this question.
Introduce a state variable, which gets used in the first switch statement, and a command variable, that gets used in the second one. I would suggest a structure like this:
enum State {AUTOMATIC_MODE, MANUAL_MODE};

State state = AUTOMATIC_MODE;
char command = 0;

void loop(){
    if(BTSerial.available()){
        resp = BTSerial.read();
        Serial.println(resp);
        switch(resp){
            case '1':
                state = AUTOMATIC_MODE;
                break;
            case '2':
                state = MANUAL_MODE;
                break;
            case 'A':
            case 'R':
            case 'I':
            case 'D':
            case 'O':
                command = resp;
                break;
        }
    }

    switch(state){
        case AUTOMATIC_MODE:
            ...
            break;
        case MANUAL_MODE:
            switch(command){
                case 'A':
                    ...
            }
            break;
    }
}

Here the serial input will be put into the state or command variable, depending, on what exactly was send. The part with the main code comes after that. Depending on the state, the corresponding code is executed. When in manual mode, the code will look at the command variable to check, which function to execute.

I see, perhaps I got it all wrong then, because the intention is to have the car run around without being connected to the pc, and therefore not conected to the serial monitor in the first place. So, should I simply asign the recieved information to my resp variable without writing it to the serial monitor at all?

With Serial (UART) writing and reading is  independent. You can see the bluetooth data on the serial monitor, if you write it to Serial, but that doesn't mean, that you can read it back from there. You can only read from Serial, what is actively send by the serial monitor. You read the important command data from BTSerial, so you should use that data for assigning to resp. You can still additionally send the data to the serial monitor for debugging purpose.

@GenaroBasoria I added a part to my answer about the problem with the manual mode


text:
New to Arduino and I have a WIP code for a class. ERROR with LEDs working?
(EDIT) My goal with this code is to use two potentiometers, pot0 and pot1 respectively, to control 8 leds. Pot0 controls which sequence the leds are running (1, 2, or 3) and pot1 controls which LEDs within each sequence are active. Currently, I am having a problem because I am running Sequence 1 (the first if statement) to my arduino, but I can't seem to make the LEDs light up when being called out by the potentiometer. The only LED that works is LED 0, and that's only if both potentiometers were in the proper positions when the code begins running.
int pot0 = 0;
int pot1 = 1;
int led[] = {7, 6, 5, 4, 3, 2, 1, 0};

void setup() {

for (int i = 0; i < led; i++){
  pinMode(led, OUTPUT)
;}
}
void loop() {
  int potread = analogRead(pot0);
  int val = analogRead(pot1);
  int potR = map(val, 0, 1023, 0, 7);

if (potread <= 341) {
  for (int i; i == potR;)
  digitalWrite(led[i], HIGH);

}

else if (potread <= 682) {

}
else {

}
}

I actually figured out what was causing the error, but I am now having an issue with what the actual code is doing, so I will update my post

separate the pot reading and the LED lighting ... instead of if (potread <= 341) { digitalWrite(led, HIGH);} use a flag variable .... do something like this if (potread <= 341) level1 = true; ... further down in the program if ( level1 ) digitalWrite(led, HIGH); ... that way your code will be less convoluted

I have updated my post. I would appreciate if you would take another look at it and give me some advice.

you have a malformed for loop

For this, you should be using map(). Instead of int potR = val % 8; try int potR = map(val, [minimum pot value], [maximum pot value], 0, 7). Also, I'm pretty sure you don't need the for loop if all you're doing is led[i]. In that case, you could use led[potR].

I updated my post, thank you for your help. I fixed the For loop issue, and it will now compile to my board. Please read the post for the new issues

This will likely work, but right now I can't really see if it will because I can't get my arduino to stop only lighting leds 6 and 7, and I'm not sure what the issue is. When I run the code, it starts with both of them at a high brightness, and after maybe a second it dims the brightness on LED 6. Is there something in my code that might cause this?

Try some simple troubleshooting like doing a for loop through your LED array.

I managed to figure it out (My arduino was running an old sketch for some reason). Everything seems to be in order except that my pot1 doesn't seem to be affecting which LEDs are lit up, it's only lighting up LED 0 even if I turn pot1 all the way to max.

I spoke to someone the other night while working on this who was able to help me, and have since resolved all of my issues. Thank you to everyone who helped me fix the issues that I was having!
For those interested in how my final code came out ->
int pot0 = 0;
int pot1 = 1;
int led[] = {7, 6, 5, 4, 3, 2, 8, 9};
const int DelayPeriod = 100;

void setup() {
pinMode(pot0, INPUT);
pinMode(pot1, INPUT);
for (int i = 0; i < led; i++){
  pinMode(led, OUTPUT)
;}
}
void loop() {
  int potread = analogRead(pot0);
  int val = analogRead(pot1);
  int potR = map(val, 0, 1023, 0, 7);
if (potread <= 341) {
  for (int i = 0; i <= led; i++){
    if (i == potR){
      digitalWrite(led[i], HIGH);
    }
    else {
      digitalWrite(led[i], LOW);
    }
  }

}
else if (potread <= 682) {
  for (int i = 0; i <= led; i++){
    if (i <= potR){
      digitalWrite(led[i], HIGH);
    }
    else {
      digitalWrite(led[i], LOW);
    }
  }

}
else {
  for (int i = 0; i <= led; i++){
    if ((i <= (potR + 1)) && (i >= (potR - 1))){
      digitalWrite(led[i], HIGH);
    }
    else {
      digitalWrite(led[i], LOW);
    }
  }
}
}

source: Stack Exchange

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

sort: votes


text:
Burn bootloader finishes with "avrdude done. Thank you." but bootloader didn't actually get flashed
I've built a a stripped down version of the Arduino Nano that has some peripherals removed and three connectors for analog sensors I want to use. I'm trying to burn the Arduino Nano bootloader onto this custom board using the sparkFun AVR Pocket Programmer and from the Arduino IDE console it seems to say that it was burned successfully. But when I plug the board back into the computer it still shows up as a COM port instead of an Arduino device. This is the output I get in the console after I press burn bootloader with "USBtinyISP" selected as programmer and Arduino Nano as the board.

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

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbtiny
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x1781-0x0c9f
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, https://learn.adafruit.com/usbtinyisp
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% -0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: load data flash data from input file C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: input file C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

The burning is pretty much over instantly and you can see the reading and writing take 0.00s, it should be closer to a minute rather than an instantly. It's faster than uploading a simple sketch to the Arduino. When I unplug the programmer and plug the device back via USB, it just shows up as a COM port instead of "Arduino Nano" - which doesn't allow me to program it via the Arduino IDE.
What is very strange to me is that I can program the device over the command line. If I follow the AVR Pock Programmer instructions "Using AVRDUDE via Command Line" and use a hex file generated from the Arduino IDE, the code uploads fine and runs fine. I wrote a sketch that prints the ADC values over the command line and after flashing via command line it's running as expected.
I've tried to upload the Arduino booatloader via command line as shown in this tutorial under "Uploading Code - Hard Way" and this time it takes over 43 seconds to write to flash and 30 seconds to read from flash so I thought it worked. However when I plug it back in, it STILL just comes up on my computer and the Arduino IDE as COM9.
This is the output I get when trying to flash the bootloader via command line:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot
λ avrdude -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m

avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

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

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

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as 5
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xD6"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD6:
avrdude: load data hfuse data from input file 0xD6:
avrdude: input file 0xD6 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot
λ avrdude -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328.hex -U lock:w:0x0F:m

avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

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

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

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "optiboot_atmega328.hex"
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 43.63s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328.hex:
avrdude: load data flash data from input file optiboot_atmega328.hex:
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 30.69s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

I've reviewed my schematic multiple times, comparing it to the actual Nano schematic but I can't see anything that would cause it to fail - it's almost identical ! I've built two of these boards and they behave the same exact same way. Schematic shown below.

your post does not make sense ... you are using an FTDI chip, which presents itself as a serial port

But the FR32RL is the same chip that the Arduino Nano uses - and the Nano shows up as an Arduino Device when it is plugged in. You can program it directly using the Arduino IDE.

Would I need to do that to use the Arduino IDE for flashing ?

I'm not quite clear on what that means - could you explain a little more?

old PCs had a DB25 parallel port used for printers ... also called Centronics port ... it had 8 bi-directional data pins and some handshaking pins ... LPT1 is usually the name for the parallel port as opposed to serial port COM1

Why does it find the device and read/write to flash if the port is wrong ?

I do not know ... it is just that lpt1 leaped out when i looked at the printout

The short flash time makes sense if you think about the size of the bootloader. It should not occupy all of the 32KB! Commonly it is much smaller than the typical sketch. If avrdude tells you that 32KB are flashed, then most of the contents should be 0xFF - please check this. Since 0xFF is the erased byte value of a flash memory, there is nothing to do for these bytes, resulting in very short flash times.

try a manual reset while avrdude attempts to upload

The Arduino 'device' is identified by the USB device code of the USB to TTL Serial on Arduino or by core code in case of MCU with native USB. The USB ids are written to the USB chip in factory or are part of the firmware/core and they are listed in boards.txt file so that the IDE then knows what Arduino is attached. If you use a common FTDI it doesn't have this Arduino vid and pid codes, which identifies the device as Arduino.
Note: I think you asked a different question then your real problem is, because you assumed that the name of the port not showing Arduino is the reason why the upload doesn't work. It is so called X->Y problem. You have a problem X but asked about problem Y. I answered the question asked.

I see. Does that mean it won't be possible to flash this board via the Arduino IDE ? I'll just need to keep flashing through the command line ?

@VanGo, if you have the right COM port in Tools menu, you can upload. it doesn't have to say 'Arduino'

I've tried this, but I end up with a bunch of these messages "avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00" and then it fails. I've tried pressing the reset while it's uploading but no difference...

There are different bootloaders implementing different protocols. You might need to select another protocol/bootloader.

@VanGo, that is a different question

@Juraj thanks for the pointers. It was indeed another issue - I had the Arduino Tx/Rx plugged into another device. When I tried uploading code via the Arduino IDE with the Rx/Tx pins unplugged from the other device - it let me upload successfully even though the device still just shows up as a COM port. Thanks !

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


text:
Solution needed for sending HTTPs requests from multiple Arduino units in the field
I'm using the Arduino Wifi Nina Library to connect an Arduino Uno Wifi Rev2 to wifi and then using the Arduino HTTP Client library to make HTTP post calls to the internet. It is working. However when I switch from HTTP to HTTPs (ie: switching the port to 443 from 80) the code below fails. I understand This is because I don't have a cert on the Arduino. I need to purchase/obtain a cert and download it to the Arduino.
I need to find a solution to this problem that meets the following constraints I have:

I will only be sending https requests to one URL:
https://api.mailgun.net
The amount of memory storage available on Arduinos is severely constrained
I plan to deploy this Arduino into the field. After I deploy it, I will no longer be able to physically access it to manually update any expired certificates. But the Arduino unit must be able to send HTTPs requests to https://api.mailgun.net in perpetuity.
I plan to deploy not just this Arduino unit, but a fleet of similarly functioning Arduino units with the same functionality. And I need to keep the costs of any certificate(s) to an absolute minimum.

    #include <WiFiNINA.h>
    #include <ArduinoHttpClient.h>

    #define REMOTE_SERVER_DOMAIN "api.mailgun.net"
    #define REMOTE_SERVER_PORT 443
    #define MAILGUN_USER "my-user"
    #define MAILGUN_PASSWORD "my-secret"

    bool sendEmailViaHTTPS()
    {
        WiFiClient wifiClient;
        HttpClient httpClient = HttpClient(wifiClient, REMOTE_SERVER_DOMAIN, REMOTE_SERVER_PORT);
        httpClient.beginRequest();
        httpClient.post("/v3/sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org/messages");
        httpClient.sendHeader("Content-Type", "application/x-www-form-urlencoded");
        httpClient.sendBasicAuth(MAILGUN_USER, MAILGUN_PASSWORD);
        String postData = String("from=Mailgun%20Sandbox%20%3Cpostmaster%40sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org%3E&to=Me%20%3Cmyemail%40gmail.com%3E&subject=Hello%20World1&text=Hello%20World2");
        httpClient.sendHeader("Content-Length", postData.length());
        httpClient.beginBody();
        httpClient.print(postData);
        httpClient.endRequest();
        int statusCode = httpClient.responseStatusCode();
        String response = httpClient.responseBody();
        Serial.print("Status code: ");
        Serial.println(statusCode);
        Serial.print("Response: ");
        Serial.println(response);
        return statusCode == 200;
    }

What is the best solution to enabling my Arduino to send HTTPs requests as stated above with the least cost and friction?

You don't need to buy any certificates. Only the server (mailgun.net) requires to buy a certificate, not the client (your Arduino). To validate if the certificate the server is using is valid you need to store the Root CA certificate(s). A lot of Arduino projects skip this step, as it's to complicated, or the Arduino doesn't have enough memory/processing power to handle this.

For secure TCP connection with WiFiNINA library use WiFiSSLClient instead of WiFiClient.
The Arduino firmware in the NINA ESP32 module has certificates of well known CA authorities so the server's certificate verification should work. If necessary, you can add public keys of server certificates to NINA.

Worked! I had to add the root cert corresponding to the server I wanted to access. Thank you!


text:
ADXL345 gives wiring error in SPI mode
I get the following output from serial monitor when trying to use the ADXL345 with Arduino Uno in SPI mode (I2C mode works fine):
CA
Ooops, no ADXL345 detected ... Check your wiring!

See photos for wiring. I have tried it with another breakout board, and that produces the same results.
Interestingly this tutorial says the breakout should work in SPI mode, but it's only illustrated for I2C.
https://learn.adafruit.com/adxl345-digital-accelerometer?view=all#assembly-and-wiring
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(13,12,11,9);
//Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified();

//Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(clock,miso,mosi,cs,sensorID);
void displaySensorDetails(void)
{
  sensor_t sensor;
  accel.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" m/s^2");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" m/s^2");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" m/s^2");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void displayDataRate(void)
{
  Serial.print  ("Data Rate:    ");

  switch(accel.getDataRate())
  {
    case ADXL345_DATARATE_3200_HZ:
      Serial.print  ("3200 ");
      break;
    case ADXL345_DATARATE_1600_HZ:
      Serial.print  ("1600 ");
      break;
    case ADXL345_DATARATE_800_HZ:
      Serial.print  ("800 ");
      break;
    case ADXL345_DATARATE_400_HZ:
      Serial.print  ("400 ");
      break;
    case ADXL345_DATARATE_200_HZ:
      Serial.print  ("200 ");
      break;
    case ADXL345_DATARATE_100_HZ:
      Serial.print  ("100 ");
      break;
    case ADXL345_DATARATE_50_HZ:
      Serial.print  ("50 ");
      break;
    case ADXL345_DATARATE_25_HZ:
      Serial.print  ("25 ");
      break;
    case ADXL345_DATARATE_12_5_HZ:
      Serial.print  ("12.5 ");
      break;
    case ADXL345_DATARATE_6_25HZ:
      Serial.print  ("6.25 ");
      break;
    case ADXL345_DATARATE_3_13_HZ:
      Serial.print  ("3.13 ");
      break;
    case ADXL345_DATARATE_1_56_HZ:
      Serial.print  ("1.56 ");
      break;
    case ADXL345_DATARATE_0_78_HZ:
      Serial.print  ("0.78 ");
      break;
    case ADXL345_DATARATE_0_39_HZ:
      Serial.print  ("0.39 ");
      break;
    case ADXL345_DATARATE_0_20_HZ:
      Serial.print  ("0.20 ");
      break;
    case ADXL345_DATARATE_0_10_HZ:
      Serial.print  ("0.10 ");
      break;
    default:
      Serial.print  ("???? ");
      break;
  }
  Serial.println(" Hz");
}

void displayRange(void)
{
  Serial.print  ("Range:         +/- ");

  switch(accel.getRange())
  {
    case ADXL345_RANGE_16_G:
      Serial.print  ("16 ");
      break;
    case ADXL345_RANGE_8_G:
      Serial.print  ("8 ");
      break;
    case ADXL345_RANGE_4_G:
      Serial.print  ("4 ");
      break;
    case ADXL345_RANGE_2_G:
      Serial.print  ("2 ");
      break;
    default:
      Serial.print  ("?? ");
      break;
  }
  Serial.println(" g");
}

void setup(void)
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif
  Serial.begin(9600);
  Serial.println("Accelerometer Test"); Serial.println("");
  pinMode(9,OUTPUT);
  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }

  /* Set the range to whatever is appropriate for your project */
  accel.setRange(ADXL345_RANGE_16_G);
  // displaySetRange(ADXL345_RANGE_8_G);
  // displaySetRange(ADXL345_RANGE_4_G);
  // displaySetRange(ADXL345_RANGE_2_G);

  /* Display some basic information on this sensor */
  displaySensorDetails();

  /* Display additional settings (outside the scope of sensor_t) */
  displayDataRate();
  displayRange();
  Serial.println("");
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  accel.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print("  ");Serial.println("m/s^2 ");
//  delay(500);
}

I got it to work using the Sparkfun library in stead of the Adafruit library, and by inserting a couple of delay(100) statements in the setup (without them the output was continuously -13365, -13365, -13365). I still don't fully understand why the delay statements would be necessary in the first place though.
/*  *********************************************
 *  SparkFun_ADXL345_Example
 *  Triple Axis Accelerometer Breakout - ADXL345
 *  Hook Up Guide Example
 *
 *  Utilizing Sparkfun's ADXL345 Library
 *  Bildr ADXL345 source file modified to support
 *  both I2C and SPI Communication
 *
 *  E.Robert @ SparkFun Electronics
 *  Created: Jul 13, 2016
 *  Updated: Sep 06, 2016
 *
 *  Development Environment Specifics:
 *  Arduino 1.6.11
 *
 *  Hardware Specifications:
 *  SparkFun ADXL345
 *  Arduino Uno
 *  *********************************************/

#include <SparkFun_ADXL345.h>         // SparkFun ADXL345 Library

/*********** COMMUNICATION SELECTION ***********/
/*    Comment Out The One You Are Not Using    */
ADXL345 adxl = ADXL345(9);           // USE FOR SPI COMMUNICATION, ADXL345(CS_PIN);
//ADXL345 adxl = ADXL345();             // USE FOR I2C COMMUNICATION

/****************** INTERRUPT ******************/
/*      Uncomment If Attaching Interrupt       */
//int interruptPin = 2;                 // Setup pin 2 to be the interrupt pin (for most Arduino Boards)

/******************** SETUP ********************/
/*          Configure ADXL345 Settings         */
void setup(){

  Serial.begin(9600);                 // Start the serial terminal
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();

  adxl.powerOn();                     // Power on the ADXL345
  delay(100);
  adxl.setRangeSetting(16);           // Give the range settings
                                      // Accepted values are 2g, 4g, 8g or 16g
                                      // Higher Values = Wider Measurement Range
                                      // Lower Values = Greater Sensitivity
  delay(100);
  adxl.setSpiBit(0);                  // Configure the device to be in 4 wire SPI mode when set to '0' or 3 wire SPI mode when set to 1
                                      // Default: Set to 1
                                      // SPI pins on the ATMega328: 11, 12 and 13 as reference in SPI Library
  delay(100);
//  Set SPI mode to that matching ADXL345 (I guess this would be in here by default? )

  adxl.setActivityXYZ(1, 0, 0);       // Set to activate movement detection in the axes "adxl.setActivityXYZ(X, Y, Z);" (1 == ON, 0 == OFF)
  adxl.setActivityThreshold(75);      // 62.5mg per increment   // Set activity   // Inactivity thresholds (0-255)

  adxl.setInactivityXYZ(1, 0, 0);     // Set to detect inactivity in all the axes "adxl.setInactivityXYZ(X, Y, Z);" (1 == ON, 0 == OFF)
  adxl.setInactivityThreshold(75);    // 62.5mg per increment   // Set inactivity // Inactivity thresholds (0-255)
  adxl.setTimeInactivity(10);         // How many seconds of no activity is inactive?

  adxl.setTapDetectionOnXYZ(0, 0, 1); // Detect taps in the directions turned ON "adxl.setTapDetectionOnX(X, Y, Z);" (1 == ON, 0 == OFF)

  // Set values for what is considered a TAP and what is a DOUBLE TAP (0-255)
  adxl.setTapThreshold(50);           // 62.5 mg per increment
  adxl.setTapDuration(15);            // 625 μs per increment
  adxl.setDoubleTapLatency(80);       // 1.25 ms per increment
  adxl.setDoubleTapWindow(200);       // 1.25 ms per increment

  // Set values for what is considered FREE FALL (0-255)
  adxl.setFreeFallThreshold(7);       // (5 - 9) recommended - 62.5mg per increment
  adxl.setFreeFallDuration(30);       // (20 - 70) recommended - 5ms per increment

  // Setting all interupts to take place on INT1 pin
  //adxl.setImportantInterruptMapping(1, 1, 1, 1, 1);     // Sets "adxl.setEveryInterruptMapping(single tap, double tap, free fall, activity, inactivity);"
                                                        // Accepts only 1 or 2 values for pins INT1 and INT2. This chooses the pin on the ADXL345 to use for Interrupts.
                                                        // This library may have a problem using INT2 pin. Default to INT1 pin.

  // Turn on Interrupts for each mode (1 == ON, 0 == OFF)
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);

//attachInterrupt(digitalPinToInterrupt(interruptPin), ADXL_ISR, RISING);   // Attach Interrupt

}

/****************** MAIN CODE ******************/
/*     Accelerometer Readings and Interrupt    */
void loop(){

  // Accelerometer Readings
  int x,y,z;
  adxl.readAccel(&x, &y, &z);         // Read the accelerometer values and store them in variables declared above x,y,z

  // Output Results to Serial
  /* UNCOMMENT TO VIEW X Y Z ACCELEROMETER VALUES */
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z);

//  ADXL_ISR();
  // You may also choose to avoid using interrupts and simply run the functions within ADXL_ISR();
  //  and place it within the loop instead.
  // This may come in handy when it doesn't matter when the action occurs.

}

/********************* ISR *********************/
/* Look for Interrupts and Triggered Action    */
void ADXL_ISR() {

  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();

  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");
    //add code here to do when free fall is sensed
  }

  // Inactivity
  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
     //add code here to do when inactivity is sensed
  }

  // Activity
  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***");
     //add code here to do when activity is sensed
  }

  // Double Tap Detection
  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
     //add code here to do when a 2X tap is sensed
  }

  // Tap Detection
  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
     //add code here to do when a tap is sensed
  }
}


text:
Script works on Mega but not Uno
I'm struggling to get a script to work on an Uno that I've had working on a Mega.The script was made for an Uno and I've used all the same pin numbers as the orignal (Original project).
I just bought the Uno and something doesnt seem right about how Arduino's IDE responds to it as opposed to the Mega (see the pics I've attached). They are both copies but Arduino seems to retreive more info on the Mega.
I've installed the driver from wch.hn and it appears in the device manager as being installed okay. The 'Blink' example seems to work fine on the Uno but stops when I disconnect the USB and use external power.
The script uploads to the Uno fine and recognises the controller as per the error message section but the wheels of the model don't turn. The script I've used was made for an Uno and as I said the script worked fine on the Mega this morning and I've changed it back since not being able to get it to work and it's still okay on the Mega.
Any help is much appreciated.
P/S - I should add that the RX LED is blinking every half second when I'm using external power.
#include <PS2X_lib.h>       //for v1.6 PS2 Library

#define PS2_DAT        12
#define PS2_CMD        11
#define PS2_SEL        10
#define PS2_CLK        9

#define leftm1     3
#define leftm2     4
#define rightm1    5
#define rightm2    6
#define left_EN    2
#define right_EN   7

  //analog values read from PS2 joysticks
int LX = 0;
int LY = 0;
int RX = 0;
int RY = 0;

//#define pressures   true
#define pressures   false
#define rumble      true
//#define rumble      false

PS2X ps2x; // create PS2 Controller Class

int error = 0;
byte type = 0;
byte vibrate = 0;

void setup() {

  Serial.begin(9600);

  pinMode(leftm1,  OUTPUT);
  pinMode(leftm2,  OUTPUT);
  pinMode(rightm1, OUTPUT);
  pinMode(rightm2, OUTPUT);
  pinMode(left_EN, OUTPUT);
  pinMode(right_EN, OUTPUT);

  digitalWrite(left_EN, LOW);
  digitalWrite(right_EN, LOW);

  delay(300);  //added delay to give wireless ps2 module some time to startup, before configuring it

  //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
  error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);

  if (error == 0) {
    Serial.print("Found Controller, configured successful ");
  }
  else if (error == 1)
    Serial.print("No controller found, check wiring. ");

  else if (error == 2)
    Serial.print("Controller found but not accepting commands. ");

  else if (error == 3)
    Serial.print("Controller refusing to enter Pressures mode, may not support it. ");
}

void loop() {
  ps2x.read_gamepad(false, vibrate); //read controller and set large motor to spin at 'vibrate' speed

  if (ps2x.Button(PSB_L1))
  {
    LY = ps2x.Analog(PSS_LY);                     //receive values from p22 joystick
    LX = ps2x.Analog(PSS_LX);
  }
  if (ps2x.Button(PSB_R1))
  {
    RY = ps2x.Analog(PSS_RY);
    RX = ps2x.Analog(PSS_RX);
  }

  if (LY > 200 || RY > 200)                       //check if the joystick pushed up side
  {
    REV();
  }
  if (LY < 100 || RY < 100)
  {
    forward();
  }
  if (LX < 100 || RX < 100)
  {
    left();
  }
  if (LX > 200 || RX > 200)
  {
    right();
  }
  if(LX == 128 && LY == 128 && RX == 128 && RY == 128)
  {
    waithere();
  }

LY = LX = 128;         //return to default vlaues
RY = RX = 128;         //return to default values
}

void forward()
{
  //Serial.print("forward");
  digitalWrite(left_EN, HIGH);
  digitalWrite(right_EN, HIGH);

  digitalWrite(leftm1, HIGH);
  digitalWrite(leftm2, LOW);
  digitalWrite(rightm1, HIGH);
  digitalWrite(rightm2, LOW);

}
void REV()
{
  //Serial.print("rev");
  digitalWrite(left_EN, HIGH);
  digitalWrite(right_EN, HIGH);

  digitalWrite(leftm1, LOW);
  digitalWrite(leftm2, HIGH);
  digitalWrite(rightm1, LOW);
  digitalWrite(rightm2, HIGH);
}
void left()
{
  //Serial.print("left");
  digitalWrite(left_EN, LOW);
  digitalWrite(right_EN, HIGH);

  digitalWrite(leftm1, LOW);
  digitalWrite(leftm2, LOW);
  digitalWrite(rightm1, HIGH);
  digitalWrite(rightm2, LOW);

}
void right()
{
  //Serial.print("right");
  digitalWrite(left_EN, HIGH);
  digitalWrite(right_EN, LOW);

  digitalWrite(rightm1, LOW);
  digitalWrite(rightm2, LOW);
  digitalWrite(leftm1, HIGH);
  digitalWrite(leftm2, LOW);
}
void waithere()
{
  //Serial.print("stop");
  digitalWrite(left_EN, LOW);
  digitalWrite(right_EN, LOW);
  digitalWrite(rightm1, LOW);
  digitalWrite(rightm2, LOW);
  digitalWrite(leftm1, LOW);
  digitalWrite(leftm2, LOW);
}

Are you program the Arduino through ISP (since you are using "ArduinoISP" as programmer option)? When I want to  upload via USB, I use the option "AVRISP mkII".

Also: When you try the blink sketch with external power supply (which doesn't work as of your description), how exactly are you connecting what type of power supply with which voltage?

@chrisl, for USB upload the selected programmer is ignored

@chrisl I'm uploading the blink example via usb then unplugging the cable and leaving the board powered by 4x AA batterys (6v).

How are you supplying the voltage to the board.  6V is too much to go into the 5V pin and not quite enough for VIN.


text:
Arduino Timer 1 Library manipulate Timer value
I'm using Timer1 library for generation of pulse.
But in my code, at some places i need to change the timer values.
Can anyone suggest the ways to do it.
In below code in place of 370000, I need to change the value after getting some inputs in conditional loops.
Ex. if (x==1) Timer value should be 370000 else 185000.
#include <TimerOne.h>

int count = 0;
int LED = 13;

void setup() {
 pinMode(LED, OUTPUT);
 Timer1.initialize(370000);
 Serial.begin(9600);
}

void loop() {
 Serial.print("Count Value: ");
 Serial.println(count++);
}

When you look into TimerOne.h, which is the header file for the TimerOne library, you can see at line 55 the method
void setPeriod(unsigned long microseconds)

which can be used to set the period of the timer at any time in your program. The method TimerOne.initialize() also calls this method to set the timer period.

Just use a variable...
unsigned long val = 0;

void setup(){
  if(something){
    val = 370000;
  }
  else {
    val = 185000;
  }
  Timer1.initialize(val);
}

Calling the initialize method multiple times feels wrong. In some libraries this can have some weird side effects. In the case of Timer1 if you call detachInterrupt and then change the period using initialize, instead of setPeriod, the interrupts will start again, and you ISR will get called. Though I admit that's a bit of an edge case.

Who said to call it multiple times?  It's only called once in setup.  Is there more to this than was in the question?  I thought we were coming up with a way to alter the 370000 number.  Question should be more specific.  If this answer is a downvote for answering exactly what the question said then I'm downvoting the question for being vague.

@Delta_G - You can call the initialize function twice per minute with different values if you like. I've built a clock that does just that, and has been running for over a year with no issues. https://arduino.stackexchange.com/a/68627/37523 +1 for your answer.

I still say the question didn't ask to do it over and over.  The question just asked how to do it once in setup.

@Delta_G - The question is not the greatest, but it does say ...at some places i need to change the timer values. I still like your answer :)

While it does say that, I figured that was a language issue as the code posted shows nothing in loop and only shows the one Timer1 function being called.  If that's not the code the OP needed help with then why is that the code that was posted?

@Delta_G that's right I didn't post the full code here. Let me clarify. I'm blinking LED/Bulbs with arduino. On time of that will be 370ms and same off time. After current/load sensing, if load is in range, I need to start timer with 370000. If not, timer should count 185000. So here is my question, that once I initialize timer to 370000 in setup, is it possible to change that value later in code. Because i badly need to change the timer value. Hope this clarify the things and doesn't sound stupid enough to down vote the question.

@Delta_G Also let me add something to question that, once I start blinking LED/Bulbs with timer say 370ms. After starting timer, in ON timer I'm checking load/current by polling. If load not appropriate, I've to change value from 370000 to 185000 while timer is still going on with 370000.

This would all be simpler without the timer library if that's all you need to do.  Just use millis for the timing.


text:
Data in two 8 bit shift registers won't change
I'm trying to output 16 bits of data to two 8 bit shift registers (74HC595), which drive a 8x8 led matrix. There is a problem with the way the code outputs data to the registers, its like no data is even shifted onto them. The first 8 bits handle the rows and the last 8 bits handle the columns.
I have already written this code in Arduino, but I am trying to re-write in it C (we have to learn AVR programming in C for college). The Arduino version works fine, so I know the circuit is correct. I'm using Atmel Studio.
For example, I replaced all the digitalWrite(clockPin, HIGH)'s with PORTD = PORTD | (1<<clockPin).
But I can't get anything to output with my code.
For refreshing the led display the variable refreshFlag is used. For updating the game state (which hasn't been implemented yet) the variable updateFlag is used.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>

//portd 2(latch), 4(clock), 7(data). Same as pins on arduino board
#define latchPin 2
#define clockPin 4
#define dataPin 7

//functions
void init_ports(void);
void init_USART(void);
void init_timer0(void);
void sendmsg (char *s);
void drawData(uint8_t myData[]);
void shiftOut(uint8_t myDataOut);

unsigned char qcntr = 0,sndcntr = 0;   /*indexes into the queue*/
unsigned char queue[100];       /*character queue*/

int updateTimeCount;
int updateDelay;
int updateFlag; // Flag for updating game state
int refreshFlag;// Flag for refreshing display

uint8_t data[] = {0b00000001,
                  0b01111110,
                  0b11000110,
                  0b01001010,
                  0b01010010,
                  0b11100010,
                  0b01111110,
                  0b01000010};

int main(void) {
    //init_USART();// Serial for debugging purposes
    init_ports();
    init_timer0();
    clearData();
    newBlock();

    sei();

    PORTB = 0; //PortB for debugging
    updateTimeCount = 0;
    updateDelay = 13; // Game updates every 13* 16ms = 208ms.
    updateFlag = 0;
    refreshFlag = 0; // Display updates every 16ms

    while (1) {

        if(updateFlag) { //updates game state
            PORTB = (1<<5); //debugging led
            updateFlag = 0;
        }

        if(refreshFlag) { //refreshes display
            drawData(data); //output data array

            refreshFlag = 0;
        }
    }
    return 0;
}

void drawData(uint8_t myData[]) { //takes data and outputs it
  for (uint8_t j = 0; j <= 7; j++) {

    //ground latchPin and hold low for as long as you are transmitting
    PORTD = PORTD & ~(1<<latchPin); //latch pin low

    //shift data into regs

    shiftOut(~(1<<j)); //grounds row. For example 10111111 means 6th row is on

    shiftOut(myData[j]);  //outputs column data.

    //return the latch pin high to signal chip that it
    //no longer needs to listen for information
    PORTD = PORTD | (1<<latchPin); //latch pin high
  }
}

void shiftOut(uint8_t myDataOut) { //shifts 8 bits out to register

  // This shifts 8 bits out LSB first,
  //on the rising edge of the clock,
  //clock idles low

//internal function setup
  uint8_t i=0;
  int pinState;

//prepare shift register for bit shifting
  PORTD = PORTD & ~((1<<dataPin) | (1<<clockPin)); //clock & data pin low

  //for each bit in the myDataOut
  for (i=0; i<=7; i++)  {

    PORTD = PORTD & ~(1<<clockPin); //clock low

    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // %11010100 it would the code compares it to %01000000
    // and proceeds to set pinState to 1.
    if ( myDataOut & (1<<i) ) {
      pinState= 1;
    }
    else {
      pinState= 0;
    }

    //Sets the pin to HIGH or LOW depending on pinState
    PORTD = PORTD | (pinState<<dataPin);

    //register shifts bits on upstroke of clock pin
    PORTD = PORTD | (1<<clockPin);

    //zero the data pin after shift to prevent bleed through
    PORTD = PORTD & ~(1<<dataPin);
  }

  //stop shifting
  PORTD = PORTD & ~(1<<clockPin);
}

void sendmsg (char *s) { //create serial message
    qcntr = 0;    /*preset indices*/
    sndcntr = 1;  /*set to one because first character already sent*/

    queue[qcntr++] = 0x0d;   /*put CRLF into the queue first*/
    queue[qcntr++] = 0x0a;
    while (*s)
    queue[qcntr++] = *s++;   /*put characters into queue*/

    UDR0 = queue[0];  /*send first character to start process*/
}

/*this interrupt occurs whenever the */
/*USART has completed sending a character*/

ISR(USART_TX_vect) {
    /*send next character and increment index*/
    if (qcntr != sndcntr)
        UDR0 = queue[sndcntr++];
}

ISR(TIMER0_OVF_vect) { //overflow every 16ms
    TCNT0 = 6; // 256-250 = 6
    ++updateTimeCount;
    if(updateTimeCount >= updateDelay) { //after 208ms, update game state
        updateFlag = 1; // Call for updating game
        updateTimeCount = 0;

    }

    refreshFlag = 1; // Call for updating screen
}

void init_ports() {
    DDRD = (1<<latchPin) | (1<<clockPin) | (1<<dataPin); //enable pins
    PORTD = 0; //set all pins low
    DDRB = (1<<5); //enable the built-in led for debugging
    PORTB = 0; //set all pins low
}
void init_USART() {
    UCSR0B = (1<<TXEN0) | (1<<TXCIE0); //enable transmitter and tx interrupt
    UBRR0 = 103; //baud 9600
}
void init_timer0() {
    TCCR0A = 0;
    TIMSK0 = (1<<TOIE0);    // enable interrupt
    TCCR0B = (5<<CS00); // prescalar 1024. 16Mhz/1024 = 15625Hz = 0.064ms
    // For refresh rate of 62.5Hz, 16ms /0.064ms = 250
    TCNT0 = 6; // 256-250 = 6
}

I really can't tell what the problem is and I don't what to look up either. I think the problem is in the functions drawData and shiftOut, because that's where all the data is shifted out. I tested the timer0 interrupt by flipping the built-in led and that seems to be working fine.
Are the ports flipping too fast for the shift regs to receive the data? Is there a semantic error somewhere? Can you see any problems. Thanks for any help!

Re “I think the problem is”: better be sure. Break down the problem into smaller chunks and test them one by one. Writing the full program before you start testing is a bad idea.

@EdgarBonet I did some testing with LED's and the refreshFlag isn't getting set to one when the timer0 overflows. Which means drawData() is never called. But I have tested the updateFlag, and it does work. So I tried calling the drawData() when the updateFlag is one but still nothing. So I'm not really sure where the problem is.

this may help ...... https://electronics.stackexchange.com/questions/183299/atmega-16-timer0-with-interrupt ...... http://www.avr-asm-tutorial.net/avr_en/micro_beginner/6_Led_Int/6_Led_Int.html

As Edgar Bonet said: start with code that's as simple as possible for testing / debugging basic functionality. First get that to work before moving on to more complex code. See if your problem can be reproduced with (much) simpler code.

why do you use direct register access and not digitalWrite and the Arduino shiftOut function?

@juraj I'm using C not Arduino code

You might want to add some delays in you shiftout function. You set the data-pin to the correct value, set the clock pin to high, and then set the data-pin back to LOW. All right after each other. I'd start adding some leds to the data and clock pins, just to see if there is any data being transmitted. With these high speed signals I connect the 5V to see if the signal is ever LOW, or connect the other way around to GND to see if the signal is ever HIGH. With current high brightness led, ever a very short signal is still  visible, though might only appear as a sight glow.

Start with volatile modifier for variables accessed in both ISR and main program.

@KIIV Yes, thank you! That solved the problem with the refreshFlag. I guess the compiler interpreted it as if(0) . However there is still no output on the display, so I'm still trying to debug that.

@Gerben So there is a slight glow on the data and clock pins without any added delay, so there is definitely data being transmitted. However I just as I'm writing this I think I have found the problem.

@KIIV @Gerben @Edgar_Bonet @StarCat @jsotola @Juraj There was no data being sent because a function clearData() was called before the while loop. I feel so stupid! However there was a problem with the refreshFlag which @KIIV noticed! Thanks for your help!

Thanks to everyone who commented on my question, I was able to solve the problem with your help!
The first issue was that the compiler interpreted the if(refreshFlag) {...} as if(0) {...} so the data would have never been outputted to the display.
This happens is because the compiler doesn't see that the refreshFlag can be set to 1 in the timer0 interrupt service routine. From its perspective I have written an if statement that never runs.
As @KIIV pointed out, if the volatile keyword is used when declaring refreshFlag, this tells the compiler that this variable can change at any time.
The second and more embarrassing issue was that I forgot to remove a call to clearData() function which clears the data array. So I was just outputting nothing to the registers!
This is what the fixed variables and main should look like:
int updateTimeCount;
int updateDelay;
volatile int updateFlag; // Flag for updating game state
volatile int refreshFlag;// Flag for refreshing display

uint8_t data[] = {0b00000001,
                  0b01111110,
                  0b11000110,
                  0b01001010,
                  0b01010010,
                  0b11100010,
                  0b01111110,
                  0b01000010};

int main(void) {
    //init_USART();// Serial for debugging purposes
    init_ports();
    init_timer0();

    sei();

    PORTB = 0; //PortB for debugging
    updateTimeCount = 0;
    updateDelay = 13; // Game updates every 13* 16ms = 208ms.
    updateFlag = 0;
    refreshFlag = 0; // Display updates every 16ms

    while (1) {

        if(updateFlag) { //updates game state
            PORTB = (1<<5); //debugging led
            updateFlag = 0;
        }

        if(refreshFlag) { //refreshes display
            drawData(data); //output data array

            refreshFlag = 0;
        }
    }
    return 0;
}

It's OK to accept your own answer as the solution to the problem. You'll have to wait 48 hours before you can accept it.


text:
Alternatives to read mp3 without using an sdcard as source for the files?
I am making a project that plays several sounds using a DFPlayer Mini mp3 player and a micro sd card. The size of the sounds I normally play is less than 20 MB, so a lot of space in the sd card is unused. I was wondering if there is an alternative to use an SD card to store the mp3 files, and if there is, what would be the best approach to switch to use this alternative.
Cheers!

what please is the problem you try to solve? you want a only 200 MB storage and not more?

why is the SD card free space an important factor?

The SD free space is not really important, but I wanted to know if there was a "better" alternative or a cheaper one.

The problem of all alternatives I can think of is a commercial one:Its more expensive than to waste space. So if you look up your facvorite online dealer you will quickly find out that e.g. buying the cheapest 1GB SD card costs double than buying the cheapest 32GB card (6$). So the more space you waste the cheaper. Get an used 512MB or 1GB card (cost in my country around 1$) and be happy with the space reserve.
Of course if saving space is a topic and not money get 20 x 1MB eeprom I2C boards (20*3$ from china), solder the hardware (you'll need some more parts to manage the board addresses), get a power source, write a library for managing the memory and after spending around 100$ and a lot of time you saved up to around 15.98 GB of free space but not the environment.

I see, so it's always cheaper to use SDs to save mp3s than to store  in EEPROMs, right? As you mention commercial uses, how do they solve this issue in commercial products? Do they also use SD cards?

Depends - falsh rom in industrial use is cheap (see usb sticks) but there are no payable solutions for mkers. But if you have an old usb stick start making your own project. As an SD card is basiclly a flash rom (the biggest parts are the contacts) you could also desolder the sd-slot and directly solder the card onto the DF-Mini, but whats the difference? SD cards have no moving parts so its normally shock proof (and can be secured with tape) if thats an issue. So you see there is a difference between maker and industry ;-)

Thanks for the great explanation and examples @Codebreaker007 !


text:
Which Protocol to use to control WiFi (esp 32) enabled Led Light
I am developing a Wifi based Led light (for learning purpose). I have little knowledge about web server, clients, Web protocols. I will be using ESP32 as Controller cum WiFi module.
There are two ways to control Led light over WiFi.
Locally
Remotely // as of now am focusing on locally
Android/iOS app will be handling all the control part (Flutter app)
Which protocols can I use to control Led light, locally?
will set up multiple esp32 at that time its hard to control the device both devices will have different ip
Kindly help!
if anyone give good example it would be helpful

Personally I use MQTT and a Mosquitto server running on the internet. Then I simply use MQTTPanel on my phone.

google esp32 wifi led

There are many ways to do this. I recommend Adafruit IO which has an MQTT backend and a nice configurable dashboard frontend, and is free for small environments. I’ve recently moved to my own Mosquitto MQTT broker and Node Red frontend.

the thing is its not possible to place a server for controlling an led in local network , i want to use my app as a server to contollig all the devices connected to my router

You can use your ESP as a server by the following code and then put your DigitalWrite(1, HIGH) line in the code like the following:
 String line = client.readStringUntil('\r');
 Serial.print(line);
if(line=="ledon")
{
DigitalWrite(1, HIGH);
}

and at this point you just can call the following link to turn the led on
http://192.168.*.**/ledon

or whatever the starting of your ipv4 is.


text:
How to bridge free-running multichannel adc to serial?
I want to get meteo sensors values, and turn avr based 16mhz arduino (i have mega, but that seems not matter alot vs uno) into multichannel oscilloscope.
Task details. Desired data rate is 8(uno) to 16(mega) analog channels divide by 4 to 16 reads per second. Extra adc "speed capacity" must be spent on summing up on arduino. Prescale is almost not needed. Each reading is 32bit, lsb is always zeroed. Plus there is 0xffffffff between packets (easiest binary proto, i really hate those ascii low-quality slow shit, but this is personal and offtopic). So now you got the setup and purpose, lest get down to my simple sketch
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// packet starts after indicator and goes before next such indicator.
const long packetStartIndicator = 0xFFFFFFFFl;

// values are fixed point ints 0..65534 (with LSB always cleared)
// such descision is made because least significant bit almast always == noise;
// also its just easist pck splitting scheme
const long packetValueMask = 0xFFFFFFFEl;

const int numPins = 8;

long sensorValues[numPins+1];

// TODO: configure this from host via serial (inside setup)
int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8};
//int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15};

// 1 reading is 10 bit. we can make 2^6==64 readings and sum them up (to top up to full 16 bit, to make kind of digital expoure)
// upd. 1 reading is counted as 16 bit, for host convenience (no matter or real adc)
// sum up like 256 of 16-bit readings to get 24bit value. send as 32bit long variable.
const int adcOrder = 10;
const int readingsOrder = 8;
const int targetOrder = 24;
const int numReadings = 1 << readingsOrder; //64;

void setup() {
  // TODO: reset ADCSRA, or it would not work. Also: get clue on free run mode
// sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
// for Arduino Uno ADC clock is 16 MHz and a conversion takes 13 clock cycles
//ADCSRA |= (1 << ADPS2) | (1 << ADPS0);    // 32 prescaler for 38.5 KHz
//ADCSRA |= (1 << ADPS2);                     // 16 prescaler for 76.9 KHz
//ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz

//sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 32 for 38.5 KHz
//sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); cbi(ADCSRA,ADPS0); // set prescale to 16 for 76.9 KHz
//cbi(ADCSRA,ADPS2); sbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 8 for 153.8 KHz

  sensorValues[numPins] = packetStartIndicator;
  //analogReadResolution(10);
  Serial.begin(115200, SERIAL_8N1);
  //Serial.begin(250000, SERIAL_8N1);
  //Serial.begin(500000, SERIAL_8N1);
}

void zero_values() {
  int i;
  for(i=0; i<numPins; i++) {
    sensorValues[i] = 0;
  }
}

void clear_lsb() {
  int i;
  int shiftOrder = targetOrder - (adcOrder + readingsOrder);
  for(i=0; i<numPins; i++) {
    sensorValues[i] <<= shiftOrder;
    sensorValues[i] &= packetValueMask;
  }
}

void serial_write() {
  Serial.write( (uint8_t*)sensorValues, sizeof(long)*(numPins+1) );
}

void loop() {
  int i, j;
  zero_values();
  for(i=0; i<numPins; i++) {
    for (j=0;j<numReadings; j++) {
      sensorValues[i] += analogRead(pinNumbers[i]);
    }
  }
  clear_lsb();
  serial_write();
}

I am weak with reading avr datasheets and lacking of knowledge on internals. My question is tied with my desire to switch it to freerun mode. I really dislike analogRead, seems it was written by real juniors, and is real slow. AFAIK free run mode is something when you have interrupt function running when conversion is done. I feel (dont know but really feel) that working with serial inside interrupt is a bad idea. How, in somple words, this can be reworked to event-based ISR with sending over serial when you would encounter inside your interrupt following: currentPin == lastPin && currentReading == numReading means you have summed up desired bumber of readings, and this is last pin, so its time to post it over serial.

Can you elucidate for us which parts of analogRead you feel are "junior".

In the Arduino environment sending data over serial inside an interrupt is seldom a good idea. That's not to say it's impossible, you just need to keep certain caveats in mind.
The chief of which is that when the TX buffer fills up everything will lock up.
So with that in mind, if you can guarantee that all your data from one interrupt will be completely sent out before the next interrupt occurs then sending serial in an interrupt can be used.
And yes, analogRead(), like many things in the Arduino API, is not fast. It's not intended to be fast. It is, though, intended to be simple.  And also like many things in the Arduino API it's easy to out-grow them.
I am not familiar with the Atmel ADC registers (preferring PIC32 to AVR any day...) but looking at the datasheet I can see a few points of interest.

First set the trigger source to "free running" (ADCSRB):

Bit 2:0 – ADTS2:0: ADC Auto Trigger Source

If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect. A conversion will be triggered by the rising edge of
  the selected Interrupt Flag. Note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching
  to Free Running mode (ADTS[2:0]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set.

Then set it to use the trigger source for starting conversions (ADCSRA):

Bit 5 – ADATE: ADC Auto Trigger Enable

When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive
  edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in
  ADCSRB.

And enable interrupts (ADCSRA):

Bit 3 – ADIE: ADC Interrupt Enable

When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt is activated

Alternatively you could set it to use a timer for the trigger source so you have finer control over when a conversion is performed. That will help you to ensure that all of the previous data set has been sent over serial before the next interrupt occurs.

"if you can guarantee that all your data from one interrupt will be completely sent out before the next interrupt occurs" I can just gurantee that for 11500 baud/s == 359.375 longs/second. I can send each long when it's adc is fired, and i need to swotch to another send accumulated A0->send A1->..->send A7->send 0xffffffff->send A0 So ITS BEST and most lightweight, if i could send inside interrupt.

So i can fire 39.93 of those (8+1)xlong readings per seconds. I just need 4 to 16 times per second. So it's guranteed that serial bus is free 30% to 90% of time to send whatever I want. I cant gurantee implementation, and I dont know it, and.. (I dont want to know it, i want just to use it efficiently) So I asked how to fire something from inside ISR without breaking arduino to hell..

The serial code is pretty efficient. There's a TX circular buffer and the sending from that buffer is all interrupt driven. write() blocks if there is no room in the buffer, and if that happens in an interrupt then you're screwed. As long as you make sure that can't happen (less than 64 bytes written between each ADC interrupt that writes data to serial) then you'll be fine.

So ARE you making me sure that writing send.serial.tx from some isr is just straightforward and fine enough? (if i gurantee that data send rate is low enoughh? (to wat degree should it be fine? 0.9 bandwith == fine? 0.3 == fine? or wat? how fast must i send to be fine and not dig into datashit? i dont want to, i just know that its right away and i go with it!))

If it will work i'll accept. Here is just prattical impl question to theoretical knowers, so to what degree is it guranteed to send serial from isr, or should i make some timer, sync and another loop shitcode? (felt like not. i send serial from interrupt, no need for any other kind of loop, pretty straight tast!) Also if this is a loopless ADC solution, could you please post to arduino beginners, what should they post in their main? sleep? why? could you post some code plxz!?

If you have nothing to do in loop() then do nothing in loop(). You don't need to do anything special, just leave it empty.  There is a slight delay between each byte sending as the ISR retrieves and queues the next byte, so at 115200 baud you can send maybe 11000 bytes per second. If you're sending 8 bytes then 1375 sendings is your absolute limit. But you want to give yourself a bit of leeway to be safe. So running no more than 1000 samples per second would be about right.

Does atmega has some kind of sleep operation? In a regular pc if you "do nothing in a loop" it consumes 100% core and wastes power. its far more complex and you have to give os sheduler a hint to put core to "sleep until interrupt happens". Is here something like this?

@xakepp35 It does have "sleep" modes, but they are for a different purpose. There is no concept of "do nothing". It always does something, unless the chip is put to sleep, where nothing (or very little) happens until some external stimulus wakes it up.


text:
ESP 8266 reverse digitalWrite behaviour on which pins?
I am using a device with an ESP 8266 microcontroller. I have discovered that setting LED_BUILTIN to HIGH turns the built-in LED off and  setting LED_BUILTIN to LOW turns the built-in LED on. This seems to be because the microcontroller can sink more current than it can source.
Before I start using this microcontroller, I would like to know which other pins have this reverse behaviour. I've looked up datasheets for the ESP 8266 but I don't see how to discern this information. I would simply write a sketch to test, but I'm not sure what I might damage, and I'm not sure how to determine when an output pin is in the high-impedance state anyway.
On the ESP 8266, how to know which pins are HIGH -> 0v and which pins are HIGH -> 5v? Are the HIGH -> 0v pins necessarily LOW -> 5v? Where is this documented?

the pin is not reversed. the attached circuit with the LED reverses the signal.

@Juraj: Thank you. The pin is not reversed, but the behaviour (on this board and others) is. Are you saying that the issue is board-specific, so won't be relevant to all ESP 8266 boards? This is the board that I'm using.

it is a Wemos D1 R1

the behaviour is not reversed ... a HIGH does not necessarily mean LED on ... a HIGH only means high output

Yes, or at lease a clone of one. I see mention on forums of people having this issue with other ESP 8266 boards as well.

@jsotola: So if the output is HIGH, that would make the LED turn off only if the LED were pulled down to 0v on the same side as the pin, and connected to 5v on the other side (i.e. the pin is on the LED cathode). Is that how this board is wired? Where is that documented?

'people' have issues with everything

@dotancohen, the schematic diagram is the documentation

@dotancohen, it is unclear what this means LED were pulled down to 0v on the same side as the pin .... how do you turn on a LED? ... one side is connected to HIGH and the other side is connected to ______

@dotancohen, you are overthinking this ... an LED lights up if there is a voltage difference across the LED, and that is all (assuming correct orientation) ... the LED will not light if both leads are grounded, or if both leads are conected to 5 V, or if both leads are connected to a 1000 V

@jsotola Where is that schematic diagram? I found the WeMos D1 page on the Raspberry pie wiki but the diagram is impossible to read. The Official WeMos site doesn't seem to have such a diagram, mentioning only the D1 Mini.

I see on the D1 Mini schematic that the LED is in fact connected with the cathode to the ESP 8266, but without the pulldown resistor that I suspected.

The esp8266 must have a pull-up on io 2 for boot configuration. The Wemos D1 boards put the LED in series with the pull-up resistor on io 2. This creates the 'reversed' LED behavior.

The large D1s are retired and it is hard to find a good and readable schematics. The cut out is from D1 mini schematics.

I see now, thank you! I take it that this is common, but not necessary, on ESP 8266 boards.

I've found the explanation of the boot configuration and it is lucky that I did, as it is non-trivial and very important. Thank you Juraj!


text:
Use of "static" with "RTClib"
I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".
Here you can see an excerpt from the example provided for the pcf8523 real-time clock:
#include "RTClib.h"

RTC_PCF8523 rtc;

void setup () {

  while (!Serial) {
    delay(1);  // for Leonardo/Micro/Zero
  }

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.initialized()) {
    Serial.println("RTC is NOT running!");
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    /*
    do some more stuff
    */
}

In the beginning of loop() they wrote:
DateTime now = rtc.now();

Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right?
This appears inefficient to me.
I thought about rewriting it this way:
static DateTime now;    // static declaration, executed only once
now = rtc.now();    // assignment to "now" every time loop() starts over

In this case "new" should be allocated on the stack like a global variable, right?
I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.
Link to the library:
https://github.com/adafruit/RTClib
Thank you! :-)
EDIT: For some reason I CAN NOT declare DateTime now; in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.

Re “I CAN NOT declare DateTime now; in global scope”: what happens if you do so? A compilation error? Incorrect run-time behavior? I tried and it compiles just fine (but I have no RTC for testing).

Actually, DateTime now = rtc.now() might have utilize "copy elision", so it gets constructed directly into now variable and therefore it's faster than your approach (as you effectively blocked this possibility - so it has to create temporary object and copy it into now variable).

@EdgarBonet , it compiles and uploads but will not execute Setup(). Setup() starts with Serial.begin(9600); Serial.println("test"); Blinking the builtin-led doesn't work either.

@KIIV , concerning C++ I've read many times that separate declaration and definition can be part of "good practice". Your explanation was never mentioned but seems to make sense! Maybe it makes no difference with (aggressive) compiler optimization?

@blackdaw I'm pretty sure it's about declaration and definition of Class methods, not variables. And non rules/myths: Don't insist that all declarations shoudl be at the top of function and two rules Don't introduce a variable (or constant) before you need to use it

@KIIV You are right. I picked up many misconceptions through "beginner guides". The one you linked is a very helpful guide, thank you!

You wrote:

DateTime now = rtc.now();

Thus, with every iteration of loop() "now" gets defined anew (on the
  heap?!), right?

No. Local variables like this are usually allocated on the stack,
although the compiler may keep them in CPU registers if that helps
optimization.

static DateTime now;    // static declaration, executed only once

In this case "new" should be allocated on the stack like a global
  variable, right?

No. It is allocated statically, in the .bss section, like uninitialized
global variables.

I want to use "static" to increase overall performance by reducing
  work for the processor

Not sure it will make much difference. Static allocation may save you a
few CPU instructions compared to stack allocation (the instructions that
move the stack pointer). On the other hand, it will cost you a few
instructions compared to register allocation (the instructions to access
the RAM).

avoiding heap fragmentation

Stack allocation does not use the heap, and the stack never fragments.

Does this make sense or will it cause more problems than it solves?

If you really care about sub-microsecond differences in the execution
time, you should either look and the disassembly of the program, or do
some benchmarking. Otherwise just write whatever makes more sense from
the point of view of the program's logic: does the variable need to keep
its value across calls to loop()? If the answer is “no”, do not use
static.

You don't need to use the static keyword.
The cleanest solution is to define DateTime outside of the loop function:
DateTime now;

This will allocate the memory, and call the constructor of the class DateTime initializing it.
In case you would need a basic variable (like an int), you should initialize it, like:
int now = 0;

When you use it in setup or loop you use the created instance (without the class name to declare it):
void loop() {
   ...
   now = rtc.now();
}

Also, find a better name for now, because the variable is the same as the rtc's function now.
Update
after your comment, it cannot be used as a global variable:
I didn't try it myself, but I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point. Actually, it's quite bad practice.
Anyway, one way to circumvent and stick as much to what I wrote above, is to use a pointer instead:
RTC_PCF8523* rtc = NULL;

Than you create an empty pointer, without calling the constructor. You will do this at the end of setup:
void setup() {
   ...
   rtc = new RTC_PCF8523();
}

This will cause the variable to be put on the stack.
Than when using it, you call:
now = rtc->now();

Note you have to use the -> notation, as rtc is a pointer.

Forgot to mention: Defining it outside of loop() in the global scope DOES NOT WORK! Don't ask me why, I spent hours just to find this problem. This is the reason why I wanted to use static in the first place. Will edit my post. And concerning the name "now": It's just what they used in the example, I won't use it, but good point!

I updated my answer, just try if it helps.

Re “I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point”: I can't see anything wrong in this constructor.

@EdgarBonet ... me neither, I'm wondering why creating it as global variable wouldn't work.

See the comments above beneath @EdgarBonet 's solution. It compiles and uploads but doesn't execute.