text:
How can I handle six SoftwareSerial ports for six Nova SDS011 Air Quality Sensors on Arduino MEGA?
First of all, thank you in advance.
I'm trying to connect six Nova SDS011 Air Quality Sensor (sensor specifications here) to an Arduino MEGA. I'm using the Nova Fitness Sds dust sensors library which relys on the SoftwareSerial library. As fas as I know, SoftwareSerial can handle a virtual serial port on any digital pin (with some limitations as seen on Arduino reference), but I don't know whether there is any limit on the number of ports that it can handle.
I have communicated successfully with four of them which are conected to the pins:

RX
TX
Sensor

13
12
1

10
11
2

51
50
3

53
52
4

XX
XX
5

XX
XX
6

The two sensors left (5 and 6) have been tested on the Arduino remaining free pins, but it couldn't listen to the ports. I checked if all sensors worked propperly separatedly, and they do, so I can dischart that the problem is related with a faulty sensor. The pins for the serial ports have been declared (for each sensor) as:
// Sensor 1
const uint8_t rxPin1 = 13;  // Brown wire
const uint8_t txPin1 = 12;  // Violet wire
SoftwareSerial sensor1(rxPin1, txPin1);
SdsDustSensor dust_sensor_1(sensor1);

As I have seen on Arduino Reference, I must use the .listen() and .isListening() functions in order to listen to a specific port:
void setup() {
  Serial.begin(9600);
  Serial.println("===========================================");

  // SDS sensors configuration
  dust_sensor_1.begin();
  dust_sensor_2.begin();
  dust_sensor_3.begin();
  dust_sensor_4.begin();
  dust_sensor_5.begin();
  dust_sensor_6.begin();

  sensor1.listen();
  dust_sensor_1.wakeup();
  delay(100);
  if (sensor1.isListening()) {
    dust_sensor_1.setQueryReportingMode();
    String status_mode_1 = dust_sensor_1.setQueryReportingMode().toString();
    while (!status_query.equals(status_mode_1)) {
      dust_sensor_1.setQueryReportingMode();
      status_mode_1 = dust_sensor_1.setQueryReportingMode().toString();
      Serial.print("Sensor 1 mode >> "); Serial.println(status_mode_1);
    }
    Serial.print("Sensor 1 mode >> "); Serial.println(status_mode_1);
  }
  dust_sensor_1.sleep();

  delay(1000);

  // Next sensors
}

The code from above is the same for each sensor, but I have condensed the whole setup() code in just one sensor.
If that code has worked for four sensors, it isn't strange to think that the same code should work for six too. I'm completely stuck at this point and I don't know what I should do. I will not write the loop() code untill the setup() works fine.
At last, when all problems will have been solved and the sensors will tested, I will swap the code into a state machine for a better performance. I will also change some variables that could be joined into a single variable (such as String status_mode_1 which can be just String status_mode; it can be shared with all sensors).
If you happen to need the whole code, please ask for it and then i'll post it.

What pins have you tried for the remaining sensors? Unrelated, but the code would be incrementally easier to reason about if the ports/sensors were stored in an array (and I'd recommend using only a singleNamingConvention).

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

@DaveNewton I have tried all of the remaining digital and analog pins. Regarding the array, I hadn't thought about it and yes, I should use singleNamingConvention, sorry. Juraj, I have seen that info on Arduino Reference web, and I tried all those pins at first, and only worked (for me) 10, 11, 12, 13, 50, 51, 52 and 53, the ones I wrote on the table.

Off the top of my head can't think of anything obvious. Have you tried a simple sketch with a single sensor on one of the available pins you haven't tried? (Another reason having the ports/sensors in an array is that it's much easier to make changes like that :)

I have tried with just one sensor, but with an Arduino UNO. I'll try what you say and I'll edit this comment ASAP.

TX pin can be any pin. only RX pins must support pin interrupt

I have just tried with one sensor using random pins and the specific, as @Juraj sugested. If I use digital pins it seems it works fine, but if I use an analog pin (A8, for instance) it looks it takes some more time to do the task. The behaviour is the same with the six sensors, on analog pins it seems it takes some more time. Yesterday I also tried with all free pins for TX and RX, and it didn't work; maybe, I was declaring a variable wrong, I don't know. I had already worked with SoftwareSerial, but with less sensors. Anyway, it seems it works now and I thank all of you ;)


text:
Same structure taking different memory space on Uno and NodeMCU ESP8266, leading to data corruption when transferring via nRF24L01+
I'm trying to transfer data between a Arduino Uno board to a NodeMCU ESP8266 board, using nRF24L01+ transceivers module and RF24 library on both side. The data I'm transferring are stored in a struct defined this way:
// Struct declared in both code
struct sensorData {
    bool doorOpened;
    int light;
    int temperature;
    int humidity;
    float voltage_battery;
};
// Variable in Uno code (source node)
sensorData dataToSend;
// Variable in ESP8266 code (dest node)
sensorData dataToReceive;

But the data are not transferred properly between the two boards and I get random values or 0 when trying to display them from ESP8266 (values are correctly displayed from Uno).
Display in Uno (using signed short as data type, see following paragraphs):

Display in ESP8266 (using signed short as data type, see following paragraphs):

After some testing, I found out that memory-allocation on both boards are different, as Uno takes 2 bytes to store int while ESP8266 takes 4 bytes. Moreover, sensorData takes 11 bytes of memory on Uno (1 for bool, 2 for int and 4 for float, which sums up to 11 bytes), but takes 20 bytes of memory on ESP8266 (1 for bool, 4 for int and 4 for float, which does NOT sum up to 20 !).
Trying to solve this, I tried changing int for signed int, byte, short, signed short but the transmission problem remains. When using short or signed short (which takes 2 bytes on both boards), my structure sensorData still takes 11 bytes of memory on UNO while it takes 12 bytes of memory on ESP8266. For some reason, ESP8266 always takes more space than needed to store sensorData, probably causing bits to be wrongly placed when receiving data.
I'm sure that both boards, radio module and transmission protocol work as I successfully tested the same code with a smaller struct (text was "Hello World !" and cmp was increased at each transmission):
struct Package {
    char text[16];
    long cmp;
};

Does anyone have faced this issue before ? How could I solve that ?

By the way, I'm used to coding (VBA, C++ and python mostly) but I'm still new to the Arduino world, so I might be missing something obvious here.

There are three main issues you may need to deal with when passing structures between systems that use different processors.
The first is that data types vary in size between architectures. You can avoid this for integers by avoiding the basic C types and instead using the fixed size types from stdint.h/cstdint. For floating point types this is less of a problem as most systems use the IEEE single and double precision types for float and double.
The second is padding, according to the C standard padding is implementation dependent. In practice most compilers will insert the minimum amount of padding needed to meet alignment requirements. Exactly what the alignment requirements are also depend on the implementation, but the alignment requirement of a type is always a factor of it's size.
You can thus avoid compiler-generated padding on most architectures by designing your structure to place types on "natural" alignment (that is their offset in the structure is a multiple of their size) and to have a size that is a multiple of the largest type in the structure. So you might design your structure as.
struct sensorData {
    int8_t doorOpened; //size 1 offset 0
    int8_t spare; //size 1 offset 1
    int16_t light; //size 2 offset 2
    int16_t temperature; //size 2 offset 4
    int16_t humidity; // size 2 offset 6
    float voltage_battery; //size 4 offset 8
};

Another option is to use packed structures, but extreme care is needed when using such, especially in C++. It is easy to create unaligned pointers or references.
The final issue is byte order (also known as endian), if your systems use different byte orders for integer or floating point values you will need to insert conversions to deal with this.

Interesting. Do you have an example of a non-aligned struct, please? Would it be something like a float after an int16_t, so size 4 offset 2?

@EricDuminil Anything that breaks natural alignment, uint8/uint16/uint8 breaks that because the uint16 isn't aligned to a 16-bit boundary.

int, long, etc have different sizes depended on the compiler and target.
Use explicit sizes to make sure you're variables have the size you want. Eg. uint8_t, int16_t or int32_t, ... (as @Mat commented)
Also, I wouldn't use bool (if writing in C) as it's not really standard in C and the size is also implementation dependent: https://stackoverflow.com/questions/1608318/is-bool-a-native-c-type
Extra, there are different types of explicit sizes: https://stackoverflow.com/questions/5254051/the-difference-of-int8-t-int-least8-t-and-int-fast8-t
(but don't use it here otherwise you'll have again the same problem :))

"bool" is fine in general; we're discussimg C++. The issue with "bool" is that its size is implementation-dependent.

@DaveNewton I did not know we were talking C++. I'll leave it in my answer though

Thank you for the explanation and links, they are quite useful ! I never had this issue before so I didn't pay attention to explicity sizes, but I will from now on.

@Swedgin That's what the Arduino ecosystem uses.

@DaveNewton My bad, it's been so long since I used the Arduino ecosystem that I forgot it was C++.

In addition to the rule of always using fixed and predictable sizes across different architectures, it's also a good idea to pack your structs. This prevents the compiler from padding smaller variables with blanks to align them with the architecture's word boundary when needed.  For example:
struct Package {
    uint8_t doorOpened;
    uint16_t light;
    int16_t temperature;
    uint8_t humidity;
    float voltage_battery;
} __attribute__((packed));

Depending on what "bytewise access" instructions are available on your target 32-bit architecture, without the packing you may end up with (worst case) the equivalent of:
struct Package {
    uint8_t doorOpened;
    // 3 bytes padding
    uint16_t light;
    // 2 bytes padding
    int16_t temperature;
    // 2 bytes padding
    uint8_t humidity;
    // 3 bytes padding
    float voltage_battery;
} __attribute__((packed));

Of course there may be a granular enough access method in the architecture which means the packing is irrelevant - but it's better to have it and it be ignored than to not have it and need it.

@Vincent Yes, it can cause a problem. But either it causes problems or it doesn't, so you can just try it. You can also add your own padding

I wasn't aware that "using a pointer to a variable" was a "stupid thing"?

The esp8266 has a 32 bit mcu and the uno an 8 bit mcu so their variables have different storage requirements. You need to allow for this in your code.

How can I do that ? Should I format the source data to be properly understood when received by ESP8266 ?

Declaring signed short doorOpened instead of bool doorOpened fixed the issue (as both have 2 byte size), but if you have time I'm still curious about properly handling a bool between the 2 MCU.

Use types with explicit sizes (uint8_t, uint16_t etc).

Note particularly that int is 16 bits on Arduino Uno, but 32 bits on ESP8266.

@PMF I noticed that, which is why I changed int to short (16 bits on both MCU).

For all the reasons mentioned in the other answers (different types sizes, alignment requirements and endianness), it's often a bad idea to use structs for data that needs to be sent/received (be it over the network or stored in files), as interoperability is often a problem.
Using a plain array of bytes (i.e. uint8_t[]) is often a much better solution, together with functions to read/write data with specific types at specific offsets.
In many higher-level languages (perl, php, python...) this is often done using pack/unpack or equivalents, but as far as I know there is no direct equivalent in C.
You then end up using temporary variables, htons/ntohs/htonl/ntohl and memcpy to copy data between the temporary variables and the transmit buffer. Floats are a bit more tricky because even though their format is well defined, they endianness is not, and may not be the same as integers, but htonf/ntohf are rare. In your case, I would recommend converting to integers with a factor of 10 (if you need one digit) or 100 (if you need 2) for instance.
If you're using C++ you could consider using Google's Protocol buffers

