text:
Restoring all fuse bits on AtMega328P-PU
I'm worked with Low Fuse bits in AVRDUDEPROG 3.3. Fuses was non-inverted. And by mistake I enabled SUT1 and SUT0, when SUT0 was enabled. And when I programmed avr,
it shows me error that avrdude.exe: initialization failed, rc=-1. I have read I can restore it with Avr Fuse Doctor, but I can't buy or make with pcb. Can I recover avr with:
#include <avr/io.h>

int main(void) {
    DDRB = 0xFF;
    while(1) {
        PORTB ^= 0xFF;
    }
}

and load it to another avr and connect it to broken avr?
Can I make doctor on breadboard or Can I do it with usbasp/isp?
Can I load a new bootloader in it?

It doesn't answer your question, but I foubd this online tool very useful when configuring fuses on avr-uCs: http://www.engbedded.com/fusecalc/

The following is from:
https://www.allaboutcircuits.com/projects/atmega328p-fuse-bits-and-an-external-crystal-oscillator/
"The two bits to be avoided unless you are absolutely certain you know what you are doing are bit7, the RSTDISBL (external reset disable) bit and bit 5, the SPIEN (Serial Peripheral Interface Enable) bit. Disabling either one is often the cause for "bricked" Atmel µCs; "leave them alone" is good advice."
According to the article SUT0 and SUT1 are clock start up time related bits. It doesn't seem as though it is necessary to use anything special to change them.
You will find the information at the website very usefu. I know I have.
The High Voltage (other names too) programmer you have mentioned should not be necessary if you only changed the SUT0 and SUT1 fuses.
HOWEVER, if you did change the SPIEN or RSTDISBL fuses, you should either get one of the special programmers or just purchase another 328P microprocessor.
If you search the internet for "AVR High Voltage programmer" you will find many ideas for how to build one.
This link :https://electronics.stackexchange.com/questions/33/arduino-as-avr-programmer/71
provides good information.

I have got 2 atmega328 and one uno. OK. But I didn't touch to Rest disable or Spi enable(I coiuldn't touch him because it was untouchable). I have set CKSEL to 0000 without invert. And set SUT1,0=11 non-invert and I loaded it to avr. With CKSEL=0000 It worked because I have got external Crystal with 16 MHZ. But when I loaded sut1,0=11 It shows me Error that avrdude cannot connect it.

And if you now, what High Voltage programmer is?

If it is 5V programmer?

No, it switches 12V in to reset the fuses.  Nick Gammon has a nice writeup on it here https://gammon.com.au/forum/?id=12898 with a schematic showing the setup needed to bring the Reset pin to 12V for the needed duration under software control.

Thanks but can I get 12V adapter and connect to atmega with resistor. And which contact I connect it?

Hey if I have got usbasp I can't do it?

Or I must take arduino uno and do it

ANd what I must do with my Uno for it

How can I get 12v from Uno?

Use the link CrossRoads posted, you should be able to 'engineer' a way to use it with what you have...


text:
Using Arduino Motor Shield
I'm looking to create a blind controller and have set up the hardware and software as I think it should be.
I had the software working fine using an IC motor driver, but as I am no great at soldering, I decided to use a motor shield. The software (below) now only turns the motor one way. I did amend the code to try to get the motor to turn the other way, and it did but only when the 'BlindOn' was during it's on.
Therefore, the hardware is set up correctly (pins D1 and D3) but there is some modification needed to this program; any help or advice greatly appreciated.
/**********************************************************************************
  * Code for controlling multiple devices connected to one NodeMCU using Amazon Echo
  *
  * Written by Sid for Sid's E Classroom
  *
  * https://www.youtube.com/c/SidsEClassroom
  *********************************************************************************/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "fauxmoESP.h"

#define WIFI_SSID "VM0718169" //change your Wifi name
#define WIFI_PASS "8kcgvwSFymjx" //Change your Wifi Password
#define SERIAL_BAUDRATE                 115200

fauxmoESP fauxmo;
//declare switching pins
//Change pins according to your NodeMCU pinouts
#define BlindOp D1
#define BlindCl D3
#define Test D2

volatile bool BlindOpOn = false;  // needs to be volatile since used in ISR
volatile bool BlindClOn = false;
volatile bool TestOn = false;

const unsigned long BlindOpOnTime = 5;    // seconds
const unsigned long BlindClOnTime = 5;     // seconds
const unsigned long TestOnTime = 5;

volatile unsigned long BlindOpStartTime;
volatile unsigned long BlindClStartTime;
volatile unsigned long TestStartTime;

// -----------------------------------------------------------------------------
// Wifi Setup
// -----------------------------------------------------------------------------

void wifiSetup() {

    // Set WIFI module to STA mode
    WiFi.mode(WIFI_STA);

    // Connect
    Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASS);

    // Wait
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(100);
    }
    Serial.println();

    // Connected!
    Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}
// -----------------------------------------------------------------------------
// Device Callback
// -----------------------------------------------------------------------------
void callback(uint8_t device_id, const char * device_name, bool state) {
  Serial.print("Device "); Serial.print(device_name);
  Serial.print(" state: ");
  if (state) {
    Serial.println("ON");
  } else {
    Serial.println("OFF");
  }
  //Switching action on detection of device name
  if ( (strcmp(device_name, "BlindOp") == 0) ) {
    // adjust the relay immediately!
    if (state) {
      digitalWrite(BlindOp, HIGH);
      BlindOpOn = true;
      BlindOpStartTime = millis();
    } else {
      digitalWrite(BlindOp, LOW);
      BlindOpOn = false;
    }
  }
  if ( (strcmp(device_name, "BlindCl") == 0) ) {
    // adjust the relay immediately!
    if (state) {
      digitalWrite(BlindCl, HIGH);
      BlindClOn = true;
      BlindClStartTime = millis();
    } else {
      digitalWrite(BlindCl, LOW);
      BlindClOn = false;
    }
  }
  if ( (strcmp(device_name, "Test") == 0) ) {
    // adjust the relay immediately!
    if (state) {
      digitalWrite(Test, HIGH);
      TestOn = true;
      TestStartTime = millis();
    } else {
      digitalWrite(Test, LOW);
      TestOn = false;
    }
  }
}

void setup() {
    //Initialize pins to Low on device start
    pinMode(BlindOp, OUTPUT);
    digitalWrite(BlindOp, LOW);
    pinMode(BlindCl, OUTPUT);
    digitalWrite(BlindCl, LOW);
    pinMode(Test, OUTPUT);
    digitalWrite(Test, LOW);

    // Init serial port and clean garbage
    Serial.begin(SERIAL_BAUDRATE);
    Serial.println("FauxMo demo sketch");
    Serial.println("After connection, ask Alexa/Echo to 'turn <devicename> on' or 'off'");

    // Wifi
    wifiSetup();

    // Device Names for Simulated Wemo switches
    fauxmo.addDevice("BlindOp");
    fauxmo.addDevice("BlindCl");
    fauxmo.addDevice("Test");
    fauxmo.onMessage(callback);
}

void loop() {
  unsigned long duration;

  fauxmo.handle();
  if ( BlindOpOn == true ) {
    duration = (millis() - BlindOpStartTime) / 1100;  // convert to seconds
    if ( duration >= BlindOpOnTime ) {
      digitalWrite(BlindOp, LOW);
      BlindOpOn = false;
    }
  }

  if ( BlindClOn == true ) {
    duration = (millis() - BlindClStartTime) / 1100;  // convert to seconds
    if ( duration >= BlindClOnTime ) {
      digitalWrite(BlindCl, LOW);
      BlindClOn = false;
    }
  }
  if ( TestOn == true ) {
    duration = (millis() - TestStartTime) / 1100;  // convert to seconds
    if ( duration >= TestOnTime ) {
      digitalWrite(Test, LOW);
      TestOn = false;
    }
  }

}

if ( BlindClOn == true ) - this strange convention is inexplicably popular in Arduino-related code...

you are using inconsistent programming style .... at one point you use if (state) and  at another point you use the redundant if ( BlindOpOn == true ) ..... the first style is the desirable one to use .....  use if ( BlindOpOn ) for the second one ...... the if ( BlindOpOn == true ) is redundant because it means if ( true == true ) when BlindOpOn is true

Thanks for the replies, I think the mismatch is due to various people editing the original, but this does work when using an IC motor driver...it will only opens when using the shield, and won't close.
Ideally, it would be one device which operates for a set time when turned on to open, and operates for a fixed time to close.
I need to learn more as I find the many }s used confusing, I've not much experience in programming in general

source: Stack Exchange

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

sort: votes


text:
Why my servo motor is always on?
Why my servo motor is always on?

#include <Servo.h>

Servo myservo;

int pos = 0;

void setup() {

pinMode(2, INPUT);
myservo.attach(9);

}

void loop() {

  if (digitalRead(2) == LOW) {

    for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(15);
    }

    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(15);
    }
  }
  else {
    myservo.write(0);
    delay(15);
  }
}

Provide a proper schematic and listing.

What do you mean by 'always on', is it always moving or always energized?

Voting to close because it is unclear what you're asking.  Please answer @JackCreasey's question, and maybe we can help.

@TimWescott Why not simply give the OP the opportunity to alter the question rather than hastily 'close' the question. Once closed it seems unlikely to get votes to open again even if it is altered. This is really just 'close' being used as a form of bullying.

@JackCreasey I did not invent Stackexchange, or its rules.  I just follow them.  As was pointed out to me when I asked just your question, closed questions do get reopened when they are fixed up.