source: Stack Exchange

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

sort: votes


text:
How to correctly measure the duty from an interrupt that is used for counting
Trying to get the duty cycle % from an input (pin27) on my ESP32 that is currently used for analog input to read out the voltage provided by a GM driver.
Anybody has an idea on how could I achieve this?

Used controller: https://heltec.org/project/wifi-kit-32/
Used HV driver: https://rhelectronics.net/store/high-voltage-400v-geiger-tube-driver-two-channels-with-signal-buffer-for-muon-cosmic-ray-coincidence-detector.html

Thanks!

You could enable the external interrupt for that pin, triggering on rising and falling edge. Keep tabs on what's in the timer's register on each interrupt and you can calculate the frequency and duty cycle.

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


text:
Arduino nano BLE sense Serial port Suddenly stopped working
Last week I got my new Arduino nanao ble sense. Today I was executing a code on it which reads every sensor data on it and print it on serial monitor. I changed some parameters in my code and upload my code, while the code was uploading I opened the serial monitor and code was fully uploaded. Suddenly i got an error on terminal saying cannot find upload port. After that my Arduino board was never detected by the system. I tried to $lsusb to check whether the device is mounted on usb port but it didn't show up.... I tried on different PC and even that not detected... Plzz let me know if my hardware is damaged in someway? OR is there a solution to this???

All that has happened is that you don't have a sketch running. When you have a board with a native USB connection a sketch has to be running to make that USB connection be anything.
You corrupted your sketch, so it's not executing.
All you need to do is manually trigger the bootloader to install a new sketch. According to the "Getting started" page:

NOTE: If the board does not enter the upload mode, please do a double press on the reset button before the upload process is initiated; the orange LED should slowly fade in and out to show that the board is waiting for the upload.

Reset? Power cycle?

@JRobert Looks like double-reset.

@Majenko How do I manually trigger the bootloader for Arduino nano BLE can't find any thing about on get started page or any other place. BTW thanks for Answering!!!

@TauhidKhan I told you how in my answer - copied and pasted from the getting started page here: https://www.arduino.cc/en/Guide/NANO33BLESense#upload-the-program - look under "Upload the program" in the block in italics.  Press the reset button twice.


text:
accelstepper continuous rotation with forward and backward control
I am using Uno and the A4988 driver with nema17 motor and finally the Accelstepper, I want to make the motor run endlessly in a direction, but when I press a button I want it to stop and run in the other direction also endlessly until I push the button again, here is my code:
// Include the AccelStepper Library
#include <AccelStepper.h>

// Define pin connections
const int dirPin = 2;
const int stepPin = 3;
const int dirButton = 8;
int potPin = 0;

int buttonState = 0;

// Define motor interface type
#define motorInterfaceType 1

// Creates an instance
AccelStepper myStepper(motorInterfaceType, stepPin, dirPin);

void setup() {
  pinMode(dirPin, OUTPUT);
  pinMode(dirButton, INPUT_PULLUP);
  myStepper.setMaxSpeed(500);
  Serial.begin(9600);
}

void loop() {
  int speed = analogRead(potPin)/4;
  myStepper.setSpeed(speed);
  digitalWrite(dirPin,LOW);
  buttonState = digitalRead(dirButton);

  if(buttonState = 0){

  }

  Serial.print(buttonState);
  delay(5);
  myStepper.run();
}

so the question is what should i put inside the :
if(buttonState = 0){

}

to make it switch direction?
I tried countless examples from the internet but the motor never changes direction.
thanks

direction = ! direction;

buttonState = 0 is an assignments, sets button state to zero and the expression itself evaluates to zero. So your if condition is always false. Use == for comparison.


text:
Trying to use I2C accelerometer and SPI OLED
I'm trying to stream the data coming from my I2C MMA8452Q accelerometer to an Adafruit-based SSD1351 OLED RGB display that uses SPI via an Arduino UNO.
When I run example code for the accelerometer I can see it outputting data to the serial monitor, and when I run my code for the screen using a joystick as test input it graphs the values nicely.
When I try and build in the I2C example code into my code for the display, the moment I include to the code to read the values from the accelerometer, the program runs setup and then goes blank after that. When I block out the sensor read and swap in the joystick reads it works fine again.
I've been staring at all kinds of forum posts about using SPI and I2C simultaneously but I haven't really found any with a straightforward solution or they use a very different board.
#include <Adafruit_SSD1351.h>
#include <SparkFun_MMA8452Q.h>
#include <SPI.h>
#include <Wire.h>

#define SCREEN_WIDTH  128
#define SCREEN_HEIGHT 128 // Change this to 96 for 1.27" OLED.

// You can use any (4 or) 5 pins
#define SCLK_PIN 2  // not using this as I've got it setup
#define MOSI_PIN 3  // on the hardware SPI pins as per the text below
#define DC_PIN   4
#define CS_PIN   5
#define RST_PIN  6  // not in use

#define joy_XPin A1
#define joy_YPin A0

// Color definitions
#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

// Option 1: use any pins but a little slower
// Adafruit_SSD1351 tft = Adafruit_SSD1351(SCREEN_WIDTH, SCREEN_HEIGHT, CS_PIN, DC_PIN, MOSI_PIN, SCLK_PIN, RST_PIN);

// Option 2: must use the hardware SPI pins
// (for UNO thats sclk = 13 and sid(which is SDA on my display) = 11) and pin 10 must be
// an output. This is much faster - also required if you want
// to use the microSD card (see the image drawing example)
Adafruit_SSD1351 tft = Adafruit_SSD1351(SCREEN_WIDTH, SCREEN_HEIGHT, &SPI, CS_PIN, DC_PIN, RST_PIN);

MMA8452Q accel; // intialise sensor - SDA/SCL connected to A4/A5 pins as per example code

#define graphLength 32

int joy_X, joy_Y;
int tilt_X, tilt_Y;

int graphY[graphLength] = {0};
int graphX[graphLength] = {0};

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

  tft.fillScreen(BLACK);

  tft.setCursor(10,64);
  tft.setTextColor(WHITE);
  tft.println("Welcome, have fun");

  delay(2000);
  tft.fillScreen(BLACK);
}

void loop() {

  // scaled inputs to be smaller and offset to be in the middle of the screen
  joy_X = (analogRead(joy_XPin) / 32)+48;
  joy_Y = (analogRead(joy_YPin) / 32)+48;

  // when this block is included everything breaks
  // this is the code to read the accelerometer input so I'm pretty sure the issue is here.
  /*
  if(accel.available()){
    tilt_X = accel.getCalculatedX() * 10;
    tilt_Y = accel.getCalculatedY()* 10;
  }
  */

  graphY[graphLength - 1] = tilt_X; // swap tilt_X/Y with joy_X/Y to graph joystick inputs
  graphX[graphLength - 1] = tilt_Y;
  for(int i = 0; i <= (graphLength - 1); i++){  // invokes undefined behaviour but it works for now
    tft.drawPixel(i,graphY[i],RED);
    tft.drawPixel(i,graphX[i],BLUE);
  }

  delay(5);
  graphShiftAlong();
}

// Just functions to clear the things I've drawn on the display rather than trying to wipe the whole display each time.

void clearPixel(uint16_t x, uint16_t y){
  tft.drawPixel(x, y, BLACK);
}

void drawRect(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color){
  int x1,y1,x2,y2;
  w = w/2;
  h = h/2;

  x1 = x - w;
  y1 = y - h;
  x2 = x + w;
  y2 = y + h;

  tft.drawLine(x1,y1,x1,y2,color); // top left to bottom left
  tft.drawLine(x1,y1,x2,y1,color); // top left to top right
  tft.drawLine(x2,y1,x2,y2,color); // top right to bottom right
  tft.drawLine(x2,y2,x1,y2,color); // bottom right to bottom left
}

void clearRect(uint16_t x, uint16_t y, uint16_t w, uint16_t h){
  drawRect(x,y,w,h,BLACK);
}

// Sets the 'old' data to be drawn as black and redraws it one pixel offset
// Compiler gives me red text but not errors so I'm running with it for now
void graphShiftAlong(){
  for(int i = 0; i <= (graphLength - 1); i++){
    tft.drawPixel(i,graphY[i],BLACK);
    tft.drawPixel(i,graphX[i],BLACK);
    graphX[i] = graphX[i+1];
    graphY[i] = graphY[i+1];
  }
}

The example code I'm using for the sensor is here:
  Library for the MMA8452Q
  By: Jim Lindblom and Andrea DeVore
  SparkFun Electronics

  Do you like this library? Help support SparkFun. Buy a board!
  https://www.sparkfun.com/products/14587

  This sketch uses the SparkFun_MMA8452Q library to initialize
  the accelerometer and stream calcuated x, y, z, acceleration
  values from it (in g units).

  Hardware hookup:
  Arduino --------------- MMA8452Q Breakout
    3.3V  ---------------     3.3V
    GND   ---------------     GND
  SDA (A4) --\/330 Ohm\/--    SDA
  SCL (A5) --\/330 Ohm\/--    SCL

  The MMA8452Q is a 3.3V max sensor, so you'll need to do some
  level-shifting between the Arduino and the breakout. Series
  resistors on the SDA and SCL lines should do the trick.

  License: This code is public domain, but if you see me
  (or any other SparkFun employee) at the local, and you've
  found our code helpful, please buy us a round (Beerware
  license).

  Distributed as is; no warrenty given.
*/

#include <Wire.h>                 // Must include Wire library for I2C
#include "SparkFun_MMA8452Q.h"    // Click here to get the library: http://librarymanager/All#SparkFun_MMA8452Q

MMA8452Q accel;                   // create instance of the MMA8452 class

void setup() {
  Serial.begin(9600);
  Serial.println("MMA8452Q Basic Reading Code!");
  Wire.begin();

  if (accel.begin() == false) {
    Serial.println("Not Connected. Please check connections and read the hookup guide.");
    while (1);
  }
}

void loop() {
  if (accel.available()) {      // Wait for new data from accelerometer
    // Acceleration of x, y, and z directions in g units
    Serial.print(accel.getCalculatedX(), 3);
    Serial.print("\t");
    Serial.print(accel.getCalculatedY(), 3);
    Serial.print("\t");
    Serial.print(accel.getCalculatedZ(), 3);
    Serial.println();
  }
}

Your SPI is not setup for the Arduino UNO. Check another example for SPI and you will be using pins 11 and 13, this is mandatory and 8,9,10 or any three and there is a definition statement for these 3 pins - look at the example for your display.
For I2C do you have pullup resistors on both I2C lines 4.7k up to 10k? These are required.
Good luck

Sorry I should have clarified a bit more than what is in the code, I am using pins 11 and 13 for SPI, ignoring the setup defined early in the code. There are two declaration statements for the display - one uses any combination of pins for the display and the other uses 11 and 13 plus the other three.
As for the pullup resistors, no I haven't put those in. However I did think that if the sensor worked when its own example code was run (even without the resistors) that it should run in conjunction with the display. Or is there some interference I am missing?


text:
How to pass Strem object to my class
I'm trying to creaper class wraper to use an Streamobject but I've an error when I try to compile.
My .hfile :
#include <Arduino.h>

class TestSerialListener {
public:
  TestSerialListener(Stream &serial);
  void testPrint(void);
private:
  bool _listener_start;
  Stream &_serial;

  void startListener(void);

};

my cppfile
#include "TestSerialListener.h"
#include <Arduino.h>

TestSerialListener::TestSerialListener(Stream &serial) : _serial(serial)
{
}

void TestSerialListener::testPrint(){
    _serial.begin(115200);      <---------- error compilation
    _serial.println("test");
}

void TestSerialListener::startListener(void)
{
    if(!_listener_start){
        _listener_start = true;
    }
}

And when i try to compile it I got this error : error: 'class Stream' has no member named 'begin'Why I can't use begin()in my classe ?

The compiler said: “you can't because the Stream class has no method named begin”. Does this answer your question?

Ok but why I can do SerialUSB.begin(115200)in my sketch ? @EdgarBonet

Because, SerialUSB does have a method named begin. Some Stream-derived classes can have such a method, It's just not something you can expect from any Stream object.

see https://arduino.stackexchange.com/questions/78719/can-you-use-serial-port-as-a-variable/78725#78725

the begin() method is defined in the HardwareSerial class, not in Stream. You can look that up yourself in your Arduino installation. For me these files are placed under ~/.arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino/ and are named Stream.h and HardwareSerial.h.
And if you  think about it, this is quite logical. The Stream class can represent any object, that can stream data. It doesn't know anything about how exactly the data is streamed on a hardware level. It just provides the convenient functions for handling the data. The HardwareSerial class then derives from Stream to get those data handling methods and adds its own methods to handle the hardware side of the problem, including setting a baudrate.
When providing a Stream reference to a class constructor you want to begin() the corresponding object outside of the class, before you start to stream any data through it. Doing it this way makes your class widely usable, since you could use any Stream object, even a file on an SD card.
So move the begin() line from your class to the setup() function in your main code.

For reference: Juraj showed the inheritance between the classes in his answer to this question. Have a look at it, since it is quite enlightening.


text:
Where to store AES key on Arduino board
I'm working with this library AES lib so everything works I can encrypt/decrypt data. But now I'd like to know what is the best way to store my aes private key ? My boars is a personnal board build with an samd21 cortex M0+ my board doesn't have the possibility to connect with the extern world, like ethernet or ble, wifi.
I've only one possibility is to store the key in my program but what is the best way? Obfuscate my key? I know there is no perfect and secure solution if my key is store in my program, but what is the best solution ? Maybe is it possible to put my key when I upload my sketch in compiler option and store it in emulate eeprom?

I'm no expert in samd controllers, but I don't think it makes any difference for security if you store in program space or EEPROM (especially emulated)

@chrisl Yes sure you've right, but I'am little bit lost, about how/where to store my private key

For program space you could just write in as a variable in your code (you can even put it in a different file than the main code and include that file).

@chrisl Yes but if I write my key in a variable, it would be easy after a disassembly to get my key no?

Just store it in your code as a "const" and turn on "code protection" in the chip's configuration bits.

Your key will be in the program space no matter what you do, so someone reading the program space would easily get it. Majenko is right with the code protection. Remove any bootloader and enable code protection, which prevents an attacker to read the program space. Though I'm not sure, how exactly this is done on samd controllers

what is being encrypted if there's no connection to the outside world?

@dandavis I encrypt data log about system in SD card

All you can really do with your key is to just store it in your code. It makes no difference if that is as a const variable or stashed in emulated EEPROM.
The real question is not how to store it but how to stop someone reading it. Most microcontrollers (and the SAMD21 is no exception) have "code protection" facilities - settings you can enable in the chip's configuration (or "fuse") bits to prevent the flash being read by any external debugger or programmer.  By enabling these bits (check the datasheet for your chip) you will prevent people being able to read the flash containing your key no matter how you store it.

Does enabled fuse prevent rewriting the flash using OTA where the new binary is downloaded and swapped with old one?

No idea. The datasheet should tell you if flash write is inhibited in software or not. Probably not.


text:
ESP32 WROOM32 SPI EMF issues
I'm trying to run Waveshare SSD1327 128x128 screen via SPI on ESP32 WROOM32 board. On ESP8266 (D1R1?) it works flawlessly while using HW SPI but when I run it on esp32, anything connected to mains which is sitting <50cm from screen will glitch it out completely. Even if I just hold in one hand phone charger cable connected to mains, and come close to screen with my other hand(at least 1m distance between hands), screen will instantly glitch and shut down.
I'm pretty sure this is not connection issue, since it works on ESP8266 and I even tried soldering wires directly to ESP32 board.
I am using VS Code PlatformIO and Arduino framework. I tried setting CPU freq to 40MHz by adding line to platformio.ini and calling setCpuFrequencyMhz(40); in my setup() function. I don't have oscilloscope to confirm that this actually happend. I read somewhere that this .ini thing didn't work.
I am using U8g2lib for screen which is using global SPI object. Even tho I bought screen from Waveshare I can't use WS implementation. MIDAS one is the only implementation which works for me.  Since my board doesn't have all VSPI pins, I had to set them manually in SPI.begin(...):
U8G2_SSD1327_MIDAS_128X128_F_4W_HW_SPI display(U8G2_R0, /* cs=*/ 39, /* dc=*/ 16, /* reset=*/ 2);
...
...
pinMode(39, OUTPUT);
pinMode(14, OUTPUT);
pinMode(13, OUTPUT);
pinMode(12, INPUT);

digitalWrite(39, LOW);
// sck, miso, mosi, ss
SPI.begin(14, 12, 13, 39);
display.begin();

BTW, SW SPI worked extremely slow for me(display.sendBuffer() takes about 1sec), on both ESP32 WROOM32 and ESP8266 D1R1 mini. Friend of mine is using ESP32 WROOVER board and even SW SPI is working for him great without any glitching.

I would suggest you check all of your ground and power connections. Also all unused ESP32 pins should be terminated. You can simply set them as outputs and turn them on to low.

Isn't gpio39 only an input? I am not sure that you can set it as output.

Problem was GPIO39 which is internally connected to a hall sensor... Once I changed CS to some other pin, everything started working...
Having pin cheatsheet would be really helpful in these situations.


text:
Atmel SAMD21 microcontroller not making a USB port anymore
My custom board with Atmel SAMD21 microcontroller (same as Arduino MKR Zero) is not making a USB port since yesterday. The board was working fine before that.
Please suggest ways to resolve this issue. What are the possible reasons for such an issue?
Since reset is equivalent to powering the board ON and OFF which has not resolved the issue, can burning the bootloader again help?
Further information:

The board seems fine. It powers ON and OFF in the usual manner.
This problem with the USB port connection happened while I was trying to upload the code.

The USB pin connections on the board have been checked as well as tested with different USB wires.
Appreciate your help.

Does this answer your question? Why is the IDE not able to find the board despite it being clearly seen and selected?

Press reset twice to activate the bootloader.

The custom board does not have a reset button. Is there another way to get into the bootloader mode? Also, there is a GPIO pin-out for reset pin. Will burning the bootloader again help with the problem?

A wire can do the job of a reset button.

Yes, this worked. Appreciate your help Majenko ! :)

Solutions to the problem:

External Hardware Reset -- using a reset button (that I externally managed to solder using the Reset pin-out) -- to get into bootloader mode and start the program from the beginning

Thanks Majenko, from the comments.

Burning bootloader again may also work (theoretically) - I have not tried and tested it.

For detailed understanding - follow this post - https://forum.arduino.cc/t/atmel-samd21-microcontroller-not-making-a-usb-port-anymore/882504/5

What are the possible reasons for such an issue?

I noticed that calling
Serial.begin(115200);
...
SerialUSB.begin(115200);

in the script can cause this.
See post Seeeduino XIAO stopped connecting - Enter Bootloader Mode is not working


text:
Using SAM4 series microcontroller with Arduino IDE
I am looking to use SAM4S series microcontroller by Atmel/Microchip and trying to program it using Arduino IDE.

Can I use the bootloader provided by Adafruit for Feather M4 Express [uses SAMD51]  or  Feather M4 Can Express [uses SAME51] both of which are ARM Cortex M4 based just like the SAM4S series?

If yes, how do I work around few different features such as different FLASH memory and RAM of my SAM4S16B IC compared to that of SAMD51 or SAME51?

Could you suggest any other ways for using SAM4S with Arduino IDE? I, personally, did not find any direct resources for the same.

Is it even possible to use SAM4S with Arduino IDE provided that I don't have to write my own bootloader or API's etc?

Appreciate your help in the matter.
Thank you.

If no one has written a SAM4 core for Arduino then no, you can't. If someone has, then the resources you need will be in that core and their respective website / repository.

As for "Can I use any old Arm M4 based code?" the answer is a vehement "no". Just cus the CPU is M4 doesn't make it the same chip. It's like old home computers. The C64 and BBC both used the 6502, but you won't run code for one on the other.

Thanks Majenko for all your insights. This really cleared a lot of things for me. No one has written for SAM4 so I guess I won't be able to use itwith Arduino just yet. Appreciate your help.

If you're feeling adventurous, clever, and have a lot of time on your hands, you could write and maintain your own SAM4 core :)

Haha, I don't feel any of those things at the moment xD. I think I would rather switch to SAMD51 or SAME51 ICs; both of which do have arduino support from adafruit and sparkfun. Thanks !


text:
Incorrect values arriving from Arduino to RPi over serial communication
I am trying to write four values relating to energy (current, power, energy, and peak demand) via a SoftwareSerial connection from my Arduino UNO to my Raspberry Pi 4.  However, two things are occurring:

All of the values should be different, but they are printing to the RPi terminal as if they're identical.

It seems as if the values I'm writing are merging together(?), creating a nonsense value.  For example, if the values that I'm sending are 0.24, 28, 0.05, and 71, they appear in the RPI terminal looking like this:

Current:  54543878
Power:  54543878
Energy:  54543878
Peak Power:  54543878
This is a snip of my Arduino code that writes to the Bluetooth serial connection (uses HC-06):
  bluetoothSerial.write(RMSCurrent);
  bluetoothSerial.write(RMSPower);
  bluetoothSerial.write(kilos);
  bluetoothSerial.write(peakPower);

This is a snip of the Python script that receives it:
while 1:
try:
    received_data = bluetoothSocket.recv(1024)
    RMSCurrent = int.from_bytes(received_data,byteorder='big')
    RMSPower = int.from_bytes(received_data,byteorder='big')
    kilos = int.from_bytes(received_data,byteorder='big')
    peakPower = int.from_bytes(received_data,byteorder='big')

    print("Current (A): %d" % RMSCurrent)
    print("Power (W): %d" % RMSPower)
    print("Energy (kWh): %d" % kilos)
    print("Peak Demand: %d" % peakPower)