Drastically simplify your setup.  Take the condition out of the code and just command a steady angle.  Then try again with a different one.  As you make your sketch more complicated again, add serial logging to explain what it thinks it is doing.  And of course explain precisely what is happening.

Closing would prevent a bunch of well-intended but poorly informed (no info from OP) answers to be written and made obsolete by updates on the question and context.

@JackCreasey it's always moving sorry i'm didn't know much

It looks like you need to enable the pull-up resistor on D2.  As written D2 is left floating and most likely is a low voltage relative to ground.  Enabling the pull up resistor will force the pin high until you flip the switch.

Arduino inputs have significant capacitance. So once the switch has been pressed the input will tend to stay low. Use either pinMode(pin, INPUT_PULLUP) or use digitalWrite(pin, HIGH) to turn on the pullup for a (pin) configured as INPUT.

it works!! thanks

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


text:
MXCHIP IoT DevKit too many initializers for 'unsigned char [0]
Question
Trying to call the Display draw API using the sample code for the azure logo bitmap sample code. I'm unable to reach a point where I can the API because breaks when constructing the bitmap char arrays in my BMPManager class. I'm also testing custom bitmaps using this pixelcraft tool.

In file included from /Users/gregorydegruy/Code/GitHub/_mr.u/mxchip/Main.ino:5:0:
  sketch/srcsrc/BMPManager.cpp:4:2371: error: too many initializers for 'unsigned char [0]' unsigned char AzureBMP[] = {0,0,0,0,0,0,0,0,0,0,0,0, . . .

Main
void loop()
{
    Screen.print("start prgm...");
    delay(1000);
    Screen.draw(0, 0, 128, 8, bitMapManager.get_azure_bitmap());
    delay(5000);
    Screen.draw(0, 0, 128, 8, bitMapManager.get_nintendo_bitmap());
}

BMPManager
class BMPManager
{
    private:
        unsigned char AzureBMP[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,192,192,224,240,56,12,192,240,224,192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,224,224,224,224,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,224,248,252,254,255,255,63,15,3,64,248,254,255,255,255,255,255,252,248,224,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,240,252,127,31,3,3,15,127,254,240,192,0,0,0,0,8,28,28,28,28,156,220,252,124,60,28,0,0,0,252,252,248,0,0,0,0,0,0,252,252,248,0,0,0,0,252,252,252,112,56,28,28,28,0,128,224,240,248,28,28,12,12,28,248,248,240,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,224,248,252,255,255,255,255,63,15,3,0,0,0,0,0,0,3,7,15,31,63,127,255,255,255,255,255,252,240,224,128,0,0,0,0,0,0,64,112,124,127,31,7,7,7,7,7,7,7,7,31,127,126,120,64,0,96,112,120,126,127,103,99,97,96,96,96,0,0,0,63,127,127,240,224,224,96,96,56,127,127,127,0,0,0,0,127,127,127,0,0,0,0,0,0,15,63,127,123,243,227,227,227,227,99,99,35,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,8,8,8,8,8,12,12,12,12,12,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        unsigned char NintendoSwitchBMP[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, 0xc0,0xc0,0xe0,0xe0,0xf0,0xf0,0xf8,0xf8, 0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8, 0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8, 0x00,0x00,0x00,0x00,0xf8,0xf8,0xf8,0xf8, 0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8,0xf8, 0xf8,0xf8,0xf0,0xf0,0xe0,0xe0,0xc0,0xc0, 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xc0,0xf0,0xfc,0xff,0xff, 0xff,0xff,0x7f,0x1f,0x0f,0x07,0x87,0x83, 0x83,0x81,0x81,0x81,0x81,0x81,0x01,0x01, 0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xfc,0xf0,0x80,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0x0f,0x00,0x00,0xfe,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x78, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xc0,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0x00,0x00,0x00,0x00,0x01,0x03,0x03, 0x07,0x07,0x07,0x07,0x03,0x03,0x01,0x00, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x7f,0x3f,0x3f, 0x3f,0x3f,0x7f,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xf1,0xc0,0x80,0x80,0x00, 0x00,0x80,0xc0,0xc0,0xf1,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xf0,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x01,0x0f,0x1f,0xff,0xff, 0xff,0xff,0xfe,0xf8,0xe0,0xe0,0xe0,0xc0, 0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0, 0x80,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0x00,0x00,0x00,0x01,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0x1f,0x0f,0x01,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01, 0x03,0x03,0x03,0x07,0x0f,0x0f,0x0f,0x1f, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x00,0x00,0x00,0x00,0x1f,0x1f,0x1f,0x1f, 0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f, 0x1f,0x0f,0x0f,0x0f,0x07,0x03,0x03,0x03, 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};

    public:
        BMPManager() {}
        unsigned char* get_azure_bitmap() {
            return AzureBMP;
        }
        unsigned char* get_nintendo_bitmap() {
            return NintendoSwitchBMP;
        }
};

In C++ you are not allowed to declare non-static member arrays with unspecified size (empty []). Supplying an in-class brace-or-equal (BoE) initializer for such non-static member array does not override this rule
struct S
{
  int a[] = { 1, 2, 3 }; // <-- ERROR: `[]` array declaration is not allowed here
};

If you really need these arrays as non-static members of the class, you will have to explicitly specify their size (which is 1024 in your case). Once you do that, you will also be able to BoE initializers for them right inside the class definition
class BMPManager
{
private:
  unsigned char AzureBMP[1024] = { /* whatever */ };
  unsigned char NintendoSwitchBMP[1024] = { /* whatever */ };
  ...
};

The = is optional.

However, the real question in this case is whether you really need these arrays as non-static (and non-const) members of the class. Do you really need independent instances of these arrays in each instance of BMPManager class? Are these arrays supposed to be modifiable?
If you really need independent instances of such arrays in each object, then you will have to do what's shown above.
But if you don't need independent arrays in each object (which would probably also imply that the arrays are not supposed to change) then the proper way to go about it would be to declare them as static members
class BMPManager
{
private:
  static unsigned char AzureBMP[];          // static const ?
  static unsigned char NintendoSwitchBMP[]; // static const ?
  ...
};

and then define them in one of the .cpp files as
unsigned char BMPManager::AzureBMP[] = { /* whatever */ };
unsigned char BMPManager::NintendoSwitchBMP[] = { /* whatever */ };

Note that in this case you will not be able to use BoE initializers directly in class definition. The initializers are supplied at the point of static member definition in .cpp file.
This can be done much more compactly in C++17, but I'd guess that you are using Arduino IDE, which still sticks to C++11.

Also, make them const, if appropriate.
Looking at the documentation at IoT DevKit web site you linked I see that it contains a number of ridiculous typos making it almost unusable. It is quite possible that you will run into problems with their library if you properly use const-correctness in your code.

I do not need independent instances of these bitmaps and want them to be immutable so I will implement the second approach. That's correct I'm using VS Code to build and deploy my code, but it's really using the Arduino IDE in the background. I've been doing my best to stick to proper coding style, it's unfortunate that these docs don't seem to take note of this.


text:
On the LEDs WS2812C
I've got a few questions about these LEDs (WS2812C). According to what I understand in the data sheet, they are adressable RGB LEDs with 4 pins: VCC, GND, DIN,DOUT. I'm working on a project that is an LED cube, and these LEDs are a very good candidate for my project, but I'm trying to figure out how I'm supposed to wire them (like how the circuit diagram should be).
So I have three questions:
1) is 1111 the maximum number of LEDs I can have in series? because the datasheet says that the maximum transfer rate is 800Kbps, and if I have to refresh the LEDs at a rate of 30 fps, and if my math is correct, 800Kbps/30fps/24bits = 1111 pixels. So please let me know if my math is correct on that, because that would imply that I would need two rows of LEDs if I were to make a 20x10x10 LED cube.
2) In the cicuit diagram of the datasheet there was only a capacitor and no resistor. According to what I know, you should always have a resistor in series with your LED, so that you don't blow it out. It is still the case with these?
3) Can I have one big capacitor instead of many small ones in parallel? I'd think that it would be equivalent but I'm not an expert so I don't know.
If any of you can help me figure out the answer to these questions I would highly appreciate it. Thanks.

are you sure that the LEDs are suitable for a 3D layout?

the serial protocol has a reset signal of 50μs for each refresh, so the maximum LEDs would be 1109 for 30fps

if you know what you are doing, apparently you can drive 20,000+ WS2812C @ 130fps

Ok, so to clear up a little how I'm going to make this cube happen, I am designing my own pcb and it's going to be a 5x5x5 cube to start, but I might make a bigger one in the future. Now I neeed to figure out the capacitor and resistor configuration for the pcb.
So do I need to have one capacitor (of value 15pF) per LED, or can I have one bigger capacitor (of value 15pF*n) for n LEDs?


text:
LCD Display 128x64 weird pin, C86 (input)
I got some LCD display from my friend. Base on the model number (TopWay LM6023) printed on product, I found the data sheet from google. According to the datasheet, it is a 128*64 LCD display, but I am confusing the pin out does not same/similar to the famous one. I read the datasheet, there are C86 pin. I have no idea what’s that, and how to make it work. I created a github repo, I am wonder if someone could help to write an example code and wiring to Arduino UNO.
Moreover, I also would like to know what is 6800 & 8080 interface, is it Arduino UNO can simulate ? If yes, any reference?