except KeyboardInterrupt:
    print("keyboard interrupt detected")
    break
bluetoothSocket.close()

Does anyone have any ideas of what is going on?  Two of my values are floats and two are integers.  I've tried to fix this for the past 12 hours, but to no avail.

printing to the RPi terminal as if they're identical ... why are you surprised? ... it appears that you are setting all four to the same value .... print the value of received_data instead

@jsotola I get a hex ASCII code when received_data is printed.  I guess I'm just not sure how to parse the values I want from that and assign them to the four different variables.

0.24 is not an int. You python code expects ints only (and reads the first bytes of received_data four times).

You will save yourself a lot of headaches by sending the data in ASCII
instead of binary:
bluetoothSerial.print("RMSCurrent: ");
bluetoothSerial.println(RMSCurrent);

Of course, you will then have to parse the data stream on the Python
side.
If you really want to send binary data, then be aware that the write()
method you are using is intended for sending single bytes. Every number
you write() is converted to an integer (truncated if it's a float),
reduced modulo 256 to the range [0, 255], then sent as a single
byte. You can loose quite a bit of information in this process.
To send a binary object larger than a byte, you have to use an overload
of write() that takes both a pointer (the address of the object) and a
number of bytes to send. For example:
bluetoothSerial.write((uint8_t *) &RMSCurrent, sizeof RMSCurrent);

But then, you have to be aware that some numeric types do not have the
same binary representation on the Arduino and on the Pi. For instance:

an int is 2 bytes on the Arduino and 4 bytes on the Pi
a double is 4 bytes on the Arduino and 8 bytes on the Pi

I recommend you only use fixed-size integer types (uint16_t and such)
and float.
Also, be aware that the Arduino is little-endian, like the Pi, and
unlike what your Python code currently assumes.
Oh, and the serial link does not have a notion of data packets. If there
happens to be some leftover crap in the serial buffer when you start
your Python program, it will get out of sync with the Arduino, and you
will only read garbage. There are ways around this problem (search for
“packet framing”) but they add quite a bit of complexity.
As I said, you will save yourself a lot of headaches by sending the data
in ASCII instead of binary.


text:
Control output of XL6009 Boost converter with Arduino
I wonder if someone could help me with figuring out how to control XL6009 Boost converter via Arduino. I have this popular board, and it has potentiometer to adjust the output voltage. However, I want to adjust output voltage based on sensor reading so I need to do it "non-mechanically".
I tried with PWM voltage to the resistor network, but I didn't get wanted results. Any ideas (except digipot)?
Best regards

you posted your question in the wrong place ... this site is for questions about the Arduino

I didn't get wanted results is meaningless ... it does not describe the observed behavior

And why are you excluding digipots? Most Arduinos don't have a DAC, so you would need extra parts anyway

injecting a buffered (low pass, unity gain) voltage into the wiper of the pot didn't work? It works for me. You might not have enough current being injected. No more than a 1k resistor between opamp and wiper. You can also PWM+smooth to feed an optoisolator (or CDS varistor glued to an LED) that call pull one half of the pot down/up. Digipots won't work here, don't even bother.

Thanks for your responses. When I said I didnt get wanted results with resistor network, voltage range to control was too narrow (e.g 22-24V). But here is useful guide https://www.fischl.de/dcdccontrol/. When I changed resistor values a bit, it worked as intended


text:
Swap Serial pins of ESP8266?
I have designed and manufactured a PCB which contains an ESP8266 (ESP-WROOM-02D) chip with the serial uart pins connected to a 30pin connector. I made a mistake on the layout (first time designing a PCB), and have the RX (Pin 3) and TX (pin 1) pins connected incorrectly (swapped).
Is there a way to switch these pins in software? There's no nice way to physically modify and I was hoping to not have to have the boards manufactured again if I can avoid it.
Thanks!

no. there is not

You could potentially still fix this by using SoftwareSerial.
Instead of using the hard-wired serial, you can create one in software and use any pins you'd like... Have a look at this github project.
This work-around however requires you to have two unused pins to assign to SoftwareSerial.

the linked SoftwareSerial library is bundled with esp8266 Arduino boards support package

Can I reassign the two hardware serial pins to software serial? It is hardwired to pins 1 and 3...

@tommy-b-10, how do you flash the sketch into the esp?

@Juraj I flash the initial sketch before the esp is soldered to the board, then future flashes are done OTA using the esp wifi.

Had another crack at this and realised I needed to set the pinmode to function_3 for pins 1 and 3 before calling softwareserial.begin. Works perfectly now! Is there any downsides to using softwareserial? I have it working at 115200 baud but a little concerned about stability. Cheers!


text:
Interfacing IOT- GA6 to Arduino
Good evening guys,
Looking for any help on interfacing the above GSM/GPRS module with arduino.
Connections:
VCC and GND of module- separate power supply, 5v 3A
URX to pin 2
UTX to pin 3
Common GND between arduino and separate supply.
Tried AT command code for A6 module, getting +CREG:3 on serial monitor.
Same connections as above with GSM send messages code example on arduino-
Doesn't go past "Sms messages sender

what is your question?

Is there a way to interface the ga6 module with arduino. I saw some posts say you must flash the module to A6

Also is there a GA6 module code I could use

Would this help: https://create.arduino.cc/projecthub/EasyMades/a6-gsm-gprs-module-at-commands-34835a


text:
Arduino voltage misunderstanding
For arduino nano.
I set digital pins 1,2,3,4,5 to HIGH (I do this using digitalWrite(pin,HIGH) for each pin). Does this mean that 5V is being sent through each of the pins so in total there is 25V going out from the arduino?
How is this possible?

think about this ... connect five wires to the positive terminal of a 9 V battery ... is there 45 V on the wires?

i think that you are confusing voltage and current  ... voltage is like the pressure in the water pipes in your house ... it is the same at all of the water taps ... if you open taps in the kitchen and in the bathroom, the pressure at the taps is the same, it does not increase, but the amount of water flowing is double ... the water flow is like electric current

Voltage is a potential difference, like height. If you have five hills that are all 5m tall, you don't have a single 25m hill, you just have five places that are 5m tall.

Every pin gives you 5V on HIGH, yes, but these voltages don't add up.
Voltages are always measured between two points. In electronics we are defining one point in our circuit, that we use for all measurements, and call it ground. This is normally the negative pin of the power source.
Each pin has 5V in reference to the same ground, so they cannot add up (because that would mean the second 5V would be in reference to the 5V of the other pin, not in reference to ground). In the end they are connected in parallel to Vcc (where the power for the microcontroller is connected, in this case the 5V pin) of the Arduino (through the output drivers of the respective pin).
In the end this boils down to kirchoff's laws (if you want to research more about it). At a junction of connections, the voltage stays the same, but the current will be divided up between the connections.

Imagine that I have 5 flagpoles. I go to each of those flagpoles and raise a flag to a height of 2 meters. Since I have 5 flags, each at a height of 2 meters, does that mean that my flags have a total height of 10 meters?
Well, that question doesn't make a whole lot of sense, because "total height of the flags" isn't really a meaningful quantity. It's true that if you add up all the heights, you get 10 meters, but that number doesn't have any real meaning. Nothing in the system is 10 meters high.
Likewise, suppose you set 5 output pins all HIGH. Those output pins are just like flags on flagpoles, and you're raising each pin to a "height" of 5 volts. Nothing in the system is at a voltage of 25 volts; it doesn't make any sense to talk about a "total voltage."

If a private were tasked with climbing or polishing every flagpole, then yes, he would have to climb or polish a total of 10 meters of flagpole. But that's just a nuance of the analogy, your comment about voltage is correct.

It's a fascinating question. The Nano has 22 pins, all potentially set to output. D0 to D13, and A0 to A7.
So we have a total of 22 outputs. Now if they did add up then we could connect up a 5V battery and get 110V out of it! That might kill you! So clearly something is amiss here.
It's like when an employee has "20 years experience". Do they really have 20 times the experience they had in the first year, or do they have the same experience 20 times over?
The fact is that all 22 pins are all referenced to the same ground pin, so we really have 22 x 5V but all from the same starting point. So we really have 5V but with maybe a bit more current.
If you look at the datasheet, you don't even have 22 x the current you might have from one pin. The Atmega328P is specified to have a total of 200 mA current output.
Don't worry, setting all pins to output won't kill you. :)


text:
How to correctly use SSL certs with the Adafruit SIM800H
I am trying to use a Adafruit Sim800H to connect to Azure using MQTT with an SSL certificate. My first step is trying to put a new SSL certificate onto the board. To do this I am using this example here: https://github.com/vshymanskyy/TinyGSM/ ... etCert.ino . This seems to follow the typical suggested steps on how to set the SSL - by using AT command to create and write to a file, which is then set as the certificate.
The code I am running is the same as what is in the Github repo - except I have added extra print commands, getting a better idea of where it has broken. Here is an excerpt:
  SerialMon.println(F("Select..."));
  modem.sendAT(GF("+SSLSETCERT=\"" CERT_FILE "\""));
  SerialMon.println(F("cert file on.."));
  if (modem.waitResponse() != 1) return;
  if (modem.waitResponse(5000L, GF(GSM_NL "+SSLSETCERT:")) != 1) return;
  SerialMon.println(F("begin retCode"));
  const int retCode = modem.stream.readStringUntil('\n').toInt();

When I monitor my Arduino, I see "Select" and "cert file on.." printed out. However, then it hangs for a long time, and I get an error saying the command is not available.
Can anyone help me follow up on what may be the cause of this?
I have explored trying to update the firmware. I have downloaded a newer firmware (B11), and have the software needed to shift it to the board. However, it doesnt seem to recognise the board is connected over USB. In this situation, the cable is connected to the SIM800H board USB - is this correct?
Thanks.


text:
SoftwareSerial fails to receive on Nano but works with Uno
I have built a circuit board that includes a BLE module and an oxygen sensor that has a UART.  Writing arbitrary data to the BLE works fine, but for some reason every configuration of SoftwareSerial I can think of will not pick up anything from the oxygen sensor TX.  It simply never has any bytes available.
Here's the code:
#include <SoftwareSerial.h>

const int HM10_TX = 8;
const int HM10_RX = 9;
const int LOXO2_TX = A6;
const int LOXO2_RX = A7;

SoftwareSerial BLE(HM10_RX, HM10_TX);
SoftwareSerial oxygen(LOXO2_RX, LOXO2_TX);

void setup() {
  BLE.begin(9600);
  oxygen.begin(9600);
  oxygen.listen();
}

void loop() {
  if (oxygen.available() > 0) {
    BLE.write(oxygen.read());
  }
}