the difference is how the Intel  8080 and the Motorola 6800 handle hardware I/O ..... the 6800 uses memory mapped I/O .... it uses an enable signal (pin10) and read/write select signal (pin9) ..... the 8080 uses ports for I/O .... you enable the write signal (pin9) if you are outputting data from the microcontroller and enable the read signal (pin10) if you are inputting data to the microcontroller

with the arduino, you probably want to use the serial interface, since it uses only two pins for the data  (pin17 and pin18 (need to verify pin numbers))

Unfortunately driving a graphic LCD is not as easy as driving one of the most popular type HD44780 LCD's.
Back to the subject:
If the state on this pin is HIGH then you shall use  Motorola's 6800 interface, when state on C86 is LOW, use Intel's 8080 interface.
Depending on your selection you would have to keep the communication standard. For 8080 interface refer to point 3.3.1 of you datasheet, for 6800 see point 3.3.2.
Note: If you are struggling, try to search for the libraries using controller's name: LM6023A or one of the S1D15300 or S1D16700
Also, consider number of pins available on your Arduino. It may be that you can drive this LCD with Arduino Uno using serial interface only. (See this link)

Thank you for your reply, your information are helpful after I read the link. Seems it is not a simple task could be complete within a day or week.

This is why sometimes is easier to search for readily available libraries. Unfortunately this one is none of the most popular. You can also check the big collection of the libraries under the name of u8glib - see the list of the supported lcd's: https://github.com/olikraus/u8glib/wiki/device


text:
Is new without a delete acceptable?
I know it is not a good practice to use the new command to dynamically create data, however, if I would never use the delete, would it result in memory gaps/other problems?
Background
The reason I need to create instances dynamically, is that I want to test my application first on a PC. And I want for several classes to have more properties for the PC version than for the Arduino version (for example, to store names, or information for the PC GUI to display). The PC version classes will be inherited from the Arduino (real) classes, but with added properties.
In some classes I need to build up a list, and I cannot use a type with hardcoded values to fill an array.
Example:
I have a LightSetup class that has a list of Pars (which are LED lights):
class LightSetup
{
protected:
    Par* _pars[NR_OF_PARS];

Par is the Arduino/real version, to fill in these I need:
LightSetup::LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        _pars[n] = new Par(1 + 8 * n);
    }
}

In the PC version, instead of new Par, I use new TestPar.
And in the header I cannot define it without a pointer like this:
    Par _pars[NR_OF_PARS];

Otherwise it cannot contain TestPar instances.

You could avoid the new-delete-heap-issue by using a template class. Here is an example: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/IOBuffer.hh#L29

@MikaelPatel Thanks for this comment, it also sounds like a good idea ... forgot about templates (having used it 20 years ago for the last time ;-) ).

Another example is this GPIO template class that compile digitalRead/Write to a single instruction: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/AVR/GPIO.h

I have to say, when I first read the title I was pretty set on the answer being "It is never acceptable" but you have given me an interesting scenario to think about.  It's an unusual case but valid.

@MikaelPatel Thanks ... I need to check into this better, looks very useful.

@KellyS.French Actually I came to the idea, because in of my professional projects we instantiated all objects beforehand, not for delete/memory gap problems, but because of performance (no creation of new objects during the  critical execution parts).

Here is another example: Java allows you to pre-allocate a block of memory (starting heap size?) at load-time for exactly the same reason, to cut down on memory allocation during execution. This would actually make for a good general StackOverflow question for the general case and I'd encourage you to post about it.

@KellyS.French Thanks for that, although I cannot use Java for Arduino (at least not in the Arduino IDE).

Sure. Using new or malloc to set things up initially is really no different to static allocations. There is nothing inherently bad with using malloc or new, only in using it repeatedly with free or delete.
Allocating a block of heap memory and keeping it allocated for the rest of eternity does not cause heap fragmentation. It's only repeated allocation and deallocation of variable sizes (such as String causes) that start to create problems. Allocating at the start of your program and leaving it allocated, as long as you don't allocate too much, of course, is not a problem.

Thanks for the confirmation.  The only disadvantage I can see is that the used memory is not calculated to the global variables in the Arduino IDE.

Yup. Hence the nudge to watch out that you don't allocate too much :)

Maybe I will for debugging purposes show the amount of reserved memory after the new statements.

In the destructor you would need
LightSetup::~LightSetup()
{
    for (int n = 0; n < NR_OF_PARS; n++)
    {
        delete _pars[n];
    }
}

and every time you replace a _pars you need to delete the old one. This can be done automatically by using unique_ptr.
However for your purpose it sounds like a #if is better suited to differentiate at compile time which type you actually store inside that array.
#if ON_ARDUINO
    Par _pars[NR_OF_PARS];
#else
    TestPar _pars[NR_OF_PARS];
#endif

Well, the destructor will never be called, since in my Arduino application the loop will run forever, so it's not an issue. But I upvoted it for the last part, maybe that's even better than the new command (although it clutters up code a bit). However, if this is the only change, it is easier. Thanks

I agree with @ratchet on the #if as the case you describe isn't about dynamic typing but rather a difference in platforms. Unless you need the same binary to run on both platforms (if even possible) you would be better served by conditional compilation. This also removes the need to bother with a destructor.


text:
ESP8266 http.get() issue due to wifi authentication failure
Facing a weird issue while reading data from esp8266.
I am trying to read dynamic data from a demo text file on test server on same network in deep sleep mode.
Case1: Joining new network
I am using WifiManager to join network and then followed by http.get()
However whenever i try to join the wifi with correct credentials it does not connect sometimes. Post some time ,if i try to wake the device it automatically connects and displays the data.
Case2: Rejoining existing network
Similar issue happens when i stop the test server and update the text file contents and up the server and try to read it on esp8266. It ask me the credentials again which it should have remembered 1st time. Post some time, if i try to wake up device sometimes it automatically connnects and prints updated value.
I am unable to figure out the problem here and its solution.
Any suggestion please.
#include <WiFiManager.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Arduino.h>
#include <ESP8266httpUpdate.h>

ESP8266WiFiMulti WiFiMulti;
HTTPClient http;
WiFiManager manager;

  int publishPin = 0;
  int wifiPin = 5;
  unsigned int baud = 115200;
  const char* url3 = "192.168.43.215";
  const int httpsPort = 80;

  const String macValue = WiFi.macAddress();

 void publishData()
 {
    String link = "/one.txt";
    Serial.print("connecting to ");
    Serial.println(url3);

    http.begin("http://192.168.43.215/one.txt");

    int httpCode = http.GET();
    if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      Serial.println("This device is authorized!");
      Serial.println(http.getString());
      Serial.println(httpCode);

    }else {
    Serial.println("Failed to connect to API.");
    Serial.println(httpCode);
    return;
  }

  http.end();
  delay(1000);
}

void restPublish(){
  Serial.println("Rest publish");

  publishData();

}

void setup()
{
  Serial.begin(115200);
  Serial.println("setup2");

  manager.autoConnect("espdevice");
  restPublish();

 Serial.println("entering deepsleep now. DND");
 ESP.deepSleep(0);

}

void loop()
{
}

I didn't see any point where you are trying to connect to WIFI. 2. As far as I understand you had create a local network over your laptop using some APACHE or something else. As your question that sometimes you are not connecting to the server, for connection your client and server must be on the same network to connect. Please make sure that your local sever and esp device must be connected to the same network

I would try some small delays between connecting and publishing and between publishing and deep sleep

Thanks for the reply Vaibhav,
Above it did mention i have the client and server running on the same network and i am using nginx as the server.
Case1, is the code newly installed on ESP so it will get me webpage for 1st time configuration.
Case 2 i made clear about network, it doesnot join the wifi

Thanks juraj,  it works i think it needed some delay. i will do some more testing on it.

you could search for more exact solution. there are some recommendations on what to do before deepSleep. and you can test if the wifi is connected. delay() calls yield() which performs 'background' tasks...

Could you share some links for recommendation before deep sleep.
Yes i will work on check wifi connection. thanks

now I see you have a delay in restPublish() at  the end


text:
How to secure the communication between android app and door lock controller?
I have been working on a small project using android app over Bluetooth to control a servo motor (close or open lock). To authenticate the communication, I implement HMAC (with SHA256) on both the android app and the arduino controller.
When user press the button to unlock the door, it will generate a random code,  which will be seen as a message. Then HMAC is called to create a hash string with this message and the shared key. The final string sent to arduino would be  "randomcode+commmand+hashed-string"
Something like this:

 5uq0xboq82oih111e30774e4bf8302a04e71eb84c70ce2c130717304f52c67ce709203caea0ce5
(command and the random code are hidden in the string)

As the arduino received the message, it will break the string into three parts. The command, the random code and the hashed string. It will run HMAC with the shared key and the random code. Then compare that with the received hashed string. If matched, the perform the action (command).
This is my first project on implementing HMAC. I know this may be sort of subjective question but any comment on this implementation may helpful. Thanks.

How do you prevent replay attacks? Also, if someone can intercept the message; he could change the command part, and send it to the Arduino, and it will accept it. I'd hash the randomcode+command, not just the randomcode.

I am not an expert on this but I don't think replay attacks would work. HMAC deals with user authentication and validates data integrity. The command is just 1 or 0.  Adding it to the HMAC or not wouldn't make much difference, I think. The arduino controller will not execute any command unless the HMAC message is matched.

HMAC only does the authentication part. Since you don't hash the command, it doesn't do anything for data integrity. HMAC also doesn't solve the replay attack problem. Unless the Arduino stores all previous randomCodes, and rejects if they are re-used again. What would happen if you send a "door open" message, I intercept the message, and resend it after you've gone for work? The hash will match!

I could append the command to the random code, if it will make any difference. Someone may be able to guess what it may be. Intercepting the message is indeed possible as there is no secure communication channel, however my findings show that you would have to know the shared key in order to have a matched HMAC hash. So as long as the shared key is not compromised, the application will be safe and sound. No?

You still haven't solved to the replay-attack problem. The attacked doesn't need to "decyper" the message. It just needs to store it, and play it back later. This is the third time I brought this up. Why do you think your solutions isn't vulnerable to it?

it is wide-open to replay as described. you just need to generate the random salt on the ardunio (easier said than done), send it to the app, let the app create the derivation, send the arduino the result to dis-assemble and compare. that way, old keys won't work and the app itself cannot mint valid keys.

Thank you both for raising the alarm! I started with generating a random code from Arduino but walked away when finding that's not an easy task. Having your input,  I should go back to the drawing board.

Generating the random code from arduino controller as soon as the connection is being established and set a time limit such as 30 seconds, after that the code will no longer valid, should address the replay attack, at least for an application such as door lock control.


text:
Morse Interpreter-Microphone Problem
I am working on a morse interpreter. I can now use light-sensor and a regular key as input device and want to add a mic to the system. I recieve the input convert it to text and show it on nokia 5110 lcd. And also whilst input, an led and a buzzer turns on and off simultaneously. When I use mic the led works just as it should but I do not get any correct input to the lcd. I attached Out and Gnd pins of mic just as I would attach the key and vcc to 5v.
The following is the code which I use
#define RST 12
#define CE  11
#define DC  10
#define DIN  9
#define CLK  8

#include "font.h";

unsigned long signal_len,t1,t2; //time for which button is pressed
int inputPin=2; //input pin for push button
int ledPin=4; //output pin for LED
String code=""; //string in which one alphabet is stored

void LcdWriteString(char *characters){
  while(*characters) LcdWriteCharacter(*characters++);
}

void LcdWriteCharacter(char character){
for(int i=0;i<5;i++) LcdWriteData(ASCII[character-0x20][i]);
LcdWriteData(0x00);
}
void LcdWriteData(byte dat)
{
  digitalWrite(DC, HIGH); //DC pin is low for commands
  digitalWrite(CE, LOW);
  shiftOut(DIN, CLK, MSBFIRST, dat); //transmit serial data
  digitalWrite(CE, HIGH);
}
void LcdWriteCmd(byte cmd)
{
  digitalWrite(DC, LOW); //DC pin is low for commands
  digitalWrite(CE, LOW);
  shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
  digitalWrite(CE, HIGH);

}
void setup()

{
  Serial.begin(9600);
  pinMode(inputPin, INPUT_PULLUP); //internal pullup resistor is used to simplify the circuit
  pinMode(ledPin,OUTPUT);

    pinMode(RST, OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(DC, OUTPUT);
  pinMode(DIN, OUTPUT);
  pinMode(CLK, OUTPUT);
  digitalWrite(RST, LOW);
  digitalWrite(RST, HIGH);

  LcdWriteCmd(0x21);  // LCD extended commands
  LcdWriteCmd(0xA9);  // set LCD Vop (contrast)
  LcdWriteCmd(0x04);  // set temp coefficent
  LcdWriteCmd(0x14);  // LCD bias mode 1:40
  LcdWriteCmd(0x20);  // LCD basic commands
  LcdWriteCmd(0x0C);  // LCD normal video

  for(int i=0;i<504;i++)LcdWriteData(0x00);
}

void loop()
{
NextDotDash:
  while (digitalRead(inputPin) == HIGH) {}
  t1 = millis();                            //time at button press
  digitalWrite(ledPin, HIGH);               //LED on while button pressed
  while (digitalRead(inputPin) == LOW) {}
  t2 = millis();                            //time at button release
  digitalWrite(ledPin, LOW);                //LED off on button release
  signal_len = t2 - t1;                     //time for which button is pressed
  if (signal_len > 50)                      //to account for switch debouncing
  {
    code += readio();                       //function to read dot or dash
  }
  while ((millis() - t2) < 500)           //if time between button press greater than 0.5sec, skip loop and go to next alphabet
  {
    if (digitalRead(inputPin) == LOW)
    {
      goto NextDotDash;
    }
  }
  convertor();                          //function to decipher code into alphabet
}
char readio()
{
  if (signal_len < 150 && signal_len > 20)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (signal_len > 150)
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}
void convertor()
{
  static String letters[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                             ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "E"
                            };
  int i = 0;
  if (code == ".-.-.-")
  {
    Serial.print(".");        //for break
    LcdWriteCharacter(".");
  }
  else
  {
    while (letters[i] != "E")  //loop for comparing input code with letters array
    {
      if (letters[i] == code)
      {
        Serial.print(char('A' + i));
        LcdWriteCharacter(char('A' + i));
        break;
      }
      i++;
    }
    if (letters[i] == "E")
    {
      Serial.println("");  //if input code doesn't match any letter, error
      LcdWriteCharacter("");
    }
  }
  code = "";                            //reset code to blank string
}

print the signal_len

Please don't use goto, unless you really really need it. Using this can lead to big problems. There is a reason, why it is seldomly used in C/C+. You can just put the convertor() inside the if, where the goto is, and add a break after it.

Depending on what "mic" you use, you may also need a pre-amplifier

I attached Out and Gnd pins of mic just as I would attach the key and
  vcc to 5v.

This can't work. Unlike the key, the microphone is an analog device that
will output a continuously varying analog signal. If you expose it to a
pure tone it will output a sine wave. If you sing a note in front of it,
it will pick not only the sine but also a lot of harmonics. In any case,
it will also pick the ambient noise.
What you need to do is somehow determine the amplitude of the sound
signal, then compare that to some threshold in order to decide whether
the amplitude is high enough to be considered “on”. You could use a
diode-based peak detector and a comparator. Doing all this in code is
kind of tricky. You may want to take a look at this sound-level meter
sketch, but note that a software peak detection could be
simpler than the true-RMS intensity detection implemented in that
sketch.


text:
I want my arduino mega to read from all 4 serial ports at the same time, running sequentially through each one
I currently have the code running through Serial1, which works exactly as I want it to:
int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
  Serial.println("Arduino is ready");
}

void loop(){

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.print("Reader 1: "); //read out any unknown tag
  Serial.println(tagString1);

  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

However, I want to add serial0, 2, and 3 as well. there are 2 main questions I have
1) is it possible to have copy paste this section of the code:
    while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.print("Reader 1: "); //read out any unknown tag
  Serial.println(tagString1);

  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
}

while changing some of the variable names to connect the other serial ports? I saw something here, but don't know how to implement it, or if it even would work for me.
and
2) since I am routing the incoming data through serial0, Is it possible to have this code working on it as well?

There might be a way to do it if in the void loop I set up certain functions, and then treat each function as its own void tag (unsure if that is the correct terminology). That is basically what the link does, but I have no idea how I would go about setting that up in code.

Is there something that defines the end of the data? For example linefeed? Is there a start byte? What kind of data is received.

I didn't four serial ports in your code. What I understand is that you hadn't upload your full code or you just created four object for a single port. As @jsotola said you can't read all serial at the same time with single ALU or Ardunio you need four ALU or arduino to process four peripherals at the same time. If you are going to sequential reading my advice will be that you first read the data from all ports first the go for data analysis part.

@Jot CR/LF used to for new line defined beginning and end of data

@jsotola true, I meant sequentially, good point

@vaibhav correct, I want it to be read sequentially

Then I would put every incoming character in a buffer. A buffer per serial port. When the cr/lf is received then the data in the buffer can be processed. Perhaps all the buffers and all the serial ports can be put into an array or a array of structs.

The Arduino already reads from the 4 serial ports at the same time. Or
at least as close to “at the same time” as possible with a single CPU:
every time a byte is received at one port, an interrupt is triggered
that reads the byte from the UART and puts it into a buffer. You can
then get it from the buffer using Serial.read().
What you now have to do is move the bytes from these buffers (which
belong to the Arduino hardware serial library) into you own buffers for
further processing. You can do this by checking the ports sequentially
and processing each one in turn. Everything will be fine as long as you
do not have blocking code in there. If you do block, then you run the
risk of having one of the library buffers overflow. The code you posted
is non-blocking, so you are fine.

is it possible to have copy paste

You should avoid programming by copy-and-paste. It's not that it won't
work (it will), but you would be creating a maintenance nightmare.
Instead, put the code you would want to copy-paste into a function, and
call that function as many times as required. For example:
void handlePort(Stream &port, const char *readerName, char *tagString)
{
    boolean reading1 = false;
    while (port.available() > 0) {
        int readByte1 = port.read(); //read next available byte

        if (readByte1 == 2) reading1 = true;
        if (readByte1 == 3) reading1 = false;
        if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
            tagString[index] = readByte1;
            index++;
        }
    }
    Serial.print(readerName); //read out any unknown tag
    Serial.print(": ");
    Serial.println(tagString);

    clearTag(tagString); //Clear the char of all value
    resetReader(); //reset the RFID reader
    }
}

And you call it in loop():
handlePort(Serial1, "Reader 1", tagString1);
handlePort(Serial2, "Reader 2", tagString2);
...

problem is, I want the reader to change names as well. for instance, when it is going through serial1, I want it to say "Reader1", fro serial2, I want "Reader 2" and so on.