Meanwhile, I uploaded a short serial passthrough sketch to an Uno, connected probes between it and directly to the pins on the Nano that are used for the O2 sensor TX/RX, and I can see the expected bytes being received in my serial monitor.  So I'm 99% sure the problem isn't with the sensor.  Maybe the circuit, but so far I don't seem to have evidence of that.
I've been under the impression that any pin on the Nano can be used with SoftwareSerial.  All the reading I've done hasn't yielded any useful information as to why nothing is being read when clearly there are voltage changes on the pin that are being picked up by the Uno.
The reason I'm not using hardware serial is I will be using multiple sensors and the hardware serial pins need to be available for USB.
Am I doing something wrong?  The passthrough code I write for the Uno really isn't that different from the above code except it's of course using the hardware serial so I can observe the serial output on my laptop.

which oxygen sensor are you using? ... how is everything connected? ... please draw a connection diagram

A6 and A7 are analog input only and not available on Uno.

@Juraj I think you meant the Nano?  This is really disappointing to learn.  I did a lot of reading before building my PCB, and nothing I found said there were any particular pins on the Nano or Uno that couldn't be used for SoftwareSerial.  Fortunately I designed extra holes on my PCB for the only few digital pins I have left, so I can add jumpers that should make my project feasible.  Thanks for the help!

Uno doesn't have A6 and A7 so your sketch can't work on Uno as it is


text:
Arduino, generating smaller frequency than 31Hz
I'm controlling a car instrument panel with Arduino using the tone() function, however with Arduino Uno's minimum 31Hz frequency I can only set the speedometer at ~12mph or more.  I'd like to be able to set the speed from 0, which would require around 10Hz I believe. Are there any code tricks I could use? Maybe I should use hardware timer, or a different board?

What frequency range would you like to cover?

Let's say 10-400Hz, I don't have an exact number because each instrument cluster is different, but 10-400Hz should cover most of them

can't you toggle the pin on and off in loop() so as to lower the pulses per second from 30? It might not be as accurate, but your slow-reacting speedometer won't mind a 200us jitter.

try the Timer1 library

For this, I would consider using Timer 1 in mode 14 (fast PWM, with TOP
value controlled by ICR1), with the prescaler set to 64. The timer would
then be clocked at 250 kHz, giving you the following specs:

timer frequency: 250 kHz (time resolution = 4 µs)
minimum frequency: 3.81 Hz (exact period = 218 µs = 262,144 ms)
maximum frequency: 125 kHz (period = 8 µs)

As the time resolution is constant, the frequency resolution worsens as
you increase the frequency. At 400 Hz the resolution is about 0.16%, or
0.64 Hz.
This is not the only possible solution. Toggle mode would work also, and
also other prescaler values, which would give different frequency ranges
and resolutions.
Check the datasheet to see how to set the configuration bits (basically:
non-inverting PWM on either OC1A or OC1B, waveform generation mode = 14,
prescaler = 64). You may be able to find libraries to do this if you
prefer that approach, I have not checked this possibility.


text:
What is the simplest way to emulate the original gameboy's cpu using Arduino?
My initial question assumes it is possible to emulate the original GameBoy system using an Arduino board.
Additional information in non-technical terms: I am looking to create an Arduino based device that accepts cartridges as input devices (in some cases they will also function as output devices) I am interested primarily in the Hexadecimal/pixel based "logic" which gameboy games uses to display game data.
What is the simplest way to emulate the original gameboy's hexadecimal based pixel logic to fetch, decode, and execute data using Arduino?
Before flagging this question, please comment so that I may clarify as this is a complex question to ask and I am willing to re word it as necessary.

never assume anything

hexadecimal based pixel logic makes no sense ... it is all binary data

On an Arduino? No chance. On something more powerful? Sure. I've seen Z80 (and other) emulation running on an ESP32 (see FabGL), and the Sharp LR35902 the gameboy uses is very similar to the Z80.

There are multiple open-source emulators. Do your research, and read their documentation and code. You will quickly find that an 8-bit AVR cannot emulate a GB in real-time. (Note: Many years ago I wrote a GB emulator for a 68000 CPU (16/32 bit system) with 16 MHz. It runs common games with 1/4 to 1/10 of their original speed, and had no sound emulation.)

@jsotola you are correct at the machine level all operations are binary, but a 1 with 15 leading zeros can be interpreted the same as a 1 with no leading zeros that leaves 15 unique locations available for data manipulation. i'm sorry if it does not make sense to you. imagine a 16 by 16 grid of squares. each one is able to be "colored in" if any square is filled in then it is treated as a 1 rather than a 0 . the placement of these squares along with other factors can be used to store information. the compressed form is seen as hexadecimal code which when uncompressed becomes binary data.

@Majenko I am not looking to use it to play games, just utilize hex based addressing that functions similarly to how a gameboy game might store and retrieve data from a game cartridge. I believe the frame rate could be much much less than what a typical game would need to be. I would not necessarily need to play sound, though I recall how pokemon each had unique "sounds" or cries when appearing on screen, so sound is still something I am still researching. I will check out the z80 I believe that the docs i read used a teensy 4.0 which worked with most arduino peripherals.

@thebusybee I will continue researching and hopefully in a few days I can re word this question to better suit my needs. I also read that the esp32 has a dual cores with 240 mhz clock speed for each processor. I may eventually try using this if possible. To clarify I would like to Specifically be able to emulate only a game operating almost identically to Pokemon.

@PeopleCallMeAdam hexadecimal notation is simply for human readability of binary data ... it is not a compressed version of binary data ... there is no hex based addressing ... it is all binary addressing at machine level ... when the processor retrieves a value of 0x48F4, it is actually retrieving 0100100011110100 ... it knows nothing about 0x48F4

@jsotola again I am aware that the data is binary at the machine level, I view hexadecimal notation as a form of "lossless compression" humans speak many languages, when you translate between them you often lose part of the meaning in that translation. if binary code is the meaning and hardware the "speaker" think of software as people some people/software speak spanish and some speak english. if hexadecimal allowed for a lossless compression of some meaning in english then later uncompressed in spanish with nothing lost during translation with 100% success rate would what i said make sense?

@PeopleCallMeAdam No, that makes no sense at all (regarding your comment asking, “If hexadecimal allowed for a lossless compression … meaning in English uncompressed in Spanish… would what I said make sense?”).

(Assembling an answer from the comments)
The consensus is that there is no "simple way to emulate the original gameboy cpu using Arduino". That a more powerful platform is required.
Multiple commenters expressed difficulty with the novel concept of "hexadecimal/pixel based logic". It is suggested that this concept may be without merit.


text:
multiple mpu9250 using tca9548a with esp32
I'm using ESP32 and 1 sensor mpu9250(only for test) with tca9548a, connections are:
TCA <-> ESP
VIN - VCC
GND - GND
SDA - GPIO21
SCL - GPIO22
TCA <-> MPU
SD2 - SDA
SC2 - SCL
VIN - VIN
GND - GND
And my code here:
#include <SparkFunMPU9250-DMP.h>
#include <Wire.h>

#define TCAADDR 0x70
void tcaselect(uint8_t i) {
  if (i > 7) return;

  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

MPU9250_DMP imu;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  tcaselect(2);
  if (imu.begin() != INV_SUCCESS)
  {
    while (1)
    {
      Serial.println("Unable to communicate with MPU-9250");
      Serial.println("Check connections, and try again.");
      Serial.println();
      delay(5000);
    }
  }

  imu.dmpBegin(DMP_FEATURE_6X_LP_QUAT | // Enable 6-axis quat
               DMP_FEATURE_GYRO_CAL, // Use gyro calibration
              10); // Set DMP FIFO rate to 10 Hz
              delay(10000);
}

void loop()
{
  tcaselect(2);
    imu.dmpUpdateFifo();
  float q0 = imu.calcQuat(imu.qw);
  float q1 = imu.calcQuat(imu.qx);
  float q2 = imu.calcQuat(imu.qy);
  float q3 = imu.calcQuat(imu.qz);
  Serial.println("Q: " + String(q0, 4) + ", " +
                    String(q1, 4) + ", " + String(q2, 4) +
                    ", " + String(q3, 4));delay(10);
}

I need to get quaternions from the MPU sensor but I'm only getting zeros on the output.

Library that I used: https://github.com/rupin/SparkFun_MPU-9250-DMP_Arduino_Library
What could be wrong, my connection or library?

did you read the answer to this question? https://arduino.stackexchange.com/questions/70834/multiple-mpu9250-synced

You could try adapting the I2C Scanner sketch to use the TCA9548a like you do. Then you can check if the MPU is really visible on the bus. I would think, that the Arduino cannot reach the MPUn thus giving only zeros

@Juraj yes, I will try this method later. But now I'd like to figure out why my method doesn't work

@Juraj It works, thanks!