Also, tagString1 in the loop() is throwing an error

@Rambunctiouslad: 1. Anything you want to change from port to port should be passed as an argument to the function. Specifically, for the "Reader 1"/"Reader 2" issue, see the code in my amended answer. 2. Re “tagString1 in the loop() is throwing an error”: sorry, I don't have a crystal ball to tell me what the error is.

all the errors was my own stupidity, as I called it wrongly. Once i figured out what was going on, I was able to fix it, and now everything works. thanks for the help


text:
Is code in a class repeated for each instance?
I haven't needed classes before in programming for Arduino, but I now have a good use case. I'm not sure I grasp how this will affect code space, though.
Currently I have a struct that holds the properties of an object, and common code that iterates over an array of 12 of that struct. It's fairly compact.
It would be cleaner to wrap the operations on the struct in a class and act on an array of 12 of that class. Essentially the current struct would become private data of the class.
Will all the code in the class be repeated in each instance, or is the compiler clever enough to avoid such repetition?
Any clarifications welcome. C++ is not my main language.

No, it is not repeated. Unless you are using templates, each method of
each class is stored only once in the compiled program. Or even not
stored at all if the optimizer notices it is not used.
Just to demystify the classes a bit, you can consider them as a kind of
“syntactic sugar” over an “object oriented” programming pattern. The
following C++ code:
class MyClass {
public:
    int aMember;
    long anotherMember;
    int aMethod(short);
};

int MyClass::aMethod(short theParameter)
{
    return aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    objects[1].aMethod(42);
}

is interpreted by the compiler as being roughly equivalent to this C
code:
typedef struct {
    int aMember;
    long anotherMember;
} MyClass;

int MyClass_aMethod(MyClass *this, short theParameter)
{
    return this->aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    MyClass_aMethod(&objects[1], 42);
}

Can you spot the differences and the similarities?

I get the idea but I'm not sure how to interpret return aMember + theParameter; In any case, the main question is answered, so thanks.

@JimMack: Within a method, the class is used as a sort of namespace. So the compiler knows that aMember actually means this->aMember.

No, the code is not repeated for each instance. Instance methods are like functions. There is only one copy of the code.
There's a dispatch table that maps method calls to their implementations. (Actually, that's standard C++. I don't know for sure how it's implemented in the Arduino C++ compiler)

Dispatch table is only used for virtual methods. As long as we are talking about non-virtual methods, everything works exactly as @Edgar Bonet described. No need for any tables. Arduino IDE C++ compiler is C++11 compiler with GNU extensions.

Important distinction about virtual methods. Thanks for pointing it out.


text:
AnalogWrite problem
I have connected DRV8835 with 2 DC motors with 11 power supply. Arduino nano.
When I for loop like i from 0 to 1024 for analogWrite(i,Motor1) for the DC Motor1 it's accelerating from 0 to 200 and it's stopping. When I becomes 250 it's starting at higher speed. When it becomes 500 it's stopping again. And 550 we have our power again.
Now I tried to run analogWrite(1000, ***) but it's not working. When I change the value from 1000 to 1005 it's not working again. But at 1024 we have the maximum speed and it is working?

 #define LEFT_PWM 9
 #define RIGHT_PWM 10
 #define LEFT_DIR 5
 #define RIGHT_DIR 6

void setup() {
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(LEFT_DIR, HIGH);
  analogWrite(LEFT_PWM, 1000);
}

analogWrite has the following prototype
void analogWrite(uint8_t, int);

which means that its first parameter has [0, 256) range and follows the rules of modulo arithmetic, with 256 as the modulo. If you supply arguments outside of [0, 256) range, they will be interpreted % 256. 1000 is the same as 232 (1000 % 256 == 232), 500 is the same as 244, 550 is the same as 38 and so on.
This is not fully consistent with the symptoms you describe (if your description is accurate), which might imply that something else is a factor here. Are sure you are using your DRV8835 in PHASE/ENABLE mode (pin 11 pulled high)?

The pin MOD was the real problem. Soldered it to VCC with a wire and problem is solved. Before that the motors behavior was very random.


text:
Change the mac address on an HC-05
So I tried to save a little money and bought (5) HC-05 bluetooth modules off of our good buddy eBay.
When the modules arrived, as I was testing and setting up for my project (2 nano's connected via an HC-05 each to a Galaxy S4), I noticed all 5 modules shipped with the same MAC address.
I have been looking everywhere I can think of to modify the MAC address of the modules, but have had no luck.  Well, that isn't 100% accurate.  I found bdaddr on linux, but I do not have a linux machine.  Just Windows for me right now.
So, my issue is trying to find a way to set the HC-05 modules with different MAC addresses so I can have (2) connect at the same time to my S4.  I have been able to change the name of the units via the AT commands, just not the MAC address.
Thank you in advance for your help.

i do not have any experience with the HC-05 module, but it looks like AT+BIND=<Param> sets the MAC ..... page 8 of this https://exploreembedded.com/wiki/images/a/a5/HC_05_Core_Datasheet.pdf

Any luck with this topic I have a similar problem on my HC-06 I have seen a set of instructions to update the firmware of the HC-05 and HC-06 on line and wonder if the MAC address can be changed during this process.


text:
HC-02 Bluetooth module not visible
I am trying to connect to my robot car with the HC-02 module. The problem is that the module is visible on my phone only while the arduino uno board is connected to my laptop. At this point I can pair my phone with the module, but I can't controll the car. When I disconnect the car from my laptop and turn it on, HC-02 is not visible anymore. It's blinking fast which means it should be available for connecting. I cant access the AT mode and I don't know what to do anymore. Has anyone had problems with this.
My phone is Android, I also tried with another one and still not working.
I also removed arduino uno from the car, I connected only the Bluetooth module. I can see HC-02 when Arduino is connected to the PC with the USB cable. But when I disconnect it from the PC and power it with the battery it disappears from available devices.

can you share your code and schematic here.

I added the code. I also explained it a little more

Try another serial using SOFTWARE Serial Library for ardunio for HC-02. Then connect arduino to your laptop and try to control your car and attach your full code here. Copy Paste you code here.

I tried with your solution and it works, thanks. There is obviously problem with the RX0 and TX1 pins.


text:
NRF24L01+ (TMRH20 library): Receiver gets blank data
I am working on sample Arduino project for communication over NRF24L01+ (TMRH20 library), everything is working fine with my example except one issue my Receiver gets message but that message is blank. Now i am not sure how do i debug as per serial monitor data is getting transmitted, as per receiver serial monitor it receives data but its blank.
Transmitter code -

// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[12] = "Msg AKSHAY";
//int dataToSend = 1;
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[10] = txNum;
}

Receiver code -
// SimpleRx - the slave or the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.startListening();
}

//=============

void loop() {
    getData();
    showData();
}

//==============

void getData() {
  if ( radio.available() ) {

       radio.read( &dataReceived, sizeof(dataReceived) );
      Serial.println(dataReceived);
       newData = true;
   } else {
       Serial.println("No radio available");
   }
   delay(100);
}

void showData() {
    if (newData == true) {
        Serial.print("Data received ");
        Serial.println(dataReceived);
        newData = false;
    }
}

Below is the output TX1 (Transmitter ) and RX1 is Receiver. You can see that Transmitter even gets acknowledgment also..

Both of my devices are arduino nano and below is wiring diagram between arduino and nrf24l01.

I also saw few post where people suggested using 100uf capacitor in NRF24L01 (GND & VCC), this helped me with accuracy in connection but data is still missing.

Had you tried the for loop while printing your data on the serial as you are receiving data in the form of char array.

I tried that but it doesn't help.

Can you please upload the unmodified PingPair example and see if that works? It's really hard to see the real cause if it might be just your code.

I have tested your code. There appears to be defective clones of the nRF24L01 around that exhibit an issue I show in post nRF24L01 continuously reading closed pipe
You can work around this issue by changing your code as follows (although your process still has to read all those nulls):
void getData() {
  uint8_t pipeNum;
  if ( radio.available(&pipeNum) ) {

       radio.read( &dataReceived, sizeof(dataReceived) );
      //Serial.println(dataReceived);
      if (pipeNum < 2) {
       newData = true;
      }
   } else {
       Serial.println("No radio available");
   }
   // delay(100);
}

A couple of clarifications first

At the time instant 22:38, the receiver isn't detecting any available radio devices but at the transmitter side, an acknowledge is received. How is that possible? How is your tx getting an ack without the rx getting connected.
I have not seen slave adresses being set as - const byte slaveAddress[5] = {'R','x','A','A','A'}; For the record, NRF24L01 adresses are 5 bytes long by default and not 1 byte long as you have defined. While defining the pipe addresses, the first 4 bytes of the adresses should be same among all the pipe addresses. Only the last byte should be unique. Pipe addresses can be 0xF0F0F0F0A1, 0XF0F0F0F0B1, 0XF0F0F0F0C1, 0XF0F0F0F0D1, 0XF0F0F0F0E1 Try setting the pipe addresses as uint_64t address[5] = {0xF0F0F0F0A1LL, 0XF0F0F0F0B1LL, 0XF0F0F0F0C1LL, 0XF0F0F0F0D1LL, 0XF0F0F0F0E1LL};Do the same declaration at the receiver end too. And btw, you can specify any byte you want in the last byte of the address. Here I have defined the last bytes as A1, B1, C1, D1, E1.
To make sure that communication is successful, set some custom ack byte and compare it with the received ack. If both match, you can be sure that the rx did get the data. Sometimes, the NRF24L01 can pickup garbage values from stray signals present around and it can consider it as data sent by the receiver. So to avoid false triggering, its better to make a fool-proof ACK mechanism.

Your second point makes no sense at all. You are trying to stuff five-byte-wide values into one byte, which is pointless. In fact, the original intent of the OP with his const byte slaveAddress[5] = {'R','x','A','A','A'}; apparently is an attempt to create a 5-byte address. Exactly as you said it should be. It is a single slave address, not five of them.

Sorry! It should be uint_64t. Thanks for pointing it out AnT

(Firstly, it's uint64_t, not uint_64t.) But that will declare 5 separate addresses. How is that relevant to the OP's question? Why 5? He does not need five separate addresses, he just needs one.

Also, this is an example from RF24 header file itself: uint8_t address[] = { 0xCC,0xCE,0xCC,0xCE,0xCC }; radio.openWritingPipe(address);.  (https://github.com/nRF24/RF24/blob/master/RF24.h#L246) As you can see, this is the same thing as in the OP's code. There's nothing wrong with it.


text:
How can I tell which fuses are set on an ATtiny?
Following on from this question, Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature,
if the response from avrdude is 0x000000 then the internal oscillator is probably not being used and an external one (be that crystal or clock signal) is required.
However, as this menu, from Engbedded Atmel AVR® Fuse Calculator, shows, there are a lot of options:

So, instead of having to configure circuits for each of the options, in turn, until the ATtiny responds, is there any way that I can read which of the CKSEL and SUT fuses are set?1

Background
I am using a Nano/Uno as an ISP programmer, and the ATtiny is on a dev board like this (although it would be the same issue if I were to use a breadboard):

I know for sure that the connections are fine as I have checked them from pin to pin of the two ICs (ATmega328PU to ATtiny85), using a DMM.
I am receiving 0x000000 as in:
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

because the ISP programmer can't read the ATtiny, because an external clock source has been set via the fuses. However, I wish to know how to read which clock source has been specified, without having to manually try all of the circuit permutations.
I don't think that just connecting a crystal (and two ceramic capacitors) will work if the exact setting, i.e. external clock, has been selected. However, if a 16MHz crystal works for all, or any, of the external clock settings then that would be great, but I'm sure it doesn't work like that, as you can have a crystal attached but the it might not be used, see Does device signature 0x000000 mean the atmega is bad:

Even though you have a crystal connected, that does not mean it is oscillating. For example, IF you set fuses for "External Oscillator", that will turn the crystal oscillator off.

When I move the ATtiny85 to a breadboard and add a crystal (16 MHz) and two 22 pF capacitors, the error has changed for the better (at least now it sees that a ATtiny is connected)
avrdude: Device signature = 0xff0000
avrdude: Expected signature for ATtiny85 is 1E 93 0B
         Double check chip, or use -F to override this check.

Interestingly the signature varies:

0xff0000
0x00ffff
0xff00ff

When I add an external power supply to the ATtiny on the breadboard, following advice from Atmega (any chip) Device Signature issues and stk500_getsync()(resolutions), then unfortunately the device signature in the response returned by avrdude reverts back to 0x000000
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

1 This is, admittedly, a bit chicken-and-egg, as if I can't communicate with the ATtiny, due to the incorrect clock setting, then how can I read which fuses have been set..?
It's a bit like saying "If I don't have petrol in my car, then how can I drive to the petrol station to fill up?" - but I was hoping that there might be some sort of time saving measure

How are you powering the Attiny during programming? Extra capacitor on VCC-GND? https://forum.arduino.cc/index.php/topic,51819.0.html?utm_source=rb-community&utm_medium=forum&utm_campaign=device-signature-0x000000-while-burning-bootloader

The USB port on that board is only used for power! You can't program the ATTiny over that USB port.

@Gerben - I am using the ICSP pins and a Nano as the ISP programmer. Once you get the micronuleus bootloader installed then you can use the USB port to program it... see Breathing life into the DigiSpark clone with ATtiny MCU

@MikaelPatel - No I didn't have one of those... interesting... I added a 20 uF, but still the same random signature errors... I notice that in the link, an external supply is recommended, in addition to the extra cap. However, when I added the regulator and additional cap, then situation regressed and the device signature reverted back to 0x000000, unfortunately.

It could be that the ISP-disable fuse is set. I've had some ATTiny13s from China that had their fuses preprogrammed, which made them unusable. I build a simple High Voltage Programmer, to reset the fuses. I think I used this code and schematic https://github.com/tsaarni/avr-high-voltage-serial-programming. Pretty simple circuit. Only two resistors and a transistor. For the 12V source I just stacked 4 CR2032 coincells on top of each other, holding two jumper wires at both end with one hand. Very hacky, but it worked.

This seems to be an X -> Y problem, with X being the missing clock source on your ATTiny, which prevents communication.
If you have a second Uno or other AVR device, you can use that to generate a clock signal on any of the digital pins:
void setup() {
  DDRB = 0b00100000;
}

void loop() {
  PINB = 0b00100000;
}

This creates a square(~ish) signal on Pin 13 with a frequency of 1.6 MHz.
Depending on the IDEs optimization level (platform.txt), a frequency of 4 MHz is also achievable (at -O3 instead of -Os).
Connecting this to the XTAL1 pin of your ATTiny85 should allow you to communicate with the board.
Make sure to interconnect all grounds.

You need a Programmer that connects to the ISP pins
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
The programmer will hold Reset low, then communicate via the SCK/MOSI/MISO pins to read/update the fuses, read/program memory, and optionally read/program the EEPROM.
Section 20.2 discusses the 3 fuse bytes.
I use an older Atmel AVR-ISP MKii. Atmel stopped making them, there seem to be plenty of replacement choices available, and Atmel Studio 7 when I struggle with Atmega328P, '1284P, and 2560. I haven't used an Attiny in a project yet.
https://www.microchip.com/mplab/avr-support/atmel-studio-7

I obviously wasn't clear in my question. I am using a Nano/Uno as an ISP programmer. I am receiving 0x000000 as in  avrdude: Device signature = 0x000000 because the ISP programmer can't read the ATtiny, because an external clock source has been set via the fuses. However, I wish to know how to read which clock source has been specified, without having to manually try all of the circuit permutations. This is, admittedly, a bit chicken-and-egg, as if I can't communicate with the ATtiny, due to the incorrect clock setting, then how can I read which fuses have been set..?

I think you just need to supply a clock, easy way is to connect a crystal and two 22pF caps.  Read here, Nick Gammon goes thru a lot of the fuse settings stuff.  https://www.gammon.com.au/forum/?id=11643

I was thinking that it might not work if the exact setting hasn't been selected, if a 16MHz XTAL works for all or any of the external clock settings then that would be great, but I'm sure it doesn't work like that, as you can have a XTAL attached but the it might not be used, see Does device signature 0x000000 mean the atmega is bad:  Even though you have a crystal connected, that does not mean it is oscillating. For example, IF you set fuses for "External Oscillator", that will turn the crystal oscillator off.

The best way to know for sure is to use a High Voltage (12V) Programmer to reset everything.  https://gammon.com.au/forum/?id=12898

This High voltage serial resetting looks promising, but the page isn't particularly clear on how you reset the particular fuses, or to what value. I guess more reading is required. Just applying the 12V momentarily doesn't reset the fuses per se, it just puts it in serial programming mode. I'll need to read around it more.

Sure, see section 20.7 of the data sheet and Table 20.16.  If I recall, you have to do a Chip Erase before you can Reset the fuses.


text:
Arduino will not read three successive packets in the serial connection
I have written a small program to send serial commands from Python to the Arduino Micro.  This is my code for both:
Python
import serial

ser = serial.Serial('COM5', 9600)

ser.write(b'0')
ser.write(b'1')
# ser.write(b'2')

print('done')

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

void loop()
{

  while (!Serial.available()){}
  Serial.println(Serial.read()-48);

}

If I keep the ser.write(b'2') line in the Python code commented out, the code executes nearly instantly, and I am able to see both transmissions in the serial monitor. If I uncomment it, the Python code takes about 5-7 seconds to execute, and none of the data comes through the serial monitor.
I've tried different baud rates but that hasn't helped. I've also tried sending an integer rather than b'#', and the same thing happens, no data is transmitted if I have all three serial commands active.
What is happening in my code? Is the serial buffer overloaded by the three successive writes and the buffer ends up flushing?

are you sure it is not a problem every second run and not dependent on the write lines?

Hi Juraj, I'm not sure what you mean, can you clarify?

It runs reliably with 2 writes.  It fails every time with 3 writes.

what if you send '0' and '2'  or '1' and '2'.   Same issue?

You don't overload your input buffer, but your output buffer

Chad, I will try that, but I think the last time I did, I just got 0's at the output.
Chrisl, Are you sure?  This serial test is part of a much larger program which sends hundreds of serial commands every second, and I suspect the output buffer would have gotten saturated very quickly, but I haven't run into that problem, I dont think....

Are you testing with the code above, or with your larger program? That makes a difference. The above code will most likely fill the output buffer fast, because there is nothing, that would slow the loop down. If you have a larger program, it may slow down the loop enough (depending on the program). so that the ATMega has enough time to send out the data and empty the buffer.

This may be an issue with python. A full RX buffer on the Arduino does not do anything to the python program, since there is no flow control with Arduino UART. If the input buffer is full, data will simply lost. No blocking of the sender.

Hmm, I don't see a loop that is able to overflow any buffer. The python script just finishes after sending 3 bytes. The arduino sketch will only print if anything anything has been received. Also, from my experience an atmega running at 8Mhz is absolutely fast enough to poll for incoming bytes that are transmitted at a baudrate of 9600...

Oh, sorry, my mistake. Read it falsely. But still I would assume, that the error lies more with the python side, assuming that the OP really tests with the code above and not with the larger code.

The problem is that your code works but you substract 48 from what you received.
Which if python sends a char with values: '0' '1' '2' it will result in the serially outputted values of NUL SOH STX which are invisible.
If python transmits the raw byte value (aka 0x00 0x01 0x02) this would result in 0x00 - 48 = undefined behaviour with a underflow (same goes for 0x01 and 0x02)


text:
What is wrong with my code? RGB potentiometer
Arduino programming has been a huge learning curve for me and I am trying to create a project with an rgb that's color is determined by a potentiometer. To where the further I turn it, the further across the rainbow spectrum it goes. I can't figure out how to do all values in between because I am not educated enough but I came up with this basic code...
int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor = 0) {
      setColor(255, 0, 0);  // red
    }
    if (wavecolor > 0 or wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    if (wavecolor > 333 or wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    if (wavecolor > 667 or wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    if (wavecolor = 1023) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

And for some reason, where the light should change colors once the potentiometer goes past a certain number, the light just flickers and only changes colors to white when it is all the way up or down. Also, it has a weird flickery yellow color.
Since I am new to this, can one of you better educated people be willing to assist me?

think about this .... what will happen if you set the potentiometer to 333?

Equality comparison in C and C++ is expressed by == operator. ==, not =. This
if (wavecolor = 0) {

actually assigns zero to your wavecolor variable, thus destroying the value you just read.
The common sense says that you actually need and in your conditions, not or
if (wavecolor > 0 and wavecolor < 333) {

The or conditions that you curently use are simply always true, which makes them nonsensical.
This is valid syntax
wavecolor > 0 or wavecolor < 333
wavecolor > 0 and wavecolor < 333

but you might want to try using more "canonical" forms
wavecolor > 0 || wavecolor < 333
wavecolor > 0 && wavecolor < 333

or and and are "alternative" forms of || and && operators, introduced a long time ago for reasons that are all but obsolete today.
Assuming that you meant and instead of or, in your conditions you managed to "exclude" such values as 333, 667 and 1022 - they wouldn't match any of and conditions. Changing some strict comparisons to non-strict ones might be in order.
As a side note, in a single-file program all file-scope variables should be either const or static. In your case
const int redpin = 6;
const int greenpin = 3;
const int bluepin = 5;
const int potPin = 0;

"should be either const or static", saves a few bytes of SRAM too, can come in handy in big programs with lots of variable data.

Stylistic point: I prefer to write my conditions to look like ranges (in languages that don't have ranges built in), so 0 < wavecolor and wavecolor < 333 rather than wavecolor > 0 and wavecolor < 333

@Alexander: It makes perfect formal sense. But in practice it doesn't always work as well as one might expect. It clashes with another natural principle: express comparisons as "variable vs. limit" in that specific order, since that is how we usually express them in natural language. Which approach will win in the end is a matter of personal preference.

@AnT Yeah, it's certainly contentious, but I have 3 reasons I prefer it: 1) It "looks" like a range, 2) The operands are ordered from least on the left to greatest on the right (which is usually how things are ordered, e.g. the x axis on a graph)

Try this code below. This will give you the desired output!
int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor == 0) {
      setColor(255, 0, 0);  // red
    }
    else if (wavecolor > 0 && wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    else if (wavecolor >= 333 && wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    else if (wavecolor >= 667 && wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    else if (wavecolor >= 1022) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

Read up on logical and relational operators in Arduino (||, &&, >, <, ==, >=, <=) etc.
 I will leave the logic development to you as it is what develops your coding ability and trust me logic is the most important and fun part of writing a code!


text:
Why does a variable size struct not compile in the Arduino IDE?
This sketch does not compile in the Arduino IDE
void setup() {
  // put your setup code here, to run once:

}

struct test {
  int i;
  char variable[];
};

typedef struct test test;

test t = {
  0, "hi"
};

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

}

Arduino throws
sketch_may09a:16: error: initializer-string for array of chars is too long [-fpermissive]

 };

 ^

exit status 1
initializer-string for array of chars is too long [-fpermissive]

However compiling with g++ works just fine. How can I fix it? Or is there a principle reason why flexible array members are not supported?

It hurts to see that code, so it must be wrong. A struct is a definition of a variable (wich contains other variables). How would you create an array of those structs when they have different lengths?

@Jot: The struct type itself is declared correctly. There's nothing wrong with an [] array as the last member of a struct. However, in standard C language the only way to make such structs to "have different lengths" is to malloc them individually. This is what this [] feature is designed for. In all other contexts the [] array simply "disappears" (i.e. it is an array of size 0). So, the issue simply does not exist in situations when one'd try to create an array of such structs.

@AnT I know that it is set to zero size and I have read your answer with the correct type definition and declaration of the structs. the_architect tries to put the characters into the struct itself. That is not possible.

@Jot Not sure what answer you are talking about. Placing the characters into the struct itself, as the OP is trying to, is possible through GNU-specific extension. As I said already, the OP code is perfectly correct from GNU point of view.

Flexible array member is a C feature. It does not exist in C++. On top of that, the way you use it to declare and initialize a static struct of flexible size is non-standard even for C.
However, GNU-C language supports it as an extension. Also, newer versions of GCC (6 and higher) allow this in GNU-C++ code as an extension as well. But GCC 5.4.0 used by Arduino IDE doesn't support this non-standard feature in C++ code.
If you flip through different GCC versions on Godbolt (https://godbolt.org/z/Iul7hD) you'll see that support for this feature has always been present in C code, but for C++ code it first appeared in GCC 6.
This is why you were able to compile it with your standalone g++ compiler (which is apparently a much later version), but were unable to compile it in Arduino IDE.
It means that if you really want this non-standard code to compile in the current version of Arduino IDE, you have to place it into a .c file. Or just specify the array size explicitly.

Thanks for the link to godbolt. I tried a few things and it goes wrong very fast. For example adding a variable to the struct after the flexible array, or with an array of structs. Some things work with gcc version 6, but not with 8 or 9. The sizeof() does not include the flexible array member. And so on.

@Jot: Flexible array member is naturally supposed to be the last field of the struct. Yes, sizeof does not take it into account. Flexible array members are intended to provide support for the good old "struct hack" (http://c-faq.com/struct/structhack.html) and the fact that sizeof ignores this member makes it easier to calculate the proper size for malloc.

Maybe you've compiled it in g++ without any warnings enabled (or maybe it yeld warnings but was compiled). The arduino uses flags to consider all warnings as an error, so it won't compile. It may wary for different platforms, I've got -fpermissive used (and I don't like it at all).
That's because size of struct must be known compile time and if you provide char variable[]; you'll get zero sized array. Therefore anything biiger than nothing you'll try to initialize for is too long.
Maybe you're looking for something like this:
struct test {
  int a;
  const char * ptr;
};

test paramx {1, "some string"};
test paramy {2, "another string"};

test array[] = {{3,"three"}, {4, "four"}, {5,"five"}};

char variable[]; is not a zero-sized array. It is a flexible array. In standard C its size depends on how much memory was allocated by the user for the whole struct object. And in extended GNU-C the extra memory can be requested the way the OP requests it: by using an {} initializer. As far as GNU-C is concerned, the code is perfectly fine.

And it works like it's zero size array pointing after the end of struct, so you have to allocate more than sizeof(struct) to use it without "buffer overflow". But as it was noted, it can't work on statically allocated struct instance. And in C++ it has to be struct containing POD's only.

Well, it can't work for non-dynamic struct object in pedantic standard C. But the OP is apparently not trying to use pedantic standard C. And yes, it can and will work in extended GNU-C (and in GNU-C++ after version 6 of the compiler). The original code is perfectly fine as far as GNU-extended versions of these languages are concerned. The code will compile and work as intended in Arduino IDE once it is placed into a .c file, as I clearly stated in my answer. Once Arduino IDE moves to a later version of AVR-GCC, this code will compile and work as intended right away.

Hower I'm not sure he really wanted to use FAM. It might be just coincidence. Maybe he wanted just  const char * variable; That should be perfectly legal in this case (or flash string helpers / progmem pointers)

The title of the question seems to suggest that the OP did actually want to use a variable-size struct. Whether they meant it literally, as a reference to this specific language feature - I don't know.

@AnT True. Btw, it seems to be working with using malloc anyways. He just cannot use that initialization, because it takes it as zero lenght array. And strcpy must be used to copy strings on it's place.

Well, once again: in GNU C you can use this initialization. It is a specific feature of GCC compiler. It does set aside the proper (flexible) amount of static memory for struct object and it does work as if the initializing string was properly placed the into the trailing array. sizeof for the struct will ignore the [] array, but the elements will be properly accessible (and modifiable).


text:
How to use PROGMEM in a .h/.cpp file instead of a .ino file?
I want to use a lot of .h/.cpp files to be used by my ino sketch.
In one of these .cpp files (and later more) I want to use constant arrays (like lookup tables). To save SRAM I want to use PROGMEM.
What worked before in the Ino sketch is:
const uint8_t _red[]   PROGMEM = { 0, 9, 10, 220, 230, 240, 255 };

But when I put the line above in a .h or .cpp file I get the error:
Par.h:13:25: error: expected initializer before 'PROGMEM'

Should I include something or can't I use PROGMEM in a .h/.cpp file?

I already found the answer.
Include:
#include <avr/pgmspace.h>

Update
See also remark of AnT, which is a more generic (and in most cases better solution):
#include "Arduino.h"

(just to help others with the same problem).

... that is If you have a reason not to include <Arduino.h>. But if you do include <Arduino.h>, then <avr/pgmspace.h> is included with it anyway.

@AnT Thanks for that remark; I added it to the solution (I really thought I tried it before and didn't work, but it does).


text:
Send file from ESP to server via FTP
I've a code which records sound to SD, then starts an FTP connection for a limited time. I want to make an automatic system which records then sends the sound file continuously. Now I'm recording sound for 3s, then opening a FTP connection for 3s. In that 3s interval, my python code (PC) is trying to download the data in ESP (it also runs continuously. However, sometimes if ftp time is not enough, my connection is interrupting and ESP is resetting itself. So, I dont want to fetch this file via my computer, ESP32 should send this file after the recording, then it should start recording after the successful connection. I couldn't configured the code in the Arduino Playground
I pasted my code below, waiting for suggestions for valid examples.
You can find the libraries here
#include <WiFi.h>
#include <WiFiClient.h>
#include "ESP32FtpServer.h"
#include <FS.h>
#include <SD.h>
#include "Wav.h"
#include "I2S.h"

const int record_time = 3;  // second
const char filename[] = "/sound.wav";
const int headerSize = 44;
const int waveDataSize = record_time * 88000;
const int numCommunicationData = 8000;
const int numPartWavData = numCommunicationData / 4;
byte header[headerSize];
char communicationData[numCommunicationData];
char partWavData[numPartWavData];
unsigned long starttime;
unsigned long endtime;
File file;

const char* ssid = "*****";
const char* password = "*****";

FtpServer ftpSrv;   //set #define FTP_DEBUG in ESP32FtpServer.h to see ftp verbose on serial

void setup(void) {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /////FTP Setup, ensure SD is started before ftp;  /////////
  if (SD.begin()) {
    Serial.println("SD opened");
    ftpSrv.begin("esp32", "esp32");   //username, password for ftp.  set ports in ESP32FtpServer.h  (default 21, 50009 for PASV)
  }
  CreateWavHeader(header, waveDataSize);

}

void loop(void) {

  SD.remove(filename);
  file = SD.open(filename, FILE_WRITE);
  if (!file) return;
  Serial.println("recording");
  file.write(header, headerSize);
  I2S_Init(I2S_MODE_RX, I2S_BITS_PER_SAMPLE_32BIT);
  for (int j = 0; j < waveDataSize / numPartWavData; ++j) {
    I2S_Read(communicationData, numCommunicationData);
    for (int i = 0; i < numCommunicationData / 8; ++i) {
      partWavData[2 * i] = communicationData[8 * i + 2];
      partWavData[2 * i + 1] = communicationData[8 * i + 3];
    }
    file.write((const byte*)partWavData, numPartWavData);
  }
  file.close();

  Serial.println("recording finished, ftp starting");

  starttime = millis();
  endtime = starttime;
  while ((endtime - starttime) <= 3000) // do this loop for up to 1000mS
  {
    ftpSrv.handleFTP();        //make sure in loop you call handleFTP()!!
    endtime = millis();
  }
  Serial.println("ftp finished");

}

Your code does not compile. Please edit your question and ensure all of the relevant includes are in the sketch.

@VE7JRO edited the question

you need to wait on the FTP to finish before moving on

@dandavis ftp transfer is handling by pc and its time changes in every connection, if connection is slow, it could take 15s or more, however esp opens tunnel without knowing this time. how can I adjust it? best option is sending file from esp with a code

What protocols are available to you on the server? Only FTP? is there HTTP for example? any others? Seems FTP isn't suited to the solution

@JaromandaX HTTP is also ok, but I always worked on FTP. How FTP is not suitable for file transfer anyway? In the code ftpSrv.handleFTP();  line starts FTP. However, it should not only start FTP, it should also transfer the file itself in the loop, then everything will be okay. Arduino Playground example is capable to do it I guess, but I couldn't configure it for ESP.

I said it SEEMS it isn't, according to your question


text:
Cannot connect through /dev/ttyACM0 (Ubuntu 18.04)
I am using an Arduino UNO which worked fine until today. My system: Ubuntu 18.04
Now, the IDE can no longer connect to it:

Cannot do any sketch upload
Cannot ask for board info
No USB ports shown in tools --> port (only 2 serial ports shown)
ttyyACM0 not showing up in /dev

However, both lsusb and dmesg show that the board is recognized somehow.
lsusb output:
Bus 001 Device 012: ID 03eb:2fef Atmel Corp.
dmesg output:
[ 2922.171042] usb 1-1.3: new full-speed USB device number 12 using ehci-pci
[ 2922.282047] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
[ 2922.282052] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0

The problem is the same on 2 different computers, which leads me to suspect that there is something wrong with the board. Is it possible that a board be shown by both dmesg and lsusb and still be malfunctioning ?

problem with 16u2 firmware?

The board was bad. I just replaced it and it now works.
So, to answer my own question, an Arduino board can show up on lsusb and dmesg and yet be faulty. This is what the dmesg output is for a healthy board:
[10492.388028] usb 1-1.4: new full-speed USB device number 13 using ehci-pci
[10492.500520] usb 1-1.4: New USB device found, idVendor=2341, idProduct=0043
[10492.500526] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[10492.500529] usb 1-1.4: Manufacturer: Arduino (www.arduino.cc)
[10492.500533] usb 1-1.4: SerialNumber: 55736323739351010292
[10492.520354] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device
[10492.520832] usbcore: registered new interface driver cdc_acm
[10492.520835] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

And here is the lsusb output:
Bus 001 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

Judging on the difference with the previous outputs from both commands (when the faulty board was connected), it seems that my board had reverted to the basic Atmel USB interface and that the Arduino specific USB handshake was not working. Can anyone confirm ?

the USB interface on Uno is an ATmega 8u4 or 16u4. it is an AVR MCU with native USB port programmed to send data to the main MCU of the board (328p). if the firmware in 16u4 is corrupted the native USB port connects but the virtual serial port is not created https://www.arduino.cc/en/Hacking/DFUProgramming8U2


text:
NRF24L01+ Getting Started Acknowledge Failed
I have followed numerous guides and tutorials for getting the NRF24L01+ modules working with an Arduino Uno. I have swapped to a genuine Arduino and tried 4 different NRF modules. All without luck.
I am trying to get the most basic example from Simple nRF24L01+ 2.4GHz transceiver demo to work.
Hardware Connections:

Simple TX Test Code:
// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    radio.stopListening();
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);

    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}

Serial monitor:

Using radio.printDetails( ); returns:

Please let me know what I'm missing.

Can you please upload the unmodified PingPair example and see if that works?

Where is the code for the receiving side? If there is no receiver, the sender won't get an ACK packet back, and you get the TX failed error message.

What is this: uint8_t slaveAddress[5] = {0xF0F0F0F0A1LL, 0XF0F0F0F0B1LL, 0XF0F0F0F0C1LL, 0XF0F0F0F0D1LL, 0XF0F0F0F0E1LL};? How do you expect such large values to fit into uint8_t??? The compiler will interpret this as uint8_t slaveAddress[5] = {0xA1, 0xB1, 0xC1, 0xD1, 0xE1};. Is this what you wanted? I'd guess not. Also, take a look here https://github.com/nRF24/RF24/blob/master/RF24.h#L246 how the address is supposed to be formed.

@AnT I was trying the same as 1 of the answers here: https://arduino.stackexchange.com/questions/65249/nrf24l01-tmrh20-library-receiver-gets-blank-data before you commented there as well. Thank you, have updated the question and code.

Thank you all so much. Not sure why I was expecting the radio.write function to return True without a receiving end. It's working.

How did you get RF_CH=0x76?  That's not the default radio channel on power up, so are you not showing the complete version of the code?

The Arduinos 3V3 does not privide enough current. To eliminate this as a source of your problem you can use a ceramic capacitor of 100µF across VCC and GND pins of the nRF24L01+ module or buy a 5V to 3V3 step down converter specially made for nRF24L01.


text:
Modifying NMEA of Adafruit GPS
I use a Adafruit Ultimate GPS Breakout - 66 channel w/10 Hz updates to collect data on animal movement.
I have two questions regarding the produced NMEA:
- there are some information about PGACK, PMTK that are produced in the code that I don't need. Do you know a way of not including it?
- I'd like to add some information in the NMEA line, but when I do it, it creates a space between the NMEA and the new information that do not allow me to process it correctly then in Excel or R. This is the information I've added:
fichier.print(buffer);
fichier.print(",");
fichier.print(GPS.hour, DEC);
fichier.print(':');
fichier.print(GPS.minute, DEC);
fichier.print(':');
fichier.print(GPS.seconds, DEC);
fichier.print(",");
fichier.print(GPS.day, DEC); fichier.print('/');
fichier.print(GPS.month, DEC); fichier.print("/20");
fichier.print(GPS.year, DEC);
fichier.print(",");
fichier.println(j);
fichier.close();
acquisition = true;

show us the output now and how it should be, not sure what "produced NMEA" means

please explain what this means ... do not allow me to process it correctly