@chrisl It`s true, TCA scanner cannot find any addresses of MPU9250. Seems like clock stretching(idk). But now I use method of changing address of MPU that i use in 1 tick.

The solution is that I just removed the tca9548a from the circuit. Then I connected each AD0 pin to the corresponding GPIO ESP32 pins to turn on the sensor, I send a low signal to it, and a high signal to all the others. Thus, the library only works with a sensor whose address is 0x68.
There is example function from my sketch:
#include <SparkFunMPU9250-DMP.h>

/*INIT SENSORS*/
MPU9250_DMP imu;
MPU9250_DMP imu1;
const int sensor1 = 18;
const int sensor2 = 19;

String IMU_1Update(){
  String res;
    digitalWrite(sensor1, LOW); // 1st sensor enable - 0x68
    digitalWrite(sensor2, HIGH); // 2nd sensor disable - 0x69
  if ( imu1.fifoAvailable() ){
    if ( imu1.dmpUpdateFifo() == INV_SUCCESS){
      float q0 = imu1.calcQuat(imu1.qw);
      float q1 = imu1.calcQuat(imu1.qx);
      float q2 = imu1.calcQuat(imu1.qy);
      float q3 = imu1.calcQuat(imu1.qz);
      Serial.print("G1|");
      Serial.print(q0);
      Serial.print("|");
      Serial.print(q1);
      Serial.print("|");
      Serial.print(q2);
      Serial.print("|");
      Serial.print(q3);
      Serial.println("|");
    }
  }
  return res;
}


text:
Trouble obtaining values from Nextion screen to Arduino
Currently I have a setup running an Arduino BME 280 sensor and a 4.3" Nextion screen. What my program does is sent all the calculated values from the BME to numbers and progress bars in my Nextion on a screen called "Run".
This page consists of 3 values: Delta T, Temperature and Humidity as well as 3 buttons for an alarm. Each of these displayed values is connected to their own progress bar. Each of the individual values has a lower and upper alarm setting which can be adjusted on a following Nextion screen called "Settings".
So basically what I am struggling with is obtaining the obtaining the values from my "settings" screen to write the "if" function in my Arduino i.e (if the button is enabled on the run page and the value is less than X on the "Settings" page or more than Y on the "Settings" page, sound the alarm).
I have used the .getValue function, but it does not return a value to my Arduino program. Can anyone please assist. It will be highly appreciated.
// Include required libraries
#include <NexTouch.h>
#include <NexDualStateButton.h>
#include <NexNumber.h>
#include <NexProgressBar.h>
#include <NexText.h>
#include <Nextion.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

//Define BME parameters
#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme; // I2C

//Define variables
int Delta_T;
int Temp_disp;
float Temp_wb;
float Temp;
int rh;

//Define NEXTION variables
//Transport Page
NexNumber Trans_deltaT = NexNumber(2, 10, "n0");
NexNumber Trans_T = NexNumber(2, 11, "n1");
NexNumber Trans_H = NexNumber(2, 12, "n2");

//Run Page
NexNumber Run_deltaT = NexNumber(3, 14, "n0");
NexNumber Run_T = NexNumber(3, 15, "n1");
NexNumber Run_H = NexNumber(3, 16, "n2");
NexDSButton Delta_Temp= NexDSButton(3, 12, "bt0");
NexDSButton Temperature= NexDSButton(3, 22, "bt1");
NexDSButton Hum= NexDSButton(3, 13, "bt2");

//Settings Page
NexNumber DT_min= NexNumber(4, 5, "n6");
NexNumber DT_max= NexNumber(4, 12, "n3");
NexNumber T_min= NexNumber(4, 6, "n7");
NexNumber T_max= NexNumber(4, 14, "n4");
NexNumber Hum_min= NexNumber(4, 7, "n8");
NexNumber Hum_max= NexNumber(4, 16, "n5");

NexTouch *nex_listen_list[] = {
  &Delta_Temp,
  &Temperature,
  &Hum,
  &Run_deltaT,
//  &DT_min,
//  &DT_max,
//  &T_min,
//  &T_max,
//  &Hum_min,
//  &Hum_max
    NULL
};

void Delta_TempPopCallback(void*ptr) {
  uint32_t DT = 0;          // Button State
  uint32_t DT_act = 0;
  uint32_t DelT_min = 0;    //Define DT_min setting
  uint32_t DelT_max = 0;    //Define DT_max setting

  DT_min.getValue(&DelT_min);
  DT_max.getValue(&DelT_max);
  Delta_Temp.getValue(&DT);
  Run_deltaT.getValue(&DT_act);

  Serial.println();
  Serial.println();
  Serial.println(DelT_min);

  // Read value of dual state button to know the state (0 or 1)

  if (DT == 0 && DT_act < DelT_min || DT_act > DelT_max) {  // If dual state button is equal to 1 (meaning is ON)...
    digitalWrite(2, HIGH);  // Turn ON internal LED
    Serial.println("ON");
  } else {                  // Since the dual state button is OFF...
    digitalWrite(2, LOW);   // Turn OFF internal LED
    Serial.println("OFF");
  }
}

void setup() {
  Serial.begin(9600);
  bme.begin();
  pinMode(2, OUTPUT);
  Delta_Temp.attachPop(Delta_TempPopCallback);
}

void loop() {
  Temp = bme.readTemperature();
  Temp_disp = Temp;
  // Serial.print("Temperature = ");
  // Serial.print(Temp);
  // Serial.println(" *C");

  rh=bme.readHumidity();
  // Serial.print("Humidity = ");
  // Serial.print(rh);
  // Serial.println(" %");

  Temp_wb = atan(0.151977 * pow(rh + 8.313659, 0.5)) * Temp + atan(Temp + rh) - atan(rh - 1.676331) + 0.00391838 * pow(rh, 1.5) * atan(0.023101 * rh) - 4.686035;
  // Serial.print("Wet Bulb Temp= ");
  // Serial.print(Temp_wb);
  // Serial.println(" *C");

  Delta_T=Temp-Temp_wb;
  // Serial.print("Delta T=");
  // Serial.print(Delta_T);
  // Serial.println(" *C");
  // Serial.println();

  Trans_deltaT.setValue(Delta_T);
  Trans_T.setValue(Temp_disp);
  Trans_H.setValue(rh);

  Run_deltaT.setValue(Delta_T);
  Run_T.setValue(Temp_disp);
  Run_H.setValue(rh);

  nexLoop(nex_listen_list);

  delay(50);
}

What do you mean by "does not return a value"? Why don't you print out more of the values you're trying to read to get more debugging info - at least all of those that you're using in the if? Also I'd recommend you put parens in expressions like a && b || c . (a&&b)||c and a&&(b||c) are very different and C precedence rules are not always intuitive.

I had to repeat the getvalue code multiple times, there seems to be a bug which a youtuber pointed out in his video.
https://github.com/rvxfahim/AHU-Firmware/blob/main/development_HMI.ino
you can see from line 133, I called it so many times to be safe because it sometimes returned nothing or probably returned zero I don't remember it was a long time ago.


text:
Why my 4WD Bluetooth car run so slow

Code
/*Arduino Bluetooth Controlled Car
 *  * Created by Glen Tech
 * https://www.youtube.com/glentech
  */

#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

char command;

void setup()
{
  Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
}

void loop(){
  if(Serial.available() > 0){
    command = Serial.read();
    Stop(); //initialize with motors stoped
    //Change pin mode only if new command is different from previous.
    //Serial.println(command);
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(1000);//Define maximum velocity
  motor3.run(FORWARD); //rotate the motor clockwise
  motor4.setSpeed(1000);//Define maximum velocity
  motor4.run(FORWARD); //rotate the motor clockwise
}

void back()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(1000); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(1000); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void left()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(FORWARD);  //rotate the motor clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(FORWARD);  //rotate the motor clockwise
}

void right()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void Stop()
{
  motor1.setSpeed(0); //Define minimum velocity
  motor1.run(RELEASE); //stop the motor when release the button
  motor2.setSpeed(0); //Define minimum velocity
  motor2.run(RELEASE); //rotate the motor clockwise
  motor3.setSpeed(0); //Define minimum velocity
  motor3.run(RELEASE); //stop the motor when release the button
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}

Welcome! Please put your code in a code block (by adding 4 spaces before each line of code) to make it more readable. Also, add a clear description in your post about your hardware, the problem you are trying to solve and what you already tried. A link to youtube is not sufficient. What battery are you using for your project?

Can you measure the battery voltage when motors is ON?

What battery are you using? A 9V block batteries (like pictured) can't supply enough current to properly run a motor.

A photo of your actual hardware would also be helpful.

Move the stop() to setup(), and add some delay() in your loop(). Your loop is too busy and constantly stop and setting the direction again and again. Also introduce a status that holds the current direction status, if the command is the same as current direction status, skip the switch setup section, it only need when the command is changed.

I can't find issue in your code that I'm convinced is your problem. Without seeing your datasheet for the motor, I would bet your issue is one of two things:
1) A 9V battery is low-current relative to most batteries I've used for powering any decent DC motors. Do you have access to a better current source you could try?
2) Every motor has a trade-off in torque vs max-speed, dictated by the internal gear-ratio. Depending on the motor type, it may not have the torque to accelerate the vehicle to a significant speed.


text:
Model locomotive circuit review
I am building a model scale locomotive and therefore use Arduino for the DC motor, smoke generator, sound and lights. Can you help me with reviewing the circuit?
Power comes from rechargeable batteries (9.6V). This will supply the buck converter and the motor shield. Rest of circuit runs on 5V. A few MOSFETS regulate power for LEDs and smoke generator. MOSFET is overkill for this scale I know now. The locomotive has two parts: locomotive itself and the tender where the batteries and boards are put in. I just need to connect 5 cables for it to work.
Can you help reviewing if there are any errors / electrical shorts possibilities. Please don't add unnecessary complexity.

a schematic diagram is almost always clearer than a wiring diagram ... a quick glance reveals a couple of unknowns ... are mosfet connections correct? ... can DFplayer handle a 4 ohm speaker?

Shouldn't the red and white LEDs swap when the direction changes? (Three white on the front, 1 red at the back) This is not possible with this design.

I think you also need to connect 5V to the Vcc pin of the motor driver board. 2) I'd connect the LED to 5V. That way their brightness will remain constant, even when the battery voltage drops due to discharge. This will also run them more effeciently; giving you better battery life. 3) I'd add resistor to the base of the mosfets. 4) You may need to run the leds at less than 20mA, as they might be too bright.


text:
Arduino pro mini resetting itself
I am working on a brushed motor quadcopter using Arduino pro mini.
Every time I try to throttle, the Arduino gets reset by itself (motors start to spin but they will be turned off in 2 sec). I have added a 1000uf capacitor (tried up to 3300uf) to the input of Arduino VCC and GND. But still having the same issue.

Please show a wiring diagram or schematic of your setup

Do you have suppression capacitors on your motors?

What battery are you using?

I am using 3.7V 650mAH (Lithium Polymer) Lipo Rechargeable Battery for Drone.
Specifications
Battery model: KP 802540
Nominal voltage: 3.7V
Charging voltage: 4.2V
Nominal capacity: 650mAh
Operating temperature: -10 to 55°C
Discharging cut-off voltage: 3.2V
Charging current: 1C (max)
Discharge current: 15C (max)
Dimension: 43mm(L) x 25mm(W) x 8mm(H)
Weight: 10g..

and iam using 8520 Colorless Motor

@chrisl i have added schematic

Sounds like a power issue. Are you using the same battery for the motors and Arduino? If yes, Can you try a different battery/power source for arduino?

Yes I am using the same battery.

Now Iam planning to use 1200mah with 20C discharge current, so that i get 6A (20*1.2 /4) per motor (However my motor 8520 stall current is 5.3A) is that fine?

Before replacing the batteries, You can try a different battery just for Arduino and see if it still resets. Because more batteries = more weight.

I have also tried to connecting directly to computer(without battery) while calibration..it has resets. @AjithGopi

Can you try replacing the motors with LEDs and check if it resets? If it works, only connect one motor at first and see what happens.

Let us continue this discussion in chat.


text:
Programming multiple arduino at once
I actually made a prototype with multiplexing Chip select pin on Arduino, which connects to RESET pin of target board to program. When I am connecting one target board at once I am able to program it but when I am connecting multiple target boards then not able to program ICs.
I am using Nick gammon's code for programming the target Arduino using the master Arduino
https://github.com/nickgammon/arduino_sketches/tree/master/Atmega_Hex_Uploader_Fixed_Filename
This is rough block diagram of multiplexing chip select pin -

I also tried connecting RESET pin of target Arduino to its chip select pin but that is also not working.

Which pin on the targets are you multiplexing too?
I don't think they even need CS for being programmed - just a RESET, followed by the SPI communication.
I'd try multiplexing the RESET pin instead, but since that is active low, it depends on your multiplexer IC.

Also other Arduinos must have SPI pins disabled (= inputs), so it won't affects selected one. Otherwise you'll need 74HC(T)125 per arduino or 74HC(T)244 per two of them

@towe MOSI, MISO, SCK pins are common between the master and all other target arduinos. The Chip select pin on master arduino (which is responsible for programming all targets) is multiplexed using 74HC4067 mux. And the output of the mux is connected to RESET of target ICs. Now the target ICs will either be programmed for the first time when the do not have any bootloader. Or reprogrammed/firmware update. In any case the hex file is firmware+bootloader file. This setup is not working.

I searched for SPI multiplexing and found out that the master's chip select pin should be connected to target's CS pin which should be pulled up. Now as RESET on target side is needed for programming mode to initialize, I connected RESET and CS pin on target. But this setup also doesnt work.

Isnt it that RESET is normally pulled up and to initiate programming its given LOW signal?

You're right, I thought it only had to be pulsed to enable programming.

But I actually tried what you said. When I connected 2 target boards with the master IC, normally it was not working. But when I connected RESET pin of one of the target board to ground the other one was successfully programmed. Have to find a way to automate the grounding of RESET pin and program ICs sequentially one after the other.

But there is still some weird behaviour. When I replicated the same by connecting RESET of the now programmed IC to gnd and tried programming the other one, that works. But the already programmed one wont work. Basically I uploaded Blink program. So when I uploaded blink on 2nd one the 1st one was not blinking. But thanks this gives me some idea to work with.

Technically you are using ICSP to program the MCU, not SPI. So the the CS pin terminology doesn't really apply. Since the MISO MOSI and CSK pins are all tied together, you have to make sure that any code running on the target MCUs will never use those pins (as outputs), or they will interfere with the ICSP programming process, and possibly cause damage. Also, the 74HC4067 needs 2 inputs to select between 4 outputs.

You last two comments are strange. From the datasheet To enter and stay in Serial Programming mode, the AVR microcontroller reset line has to be kept active(low).

Can the 74HC4067 even work. Doesn't the 74HC4067 set only one of it's outputs HIGH, while the reset is LOW? To program one MCU you'd need one (reset-)pin to be LOW, but the reset HIGH.

you don't do SPI so you don't have to connect CS. you can use any pin of programmer board to do a reset of the target board. what for is the multi target setup? it has no practical use. how do you decide which target you reset to program? you can"t program them simultanously

@Gerben So in previous comments someone suggested to pull RESET pin down of all other targets when programming one target. It worked but I observed some issues. Trying to work on it. 74HC4067 is 16:1 MUX so there are 4 selection pins to select the output.

@Juraj So I am trying to implement multiple ic programming for mass production purpose. And yes one cannot program them sumiltaneously but what I am trying to implement is that connect like 16 ICs to one master programmer and then click a button and then everyting will be taken care of and a person who is responsible for IC programming in production cycle will then can focus on other things as well, And then when all the ICs are programmed will the check error messages to debug if any IC was not programmed successfully. Trying to improve productivity.

RESET should be LOW while ICSP flashing.


text:
Arduino-project with color sensor and rgb-led
I want to use a color sensor for my Arduino project with Arduino Uno to detect the colors red, green, blue, orange, yellow purple of leaves of paper and then light my RGB led in those colors. I have no errors in my code, but it fails for some reason :( Can someone help me?
here is the code:
#define s0 8
#define s1 9
#define s2 10
#define s3 11
#define sensorOut 12

#define LED_RED 3
#define LED_GREEN 5
#define LED_BLUE 6

// Variabelen voor de kleurwaarden
int red;
int green;
int blue;

const int RED_COLOR = (255, 0, 0);
const int GREEN_COLOR = (0, 255, 0);
const int BLUE_COLOR = (0, 0, 255);
const int ORANGE_COLOR = (255, 165, 0);
const int PINK_COLOR = (255, 105, 180);
const int PURPLE_COLOR = (128, 0, 128);
const int YELLOW_COLOR = (255, 255, 0);

int color = 0;

void setup() {
  // Zet de seriële communicatie op
  Serial.begin(9600);

  // Initialiseer de pinmodi
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(sensorOut, INPUT);

  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);

  // Zet de frequentie van de kleurensensor op 20% (rode filter)
  digitalWrite(s0, HIGH);
  digitalWrite(s1, LOW);
}

void loop() {
  // Lees de kleurwaarden
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  red = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
  delay(20);
  digitalWrite(s3, HIGH);
  blue = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
  delay(20);
  digitalWrite(s2, HIGH);
  green = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
  delay(20);

// Controleer op verschillende kleuren
if (red > green && red > blue) {
  color = RED_COLOR; // Rood
} else if (green > red && green > blue) {
  color = GREEN_COLOR; // Groen
} else if (blue > red && blue > green) {
  color = BLUE_COLOR; // Blauw
} else if (red > green && red > blue && green > blue) {
  color = YELLOW_COLOR; // Geel
} else if (red > green && red > blue && blue > green) {
  color = ORANGE_COLOR; // Oranje
} else {
  color = 0; // Geen herkende kleur
}

  // Controleer op verschillende kleuren
  if (color == RED_COLOR) {
    setColor(255, 0, 0); // Rood
  } else if (color == GREEN_COLOR) {
    setColor(0, 255, 0); // Groen
  } else if (color == BLUE_COLOR) {
    setColor(0, 0, 255); // Blauw
  } else if (color == ORANGE_COLOR) {
    setColor(255, 165, 0); // Oranje
  } else if (color == PINK_COLOR) {
    setColor(255, 105, 180); // Roze
  } else if (color == PURPLE_COLOR) {
    setColor(128, 0, 128); // Paars
  } else if (color == YELLOW_COLOR) {
    setColor(255, 255, 0); // Geel
  } else {
    // Geen herkende kleur, zet de led uit
    setColor(0, 0, 0);
  }

  delay(500); // Wacht 500 milliseconden voordat je de volgende kleur controleert
}

// Hulpmethode om de RGB-waarden in te stellen
void setColor(int red, int green, int blue) {
  analogWrite(LED_RED, red);
  analogWrite(LED_GREEN, green);
  analogWrite(LED_BLUE, blue);
}

What does “it fails for some reason” mean? What is the expected behavior of your sketch? What is the actual observed behavior? How exactly do they differ?

Reading your code, I see three points:

Your constants are not assigned the values that you think. const int RED_COLOR = (255,0,0); sets the integer constant to the value 0, i.e. the last value of a comma-separated sequence, see here. Instead, enumerate your color constants, i.e. set red=1, blue=2, etc. Or define a struct with three integer components.
The variable color will never be assigned the values ORANGE_COLOR, PURPLE_COLOR nor YELLOW_COLOR, because of the way you structured the expressions in the if-then-else block. If red > green && red > blue, the program will never even check whether red > green && red > blue && blue > green, because it already entered the first block. And PURPLE_COLOR is not listed in the upper if-else-block at all. Also, I would expect some CYAN_COLOR somewhere in there to cover the shades between green and blue.
What is the exact type of the color sensor? It seems strange to me that it transmits its data via the length of a pulse. If it doesn't, pulseIn() is the wrong method to use. If it really does, you may have a race condition here: I guess that writing to the pins s2/s3 triggers the sensor to start the "data pulse", in which case digitalRead(sensorOut) may already return the "pulse state" instead of the "pre-pulse state" and therefore waits for a different pulse than it should. You'd need to first read sensorOut into a variable, then set s2/s3, then read your data via pulseIn using the variable you set before.

But without having the datasheet of the sensor/knowing the protocol of the sensor, this is all very volatile guesswork. Please improve your question by adding the sensor type (and maybe a wiring diagram) alongside an explanation of what you mean by "it fails". How exactly does it fail? Which part works and which doesn't?
You can also glean more insight into the state of your sketch by writing measured values to the serial monitor using Serial.println.


text:
nano 33 BLE problems with reading RC signal
I'm using an Arduino Nano 33 BLE and a L293D motor driver to control a three-wheeled RC robot. The sketch I'm using worked fine with my Uno Rev3, but I've moved to the Nano for size/weight reasons, and it's no longer working. Whenever I turn the power on, the motor I'm using to test spins clockwise at what appears to be full-speed, without considering the receiver's signal at all. I actually removed the wires from the receiver and the motor just kept on spinning.
I tried looking at the serial plotter, but it appears that the Nano is disconnecting itself from my laptop whenever I turn the RC transmitter on, so I haven't been able to get any information that way.
I've troubleshooted to the best of my limited ability, and the problem seems to be with the Nano not processing the signals from the receiver. Beyond that, though, I don't have the first clue what the root of the problem is. I'm pretty new to Arduino & coding haha.
I followed this YouTube tutorial for the process of reading the RC values, and the variables with color names are referring to the motors. Here's the sketch:
//set the port speed for host communication
#define SERIAL_PORT_SPEED 115200

#include <math.h>
#define RC_NUM_CHANNELS 2
#define RC_CH1 0 //right stick LR
#define RC_CH2 1 //right stick UD
#define RC_CH1_INPUT 2 //pin 2 on arduino
#define RC_CH2_INPUT 3 //pin 3 on arduino

// Set up some arrays to store our pulse starts and widths
uint16_t RC_VALUES[RC_NUM_CHANNELS];
uint32_t RC_START[RC_NUM_CHANNELS];
volatile uint16_t RC_SHARED[RC_NUM_CHANNELS];

const int enable_pink = 13; //pin that enables pink motor
const int enable_blue = 12;
const int enable_yellow = 11;

int dead_zone = 10; //within 10 of 0, motor will not move
const int error_pin = 4; //this lights up when something unexpected happens
int UD;
int RL;
double pi = 3.1415926;

int pink; // analog value out of 255 for the pink motor
const int pink_cw = 5; // pin that signals pink motor to move clockwise
const int pink_ccw = 6; //pin signals counterclockwise
int blue;
const int blue_cw = 7;
const int blue_ccw = 8;
int yellow;
const int yellow_cw = 9;
const int yellow_ccw = 10;

void setup() {
  // set the speed to communicate with the host PC:
  Serial.begin(SERIAL_PORT_SPEED);

  //set pin modes to input for reciever
  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);
  //attach interrupts to these pins
  attachInterrupt(digitalPinToInterrupt(RC_CH1_INPUT), READ_RC1, CHANGE);
  attachInterrupt(digitalPinToInterrupt(RC_CH2_INPUT), READ_RC2, CHANGE);
  //set pin mode for error pin
  pinMode(error_pin, OUTPUT);

  //set all green wires (motor-enabling wires) to OUTPUT
  pinMode(enable_pink, OUTPUT);
  pinMode(enable_blue, OUTPUT);
  pinMode(enable_yellow, OUTPUT);

  //set all motor signal outputs to OUTPUT
  pinMode(pink_cw, OUTPUT);
  pinMode(pink_ccw, OUTPUT);
  pinMode(blue_cw, OUTPUT);
  pinMode(blue_ccw, OUTPUT);
  pinMode(yellow_cw, OUTPUT);
  pinMode(yellow_ccw, OUTPUT);

  //enable all motors
  digitalWrite(enable_pink, HIGH);
  digitalWrite(enable_blue, HIGH);
  digitalWrite(enable_yellow, HIGH);

}

void loop() {
  // read the values from our RC reciever
  rc_read_values();

  //map RC values to analog scale
  UD = map(RC_VALUES[RC_CH1], 800, 2200, -100, 100);
  RL = map(RC_VALUES[RC_CH2], 800, 2200, -100, 100);

  //output raw RC input to serial plotter
  Serial.print(UD); Serial.print(",");
  Serial.println(RL);

  //do the math to calculate wheel vectors
  pink = RL;
  blue = (UD/(cos(pi/3))) + (RL/(sin(pi/3)));
  yellow = -(UD/(cos(pi/3))) - (RL/(sin(pi/3)));

  //now map the wheel vectors to analog scale:
  blue = map(blue, -800, 800, -255, 255);
  yellow = map(yellow, -800, 800, -255, 255);

  //now, output each value to each motor
  set_color(pink, pink_cw, pink_ccw);
  set_color(blue, blue_cw, blue_ccw);
  set_color(yellow, yellow_cw, yellow_ccw);

  //output pink blue and yellow values to serial plotter:
  Serial.print(pink); Serial.print(",");
  Serial.print(blue); Serial.print(",");
  Serial.println(yellow);

}

//create function to give the signals to the motors
void set_color(int color, int color_cw, int color_ccw) {
  if (color > dead_zone) {
    analogWrite(color_cw, color);
  } else if (color <-(dead_zone)) {
    analogWrite(color_ccw, abs(color));
  } else if (color <= dead_zone && color >= -(dead_zone)) {
    return;
  } else {
    digitalWrite(error_pin, HIGH);
  }
}

// These functions are called by the interrupts. We send them all to the same place to measure the pulse width
void READ_RC1() {
   Read_Input(RC_CH1, RC_CH1_INPUT);
}
void READ_RC2() {
   Read_Input(RC_CH2, RC_CH2_INPUT);
}

// This function reads the pulse starts and uses the time between rise and fall to set the value for pulse width
void Read_Input(uint8_t channel, uint8_t input_pin) {
  if (digitalRead(input_pin) == HIGH) {
    RC_START[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - RC_START[channel]);
    RC_SHARED[channel] = rc_compare;
  }
}

// this function pulls the current values from our pulse arrays for us to use.
void rc_read_values() {
  noInterrupts();
  memcpy(RC_VALUES, (const void *)RC_SHARED, sizeof(RC_SHARED));
  interrupts();
}

any help would be greatly appreciated, I'm truly stumped here

a smaller Uno is a classic Nano. Nano 33 BLE is very different and uses Mbed OS.

The "nano" is basically form factor + pinout, 33 in the board name means it's 3.3V only board (usually has ARM mcu) and being said nano 33 ble has mbed-os which means your code will be interrupted by other threads (unless it has higher priority than other threads)


text:
Detecting peak frequency in a microphone's output signal
I'm using a simple electrode microphone with an Arduino UNO board with the aim of detecting peak frequencies in the output signal overtime. I set the sampling rate to 1 MHz, but i can't pick up a peak that is above 4000 Hz(I've verified the values with regression but it's only true for the range [200 Hz, 3900 Hz]). So my questions are:

Is this due to the microphone's sensibility or to the Arduino UNO?
Someone suggested me an ESP32, but i don't understand what difference it'll make.

CODE:
#include "arduinoFFT.h"
float peak = 0;
float val = 0;
#define SAMPLES 128            //SAMPLES-pt FFT. Must be a base 2 number. Max 128 for Arduino Uno.
#define SAMPLING_FREQUENCY 1000000 //Ts = Based on Nyquist, must be 2 times the highest expected frequency.

arduinoFFT FFT = arduinoFFT();

unsigned int samplingPeriod;
unsigned long microSeconds;

double vReal[SAMPLES]; //create vector of size SAMPLES to hold real values
double vImag[SAMPLES]; //create vector of size SAMPLES to hold imaginary values

void setup()
{
    Serial.begin(115200);
    samplingPeriod = round(1000000*(1.0/SAMPLING_FREQUENCY)); //Period in microseconds

}

void loop()
{

    for(int i=0; i<SAMPLES; i++)
    {
        microSeconds = micros();
        val = analogRead(0);
        vReal[i] = val;
        vImag[i] = 0;

        while(micros() < (microSeconds + samplingPeriod))
        {

        }
    }

    FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
    FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
    FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);

    peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);
    Serial.println((peak-5063)/122.5);
    Serial.print(";");

i've used the included FFT library, and generated sounds with an app then verified the measured frequencies with the Spectroid app, albeit i had to put the source right at the microphone.

Related: https://arduino.stackexchange.com/questions/44868/max-sample-rate-of-an-arduino-uno

I doubt, that you really have an ADC sampling frequency of 1MHz on an Arduino Uno. 4kHz seems to be about aligned with 2x the max sample rate in the first comment of that question (niquist frequency). The ESP32 was surely suggested, because it runs on a way faster clock. Mine is set to 240MHz by default (in contrast to the Unos 16MHz). Please show us your code

here is my code :

please check the question

If you write big integer literals, make sure that they are interpreted as long. So write 1000000L instead of just 1000000. Then please try again. Also you can use micros() to measure the time, that your measurement loop actually needs. That would make sure, that you are not actually slower with sampling than you think.

So you think there's now way getting around buying another more precise card?

alright i'll try that. thanks.

so i tried the long integer type but it's pretty obvious that the UNO's sampling rate doesn't match for the job. Are there any better arduino cards? I'm only interested in the audible brandwith to suggest a device that alerts in dominance of frequencies at high intensities.

There are only few Arduino boards, which are slower than the Uno. So look at what is available for you and check the clock frequency. Research the max ADC sample rate for those boards. Then you can choose one. The ESP32 is only one possibility.

Hello sir. The output of my microphone is way too low. When measuring the span(max - min) of my signal(wich i'll use later on), the span is always around 2, and i need to cough really lough, and close to the mic for it to change. Is amplification inevitable? Because my microphonealready had an in-built amplifier?

You need a voltage between ground and Vcc of your board (5V on the Uno, 3.3V on boards like the ESP32). Fi your microphone module doesn't provide that, then you need further amplication.

when i coud loud enough the signal peak to peak can reach 2 volts, so i think the amplifier that is built-in is good enough..


text:
Can a sensor have multiple I2C addresses?
So I'm having a weird issue with a TCA9548A multiplexer. When I run the scanning code given on the adafruit website, I get the following result:
TCAScanner ready!
TCA Port #0
TCA Port #1
TCA Port #2
Found I2C 0x0
Found I2C 0x44
TCA Port #3
TCA Port #4
TCA Port #5
TCA Port #6
TCA Port #7
done
And I suppose my question is, how is it possible that a device has two I2C addresses? I know for certain the address should be 0x44 but what does the 0x0 mean? and equally bizarre is that that sensor doesn't output numerical values when called. The sensor works perfectly when connected directly to an Arduino Mega 2560, but I can't get it to function with the multiplexer.

You are right that there's something wrong here. 0x0 is not a valid address for an I2C device. Maybe you should share the code that you use to do the scan.

Of course a device can have multiple addresses, theoretically. It's just a matter of comparing the received address with expected addresses, and acknowledging if one of them matches. Think about a microcontroller emulating multiple I²C chips. -- However, I don't think that a single chip exists that works like this. -- 0x00 belongs to the reserved addresses.

Can you link to the scanning code? The address 0x00 is the general call address. You can address every device on the bus with it (only master write, no master read transaction). Often these scanning codes only check for the acknowledgement after the address byte. For the general call address the protocol states that the devices on the bus all can acknowledge when receive a general call transaction. So seeing the address 0x00 does not by itself mean that something is wrong. And the standard I2C scanner doesn't even use 0x00 as address.

Some people consider I2C devices' read- and write-header as two separate addresses. I2C addresses are usually 7-bit plus one read/write bit. If all those 256 addresses are scanned, a device would acknowledge on 2 addresses.


text:
Why can't I just plug a stepper or gimbal motor (BLDC) into the ground, 5v, and analog pins of my Arduino?
I plugged a BLDC gimbal motor in to my Arduino today, and it made a very small jitter. I tried to set an analog pin for the signal pin of the motor (motor had three pins, I assumed one was power, one was ground, and one was signal/data/position) but the motor barely moved. I wanted to see my motor spin at some constant rate determined by that signal pin, or maybe move to the position specified in the signal pin.
Upon further research, I find many pages advising me to use "controllers" or other complicated setups to manage a motor. I am confused as to why it is so complicated. Can't it be simple to plug a stepper motor into an Arduino and get some constant revolutions based on Arduino control?

the arduino is not a power supply ... its output current capacity is very limited ... it cannot drive a motor directly ... you are lucky if your arduino output pins are still alive after your experiment

Not only is the available current limited, but a stepper motor in particular is not capable of running just by supplying power.
It's drive coils must be energized in sequence to "pull" the rotor around, and sequenced at a rate that drives the rotor at the desired RMP. The circuitry to do that is external to the stepper, usually a combination of logic signals from a micro-controller (typically) and hardware to translate those signals into drive currents sequenced to the stator-coils. This is what makes steppers so flexible - controllable in direction and speed, down to the single-step level (subject to the rotor's interia) - at the cost of more complex drive circuitry. In short, steppers need to be programmed, continuously, to drive them however the mechanical system requires.

It is a power issue. By that I mean Power = Votage x Current.
Put simply, the 5V supply regulator IC on the Arduino is only designed to power the microcontroller(s) and a handful of other electronic components.
The Arduino has a little 5V regulator that is capable of delivering 100mA to 500mA depending on your Arduino. Don't forget that the microcontroller itself uses roughly 20mA. The remaining current is capable of runing very low power items such as sensors, switches, LEDs etc but not parts that require more power. Unfortunately motors require a lot more power than what the regulator on the Arduino can provide.
I suggest that you use a second 5V supply. For example you could use:

Benchtop power supply
Plugpack or phone charger type power supply
An old computer power supply
A DC/DC converter (like this one)

These are just a few. There are many more options.

A brushless DC motor consists of three coils of wire wired in a Y (wye) or Δ (delta) configuration and a magnetic rotor. The coils are evenly spaced around the 360 degrees of the motor. There can be multiple poles, or "copies" of each coil, so it's not necessarily 120 degrees from a coil A to a coil B - e.g. it could be ABCABCABC to go around the full circle with 40 degrees between coils. There are no power or ground or data wires, just electromagnets.
Anyway, when current goes through one of the coils it forms an electromagnet and attracts the rotor to that position. We say the coil is energized. By repeatedly energizing and de-energizing different coils you make the rotor spin around in circles. If you energize A, then B, then C, then A, then B, then C it spins one way; energize C, then B, then A, then C, then B, then A and it spins the other way. The current direction also matters because an opposite current produces an opposite magnetic field. Of course you also have to get the timing right - so the magnetic force is always pulling the rotor ahead of where it currently is. When the rotor catches up with the magnet coil you switch to the next one. I'm oversimplifying.
To use one you can buy a controller which does have power and data and ground wires, as well as the 3 wires for the magnets, and you tell the controller to go, and it handles all the switching and timing for you. You could design your own, but good luck.

Steppers are the same basic idea but optimized for low speed and precise movements instead of big movements. Because you don't care about timing so much for a stepper - you're moving it one step at a time and not really trying to use its inertia - you can write your own control algorithm if you want. Note the Arduino's digital pins still can't output enough current so you still need some circuitry. Or you can buy a stepper motor controller.