text:
Assigning an empty array row to reference
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int (*EXCLUSIVE_COLOR)[3];

I have a two-dimensional array to store some color values.
I have a 2nd array, which I am using to assign an "EXCLUSIVE_COLOR" from the first colors array.
What is the best method to assign a null or empty value to the "EXCLUSIVE_COLOR" array to be used upon initialization and when the "EXCLUSIVE_COLOR" is unset?
Initially I tried just assigning a default value to the array upon initialization:
int (*EXCLUSIVE_COLOR)[3] = {0,0,0};
//Produces an error: scalar object ‘EXCLUSIVE_COLOR’ requires one element in initializer

int (*EXCLUSIVE_COLOR)[3] = {0};
//assigns non-zero values to all three elements

I know that I can add a "dummy" record to the colors array to reference, when there isn't an "EXCLUSIVE_COLOR" set.
int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 },

  { 0, 0, 0, }   //dummy record
};
int (*EXCLUSIVE_COLOR)[3] = &colors[4];

However I wanted to know if there was a cleaner way to be able to assign an empty value to reference when a color is not set, and when the array is initialized.

use the pointer as I recommended in you previous question

I am currently using a pointer to a 3 int array, as suggested in the previous question. However that only specifies how to assign an array element by reference from the colors array, which is why I'm currently using the "dummy record" approach to set a default value. I was wondering if there was a better way to assign a default value to the pointer,  other than having it point to a dummy array element in the colors array.

int* EXCLUSIVE_COLOR = {0,0,0}; read my comment or the edit at the end of Edgar's answer

If you're using a pointer then there's no limit to what that pointer can point to.
The way I see it you have two sensible choices:

Point to a default value

This doesn't have to be in your array. It can be anything that is an int[3], since that is what your array consists of.
int[3] nothing = {0, 0, 0};

EXCLUSIVE_COLOR = nothing;

This means that it's actually pointing to something valid, in this case it's actually (I assume) the colour black.  That can make it easy to deal with, since EXCLUSIVE_COLOR[0] will be a valid value.

Point to nothing

You can point your pointer to NULL and it will be pointing to "nothing". This means that EXCLUSIVE_COLOR[0] is no longer valid, which can make handling it somewhat harder. However it does allow you to distinguish between "nothing" and "black", unlike option 1.
For example:
EXCLUSIVE_COLOR = colors[2]; // {0, 0, 255}
...
EXCLUSIVE_COLOR = NULL; // Not pointing anywhere

To test if it's pointing somewhere you can simply use if:
if (EXCLUSIVE_COLOR) {
   // you have a valid entry
}


text:
How many LED displays can be hooked to one Arduino board?
I am new to Arduino development. I need to connect multiple led displays(between 20 and 100), such as this one to an Arduino board. The led displays will be pretty far out from each other.
How can this be achieved? How can i uniquely identify the LCD displays? At this point i need some 101 orientation.

The product, that you linked, is an OLED display, not an LCD display

okay, thanks, so how many?

Without any additional electronics: Exactly one. On each I2C interface every address needs to be unique. Since you cannot change the address of the display, 1 is the limit. Majenkos answer gives you a hint how to deal with that.

@chrisl on the SSD1306 you can select a second address, but I'm not sure the PCB in the product listed, breaks out the D/C# pin. Even then, you can only connect two. You could bitbang I2C on other pins. But you'd need two pins for each display, and you would run out of pins pretty quick. Also the library you use for the displays might only support the hardware I2C pins.

The led displays will be pretty far out from each other.

Those are I2C connected displays. I2C is not designed (though there are technologies to allow it) to operate over long distances. It's designed primarily for communication between chips within a circuit board.

How can i uniquely identify the LCD displays?

Since you can't change the I2C address of the displays you would either need a separate I2C bus for each one or employ some form of I2C multiplexer.
All of this is getting too complicated. The more accepted way of doing this would be to have a small microcontroller directly connected to each display (one display per microcontroller) and then make the microcontrollers communicate with each other (or with a single master) over some suitable communication medium (some wireless system, or a serial bus like RS485 or CAN, for example).
You're then just rubber-stamping the units as many times as you want, and connecting them all together.

source: Stack Exchange

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

sort: votes


text:
Setting an array pointer to null on declaration
How can I set an array pointer to null?
I have a pointer to a 3 int array that I am trying to set to null.

int (*EXCLUSIVE_COLOR)[3];

Per this link I was trying to set it to null upon initialization.
However this does not assign a null value to it. It assigns three 'random' integers to the array elements:

{128, 447, 451}

How can I make it point to a null or empty value?

if you assign null, test it for null, not read it

What were you expecting to  get when you read a null pointer?  That's undefined behavior.  It could give you anything.  If you want to make the thing pointed to zero then do that.  That's not the same as assigning a null pointer.

Does this answer your question? Assigning an element of a multidimensional array to a second array

Here is a full example that shows you all thing things you have been asking over the past few days:
int colors[][3] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255}
};

#define NCOLOR (sizeof(colors) / sizeof(colors[0]))

int *EXCLUSIVE_COLOR = NULL;

void setup() {
    Serial.begin(115200);
    Serial.print("You have ");
    Serial.print(NCOLOR);
    Serial.println(" colors defined.");
    reportColor();
    EXCLUSIVE_COLOR = colors[2];
    reportColor();
    EXCLUSIVE_COLOR = NULL;
    reportColor();
}

void loop() {

}

void reportColor() {
    if (!EXCLUSIVE_COLOR) {
        Serial.println("Color is not set");
    } else {
        Serial.print("Color is set to ");
        Serial.print(EXCLUSIVE_COLOR[0]);
        Serial.print(",");
        Serial.print(EXCLUSIVE_COLOR[1]);
        Serial.print(",");
        Serial.println(EXCLUSIVE_COLOR[2]);
    }
}

You have an array of colours. You have a pointer that can point at a colour or at nothing. It starts off pointing at nothing. The code recognises that it's pointing at nothing and reports it. It gets assigned to a specific colour in your colours array. The code recognises that it's now a valid value and reports it. The pointer then gets pointed to nothing again. Again the code recognises that and tells you.
The result:
You have 3 colors defined.
Color is not set
Color is set to 0,0,255
Color is not set

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


text:
Better version of MPU6050
I need really good gyroscope for my quadcopter and now I have MPU6050. I don't like how it works, after some time of use, data is absolutely wrong. So I need good gyroscope, could you pls advice the best gyroscope for Arduino?

"after some time of use, data is absolutely wrong" - That sounds like you are using the raw data, which is always problematic. The different data outputs have to be combined through means of sensor fusion. How are you using the data from the MPU?

use this: https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/ . I attached image where I just do nothing.

You want a better gyroscope? Here's one. You want a MEMS gyroscope? They're all pretty much the same, and all respond in the same way. It's your job to deal with the data in the right way.

is it explains why all sketches from internet give the same bad behavior?

You should read this: https://www.analog.com/en/analog-dialogue/raqs/raq-issue-139.html and you will then understand what you ask is an impossibility.

To be honest, I really don't see why the values are that bad. Please explain more about how they are wrong. They seems to mainly change behind the decimal point. The typical flight controller in a quadcopter also uses a similar MPU, though it also uses more different sensors for the sensor fusion, that improves the quality

@chrisl, I expect right values, like 90 degree when it is vertical and so on. May be I should use only changes of values but not values?


text:
How To Activate H-Bridge?
My understanding of the H-bridge is, that activating in1 or in2 will direct the 12V current to the motor, so it either spins right/left. Not that in1 or in2 is the actual current passing through to the 12V motor.
These are the schematics.
I am trying to activate the H-bridge and the 12V motor by powering In1 with digital 2 from my Arduino.
The power outlet is an universal adapter connected to my wall outlet, which then goes to a breadboard power supply.
I don't have a functioning multimeter, so I cannot measure the exact current going through, but I do know, that if I place in1 in the power outlet's Vout the 12V motor spins.
Other than that, I do not have much information, and I would like to ask you guys for help as to why, the 12V motor doesn't spin when I power in1?

You don't have a ground connection between the Arduino and the H-bridge?

@Majenko This is about the dumbest mistake I have made in a long time. Thank you, it needed a common ground.

It's not a dumb mistake. It's a common mistake. So common I wrote an entire blog article all about it. https://majenko.co.uk/blog/importance-sharing-grounds

George, you should post a self-answer with the solution and then accept it so the question is marked as answered. (Or @Majenko should post an answer, since they're the one who identified the solution.)

@DuncanC Will do, I can accept it in 2 days.

There was no common GND between the H-Bridge and the Arduino.
The question has been solved.


text:
Efficient way to store array with repeating values?
So I have about 2000+ X and Y values where I will look up the Y value for a given X value. If I store the values naively they won’t fit in memory, however there are a lot of repeating values and the X values are arranged in numerical order so I don’t really need to store them explicitly.
So my plan is to use the 3 most common Y values and have an array for all the Y values with only 4 possible values (So using only 2 bits with a bitfield), where 0,1 and 2 corresponds to the most common Y values and 3 tells the program to go fetch the value somewhere else, and here I am thinking a hash table/tree.
Before implementing all this stuff I thought I would ask here if anyone has a better way of doing this, such as if it’s possible/recommended to use the flash memory on the arduino for this or if there’s some better way to store the data. The Y data consists of analog read values which hover around a specific value (say 800) and vary +- 20 or so. I think a histogram of the Y data follows a normal distribution, but I currently do not have enough data to tell.

Could you give an example of how the data would look? How fast would lookup need to be?

Without a better understanding of what the data is or how you intend to use it it's impossible to give you real recommendations.
However it is simple enough to store your data in flash memory.
Since X is just a sequential value it can, as you have noted, be ignored.
For the rest, a simple array in flash which you then read with pgm_read_<X>() where <X> is the data size that you are using.
All this can be read on the Arduino PROGMEM Reference Page although the documentation is not great.
So here's a little example:
const int values[] PROGMEM = {
   100, 399, 2847, 1, -497, 32, 4370
};

void setup() {
    Serial.begin(115200);
    for (int i = 0; i < 7; i++) {
        Serial.println((int)pgm_read_word(&values[i]));
    }
}

void loop() {
}

The casting of the return from pgm_read_word as an int is needed to interpret the sign bit properly (it returns unsigned by default).

Nice, that would completely solve the memory issue :D What’s the speed penalty for storing the data in flash memory? I need to read relatively fast, I’m running the ADC at around 30 kHz and need to read data inbetween reads. From my understanding of flash memory it reads chunks at a time, right? So I could load parts of the array and store that in RAM while using that part of the array?

@BeaconofWierd At the time scales you are talking about the speed is negligible. No, flash does not read in chunks. It erases in pages, and writes in rows, but reads in bytes. It's just part of the instruction memory address space. Yes, it's slower than reading RAM, but only very slightly slower.

Ah, that makes it even simpler :) I updated the question with a more detailed explanation of how the data looks like. Even though I can store it in flash memory I probably still want to store it efficiently and you seem like the type of person who likes to think about how to store data efficiently ;)

@BeaconofWierd You would have to analyse the data more deeply to come up with some suitable storage system. And then you have to consider the increased time taken to decode your compressed data. If all your values are a small amount varying around an offset you can reduce your storage size by half by using a signed byte to store just the offset (±127). If you could reduce your values to just a selection of 16 discrete values you could store them in nibbles as 0-15 (2 values per byte). Or you could pack 3 values into 2 bytes for 5-bit (0-31) values (with 1 bit wasted per 2 bytes).

@BeaconofWierd: On AVR, reading from RAM takes 2 CPU cycles per byte. Reading from flash takes 3 cycles/byte. If you store 16-bit values, flash vs RAM is only 2 cycles difference. If you store an 8-bit offset, it's one cycle difference. Negligible in both cases if you only read one value every 33 µs.


text:
Antenna for ESP32-pico-d4
I am currently playing a bit around with the esp32-pico-4d, it does not have an onboard antenna, so an external antenna is needed, tho I don't know a lot about it so a little help would be appreciated.
I found this:
https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf
here one says that he literally just connected the antenna to ground and LNA_IN would that work?
and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)
(datasheet: https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf)

In my experience, an LNA connection typically implies that an antenna with a Low Noise Amplifier is required to meet the specifications - typically for signal strength. That's not to say it absolutely won't work without it, but rather it's typically used.
You'll need to select an antenna first, do some calculations and determine if you have enough signal to make your ESP32's receiver "happy". If your antenna doesn't deliver enough power, you'll have to add an LNA.
Wrt antennas, many boards are made today with the antennas etched from the copper. Some are quite good, and last I checked there were Gerber files available that could be used to replicate them on your PCB (assuming you use a board that meets the specs - dielectric constant is important). Another, maybe easier approach is to buy one of the miniature ceramic antennas - for example Johanson Technology makes them, and they're available from other mfrs through distributors - Mouser, for example. You may be able to wangle free samples - perhaps even some applications engineering support if they believe that will help them sell product!
Another source for antenna recommendations would be the Bluetooth Consortium website. They maintain a list of "prequalified" vendors - including some who make antennas. There may be other resources that would be useful. And don't overlook the usual open source repositories for help... there may be some out there who are hacking the same chip.
Anyway - got carried away - hope this helps.

here one says that he literally just connected the antenna to ground and LNA_IN would that work?

Yes. LNA_IN is the input to the Low Noise Amplifier - the input stage of the receiver / output stage of the transmitter.

and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)

You want one tuned for 2.4GHz. The simplest is a quarter wave dipole at 3.125cm in length. Better would be a proper 2.4GHz antenna of the kind you get on a WiFi router or some USB WiFi dongles.

well i was thinking more around this size:
https://www.molex.com/molex/products/part-detail/antennas/0479480001
its 3mm * 4mm * 3mm

Sure, if there's somewhere to mount it.

what do you mean?

If you're designing the PCB then no problem. If you're trying to attach it to an existing board then soldering it by hand could be tricky.

Of course, if you're designing the board then you could just design in a PCB trace antenna. They're free.

meaning I could just make a wide cobber trace and use it as an antenna as kinda seen on the esp32? (I am designing the PCB myself) and how thick and long would it have to be?

That is really not a question for this site. You should be asking on electronics.stackexchange.com. You've gone too technical for this site now.

ok thanks for the help

@MariusWanscher There is an example schematic in the datasheet where they show a small Pi filter between the chip and the antenna. They don't give component values for it though, just "TBD". Such a filter would improve the SNR but probably isn't essential for basic operation. All balancing is done inside the chip.


text:
CIPSEND Shows 404 error using aeduino + esp8266+01
I am trying  to save data in the data base with the get method. my url works fine when used with browser but when tried with esp shows page not found expection.
Arduino Code
SoftwareSerial ESP8266(10, 11); // Rx,  Tx

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

  ESP8266.println("AT+RST");
  delay(1000);
  ESP8266.print("AT+CWQAP\r\n");
  delay(2000);
  unsigned char check_connection=0;
  unsigned char times_check=0;
  Serial.println("Connecting to Wifi");

  while(check_connection==0)
  {
    Serial.print(".");
  ESP8266.print("AT+CWJAP=\"********\",\"*******\"\r\n");
  ESP8266.setTimeout(5000);
 if(ESP8266.find("WIFI CONNECTED\r\n")==1)
 {
 Serial.println("WIFI CONNECTED");
 break;
 }
 times_check++;
 if(times_check>3)
 {
  times_check=0;
   Serial.println("Trying to Reconnect..");
  }
  }
  delay(5000);
}

void loop() {

  // put your main code here, to run repeatedly:
   String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "homeautomationinternal.xyz"; // api.thingspeak.com
  cmd += "\",80";
  ESP8266.println(cmd);
  if(ESP8266.find("Error")){
    Serial.println("AT+CIPSTART error");
    return;
  }
  String getStr = "GET /auto/addlightvalueuseruno?userid=aravind";
  //getStr += String(temp_f);
  getStr +="&";
  getStr +="value=1";
  //getStr += String(humidity);
  getStr +=" HTTP/1.1\r\nHost: homeautomationinternal.xyz";
  getStr += "\r\n\r\n";
  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  ESP8266.println(cmd);
  ESP8266.setTimeout(2000);
  if(ESP8266.find(">")){
    ESP8266.print(getStr);
   Serial.println(cmd);
  }
  else{
    ESP8266.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
  }
   Serial.println(getStr);
  delay(5000);

}```

and the serial monitor data is

```AT+CIPSTART="TCP","www.homeautomationinternal.xyz",80

CONNECT

OK
 AT+CIPSEND=98

OK
>
busy s...

Recv 98 bytes

SEND OK

+IPD,1245:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>404 - File or directory not found.</title>

Server Error

<fieldset>

404 - File or directory not found.

The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

 </fieldset>

CLOSED

my website runs on iis server..
please help me with the arduino code and error which I am getting in the serial.monitor and how to resolve it.

As I am send data from Arduino to my website using get method I thought there may be any error with the hosting technicque @jsotola

Just ignore the iis please help me with the error and how to resolve it

how should we help you? the url is not valid for the server. how should we know what is a valid url on your server?

please let me know what all the details you require iwill provide you@Juraj

why this url? does it work from browser?

yes it works for browser . this url www.homeautomationinternal.xyz/auto/addlightvalueuseruno?userid=aravind&value=1 returns a json value 1

this is a home automation project which activates relay.. the arduino sends data to server using get method and we can see the data in website@Juraj

in code I don't see www in hostname

do we need to provide the www in host name...didnt work even after providing www in host name.. i am getting an error that webpage is not found i.e 404 error.

did you add the www in Host header too? 'www' is the name of the server. you can't leave it out

yaa i have added didnt work

You server is set up to redirect everything to https://www.homeautomationinternal.xyz which the ESP-01 doesn't like. You'd be much better off programming the ESP-01 directly with your website interaction code so that then it can handle the connections properly.

can you please help me with it how to do that@Majenko

and how did you came to know that its redirecting to home page

try AT+CIPSTART=\"SSL\", with cmd += "\",443";


text:
Using HC-SRO4 sensor and looking for obstacle
I am working in TinkerCAD, I want to design and simulate a circuit in which there are following components: 1.)An Arduino board. 2.)A potentiometer 3.)An HC-SRO4 sensor 4.)An LED.
So, the sensor should be able to tell if the range that has been set via the potentiometer has any objects in it or not. And if there are one or more objects in that range then the LED should also light up. Also, the user should be able to change the range using potentiometer during simulation.
I have attached the code here, but for some reason, I don't feel satisfied. Here is a list of the possible reasons. 1.) For LED lightening up, I had to use another if else , since it was showing an error else used without a previous if if I used LED in the same if else2.) The theoretical range for the sensor I have used is 2cm-400cm but in my circuit, it was not showing the upper range as 400cm.
Please tell the possible solutions. Also, can I improve my code and circuit
Here is the code which I used.
const int echoPin = 6;
const int pingPin = 7;

void setup()
{
 Serial.begin(9600);//Starting serial terminal
}

void loop()
{
  int sensorValue = 0;//Setting variable
  int mappedValue = 0;
  const int potentiometerRange = 0;//setting the buttons to variables to avoid confusion.
  long distance;//declaring a varible in loop because we can change the range during runtime.
  long actualDuration;//...
  long duration;
  pinMode(A0,INPUT);
  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);//
  sensorValue = analogRead(potentiometerRange);//reading the potentiometer value.
  mappedValue = map(sensorValue,0,1023,2,400);//mapping the value accordingly for ultrasonic sensor.
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);//to ensure a clean high pulse later
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);//to trigger the ping.
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);
  pinMode(echoPin,INPUT);//noe echo which tuns low in the time when waves return back.
  duration =  pulseIn(echoPin,HIGH);//time calculated by sensor
  //calculation of distance from any object
  actualDuration = duration/2;//reducing the time in half for the distance is half only.
  distance = 0.0343*actualDuration;//keeping in mid that speed of sound is 343 m/s and pulseIn returns time in microseonds.
  if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);
   delay(500); // Delay a little bit to improve simulation performance
}

I'm also attaching the picture of my circuit.

I don't feel satisfied .. maybe because you didn't have your morning coffee .... lol ...

What does "not showing the upper range as 400cm" mean?

@chrisl it means that the green area that is there during simulation which is kind of in front of the sensor, there we can look for the range right, it's showing 334.5 cm and not according to the theory as 400 cm.

@jsotola lolol, pm for these queries lol

For me that sounds like a Tinkercad problem. Simulators like Tinkercad are very limited, so you might get strange results, when hitting these limits anywhere. When using a real Arduino, you might not see this behavior

There's not much code there, so not much to optimize. I will however show you how to combine your two ifs.
You have:
if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
  else
    Serial.println("NO");
  if(mappedValue>=distance)
    digitalWrite(11,HIGH);
  else
    digitalWrite(11,LOW);

and I guess you tried this:
if(mappedValue>=distance)//checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
  else
    Serial.println("NO");
    digitalWrite(11,LOW);

That would be correct in Python where the indenting matters (oh how that brings back the PTSD of having to work with COBOL...) but not in C.  In C indenting is ignored completely. It's only there for our benefit in reading the flow of code.
Instead to group statements together within an if or an else (or any other conditional or loop structure) you wrap those statements in a block. That is, place { before it and } after it.  Thus:
if(mappedValue>=distance)//checking if the object is in range
{
    Serial.println("YES");
    digitalWrite(11,HIGH);
}
  else
{
    Serial.println("NO");
    digitalWrite(11,LOW);
}

Or with my preferred formatting:
if(mappedValue>=distance) { //checking if the object is in range
    Serial.println("YES");
    digitalWrite(11,HIGH);
} else {
    Serial.println("NO");
    digitalWrite(11,LOW);
}


text:
Running hardware interrupt function on NodeMCU ESP8266, Exception(0) after four iterations, can't disarm interupt function
I've been trying to test the stability and consistency of hardware interrupts on my NodeMCU ESP8266. I'm using the Arduino IDE. This sketch should not require any external circuitry and I think, but am not certain that the problem is a value overflowing somewhere. QUESTION 1: Can anyone point out where the problem that's causing Exception(0)?
The hw_timer_* functions are documented in the ESP8266 NONOS SDK reference pdf. The hw_timer_* declarations where not found by the Arduino IDE after I set it up with the board manager url here, so I copied hw_timer.h and hw_timer.c from the Expressif github repo into the same folder as my .ino file. The interrupt functions run now, but after four iterations, I get the exception & a stack dump and then the board reboots with this rst message:
 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

The code of my sketch is here. You shouldn't need any pins or anything.
EDIT: I added volatile before the 3 vars referenced in interrupt and in the other fns.
#include "user_interface.h";
#include "hw_timer.h";
#include "hw_timer.c";

// interrupt interval used for my hw_timer
#define timerInterval 100

// the number of cycle count samples we collect before analyzing
#define totalSamples 500

volatile uint32_t cycleSamples[totalSamples];
volatile uint16_t cycleSampleCount = 0;

// calculate min/max/mean
uint32_t elapsedCycles; // the number of cycles elapsing between two samples
float elapsedSum = 0; // cycles are large numbers...just in case we exceed 2^32 we use a float
uint32_t elapsedMax = 0;
uint32_t elapsedMin = 0xFFFFFFFF;
uint32_t elapsedCount = 0;
float elapsedMean;

// for std dev calculation
float diffSumSquared = 0;
float variance = 0;
float stdDev = 0;

// set to true by the timer fn when it has gathered the samples
volatile bool analyzeSamples = false;

// The hardware timer callback function must NOT be defined with ICACHE_FLASH_ATTR.
// Interrupt callback functions must be in IRAM, because the flash may be in the middle
// of other operations when they occur. Do this by adding the ICACHE_RAM_ATTR attribute
// on the function definition
// @see https://arduino-esp8266.readthedocs.io/en/latest/reference.html#interrupts
ICACHE_RAM_ATTR void my_timer_callback(void) {

  if (analyzeSamples) {
    // if this fn has collected all the samples, we have to skip this until it’s finished analyzing them
    // and resets this
    return;
  }

  if (cycleSampleCount >= totalSamples) {
    // we can't disable this timer
    analyzeSamples = true;
    return;
  }

  // take a peek at the cycles counter to check timing accuracy
  cycleSamples[cycleSampleCount] = ESP.getCycleCount();
  cycleSampleCount++;

}

void setup() {

  Serial.begin(115200);

  for(uint8_t i=5; i>0; i--) {
    Serial.printf("counting %d\n", i);
    delay(1000);
  }

  // START THE SAMPLE TIMER USING HARDWARE INTERRUPTS
  // use NMI_SOURCE for highest priority and quickest/most accurate timing
  hw_timer_init(NMI_SOURCE, 1);
  hw_timer_set_func(my_timer_callback);

  // If NM is used as the ISR source for auto-loading the timer, parameter val of hw_timer_arm can not be less than 100
  hw_timer_arm(timerInterval);

}

void loop() {
  // TODO we need to do something nondeterministic here to see if it fucks up timing of interrupts

  if (analyzeSamples) {

    // this doesn’t work to try and disable the interrupt fn
    // hw_timer_set_func(0);
    // nor does this
    //hw_timer_arm(0);

    Serial.println("Sampling complete, analyzing...");

    elapsedSum = 0; // cycles are large numbers...just in case we exceed 2^32 we use a float
    elapsedMax = 0;
    elapsedMin = 0xFFFFFFFF;
    elapsedCount = 0;

    // we loop from the 1th (i.e, the second) item
    for(uint32_t i = 1; i<totalSamples; i++) {
      elapsedCycles = cycleSamples[i] - cycleSamples[i-1];
      Serial.printf("%d %d\n", i, elapsedCycles);
      elapsedSum += (float)elapsedCycles;
      elapsedMax = max(elapsedMax, elapsedCycles);
      elapsedMin = min(elapsedMin, elapsedCycles);

      elapsedCount++;
    }
    // calculate mean
    elapsedMean = elapsedSum / (float)elapsedCount;
    Serial.print("Average elapsed cycles: ");
    Serial.println(elapsedMean);
    // report min/max
    Serial.print("Elapsed cycles max: ");
    Serial.println(elapsedMax);
    Serial.print("Elapsed cycles min: ");
    Serial.println(elapsedMin);

    // calculate the variance/std dev
    diffSumSquared = 0;
    for(uint32_t i = 1; i<totalSamples; i++) {
      elapsedCycles = cycleSamples[i] - cycleSamples[i-1];
      diffSumSquared +=  sq(elapsedCycles - elapsedMean);
    }
    variance = diffSumSquared / elapsedCount;
    Serial.print("Variance: ");
    Serial.println(variance);
    stdDev = sqrt(variance);
    Serial.print("Std Dev: ");
    Serial.println(stdDev);

    // reset the samples to zero and let's try again
    Serial.println("Gonna reset...");

    ets_intr_lock( ); //close interrupt
    for(uint32_t i = 0; i<totalSamples; i++) {
      cycleSamples[i] = 0;
    }
    cycleSampleCount = 0;
    analyzeSamples = false;
    interrupts();
    ets_intr_unlock(); //open interrupt
    system_soft_wdt_restart();

    Serial.println("Reset complete.");

//    stopStopStop = true;

  } else {
    Serial.println("not yet!");
  }
  Serial.println("sleeping 1...");
  delay(1000); // sleep 1000ms

}

This brings me to QUESTION 2: How do you disarm/cancel a hw_timer? As you can see in this code, I've tried setting the FN to zero and/or null and I've also tried setting hw_timer_arm(0).
The exception and stack dump seem to consistently happen after the sleep 1... debug message which corresponds to the end of the loop() function. Some typical debug output:
// useful and happy output above right up to this point
497 8000
498 8000
499 8000
Average elapsed cycles: 8000.00
Elapsed cycles max: 8263
Elapsed cycles min: 7738
Variance: 396.13
Std Dev: 19.90
Gonna reset...
Reset complete.
sleeping 1...

Exception (0):
epc1=0x40201030 epc2=0x00000000 epc3=0x400043a3 excvaddr=0x00000000 depc=0x00000000

>>>stack>>>

ctx: sys
sp: 3ffedf20 end: 3fffffb0 offset: 0190
3ffee0b0:  00000000 00000000 00000000 4010480d
3ffee0c0:  40105513 00000000 00000000 00000000
3ffee0d0:  00000010 00000000 00000000 40000f68
3ffee0e0:  00000004 00000000 40000f58 00000000
3ffee0f0:  60000200 3fffeed0 00000002 7c097c08
// giant stack dump continues....

Any help would be much appreciated.

I have not looked at your code in detail, but you should declare any global variable that can be changed inside an ISR as volatile, which you haven't done.

@StarCat thanks for that. I've added volatile before each of the 3 vars mentioned in both the interrupt fn and in the other fns. It still crashes and dumps the stack after about four iterations.

So these docs say that RST cause 4 is watchdog reset. Evidently arduino has a watchdog timer to check and make sure that your program isn't stuck in an infinite loop. Therea are some tips in that link on how to avoid this reset. Generally speaking, you need to make sure your loop doesn't spend too much time doing any one thing or handling too many interrupts or it might start to get overwhelmed and then the arduino code can't get around to all the housekeeping it has to do.
Regarding the disabling of a hardware timer function, I posted an issue on the ESP8266 github repo and someone offered what looks like a helpful response, which I have not tested. They suggest:

Call hw_timer_init with second argument = 0; then in your ISR call hw_timer_arm() if you want to keep it going and do not call it if you want to "disarm."


text:
Power MPU 6050 module through pin AD0
TL;DR: is it safe to power a MPU 6050 module through its AD0 pin instead of VCC?
We managed to have two MPU 6050 modules on the same I2C buffer by changing the address of one of them by connecting its AD0 pin to the same current origin used for VCC.
We found out that we can get the same result if we just switch the power cable which goes to the VCC pin to the AD0 pin: the module changes its address and we are able to read its data normally.
This would be a better configuration for us because, if the AD0 cable ever got disconnected, we wouldn't get anything from the second module but we would still get uncorrupted data from the first one. In the other case (cable to both VCC and AD0), if the AD0 cable got disconnected, we would get corrupted data.
So the final configuration would be: GND, SCL, SDA pins connected normally, power to AD0, pin VCC left unconnected.
The question is: is this a safe configuration or is it better to just leave the VCC pin connected normally and get another cable to the AD0?
From empirical tests it looks like it works fine, but we couldn't find any confirmation and are not experts on the matter.

Theoretically that should be OK.
According to the datasheet the MPU6050 consumes no more than 3.9mA with all the internal options turned on. That is below the limit of 25mA sustained current from a single IO pin for the ATMega chips. Just be aware of the total limit of the ATMega's power pins of 200mA, but it would take a lot of modules to reach that limit.
Since the MPU6050 is a 3.3V device your modules most likely have a voltage regulator on them to allow powering from 5V. That should mitigate any voltage droop caused by the higher impedance of using an IO pin as a voltage source.


text:
Send data before raising edge of a Clock
I'm trying to control a LED strip that has a custom protocol (developed above of I2C).
But in my tests i was successful figuring out how it works :
You set Clk to zero , you send a bit in the data line , then you set Clk to high. Based on the pixels number , i should send 16bits for each color (Red Green Blue).
I was able to generate a Clock signal at 8MHz with this code :
const byte Clock = 9;
const byte Data = 10;

void setup ()
{
 pinMode (Clock, OUTPUT);
 pinMode (Data, OUTPUT);
 digitalWrite(Data, HIGH);
 TCCR1A = bit (COM1A0);
 TCCR1B = bit (WGM12) | bit (CS10);
 OCR1A =  0;
 }

 void loop ()
 {
 ...
 }

My questions :
How could i send data at that specific time when the clock is at zero ?
Note that using digitalWrite() function was not working due to the frequency limitation of that function.
Thanks for any helpful information.

@Nick Gammon : i think i have to mention you :p

That sounds more like SPI than I2C to me. You can change the clock polarity and the sampling edge by changing the SPI mode.

The SPI sends bytes separated with a small time interval , is't possible to send multiple bits with no time interval ?

When you have a synchronous clock there is no concept of "time interval". Time is irrelevant. That's why you have a clock signal. Only the change of signal level in the clock is relevant. If you have something that requires data at precise times with no variance in the timing then you don't have a clock signal, and the communication is asynchronous (like UART).

I meant a delay between transfer of bytes

Unless you have a very very strange device then nothing cares about delays. SPI doesn't even have the concept of bytes.

That is the whole point of a protocol being synchronous. It's all synchronised by the clock signal. Data is read when the clock changes from LOW to HIGH (or the other way around for some devices). It doesn't care when that change happens. On that it does happen.

However if you gave us a clue what this LED strip and its protocol actually are then we would be in a better position to help you. Without that we're just pissing in the wind.

Thank you for this clear and simple clarification of how SPI works , i'm sure SPI is the choice to go with , the above code turns on all the LEDs with high intensity since data is always at 1. Now i'll try to instantiate an SPI communication with the LEDs and see how it works.

There are some strange protocols out there though. Can you please share the device and datasheet that you are working with?

There's no indication about the version number of the driver , i've attached pictures to the post ,i've tried to debug and test to see the Driver pinout (attached also)...

Are there no numbers on any of the chips?

Nothing , some mask is covering all the chips

After a night of continuous tests i figure out how to control correctly the LED strip using the following :
1- To apply any RGB value (a pixel) you have to send a compete frame of data to all the pixels. In my strip i have 12 pixels ,so to turn for example the first pixel into red , i have to send 11 zero pixels then the red pixel.
2- The delay and timing as mentioned above by @Majenko was the key, you just set the data and pulse the clk , that easy.
3- the protocol used isn't SPI or I2C , it's a custom protocol based on a custom driver developed by a private company (not a driver for general use or market , it was dev for a big wall lighting project).
#define setPin(b) ( (b)<8 ? PORTD |=(1<<(b)) : PORTB |=(1<<(b-8)) )
#define clrPin(b) ( (b)<8 ? PORTD &=~(1<<(b)) : PORTB &=~(1<<(b-8)) )
#define Data 7
#define Clk 9

void setup() {
pinMode(Data,OUTPUT);
pinMode(Clk, OUTPUT);
Serial.begin(9600);
}

void loop() {
int i, j, k, q, r, lim_j, lim_i;
int red, green, blue;
for(k=0; k<12; k++)
{
r= k%3;
lim_j = 2 - r;
q = k/3;
lim_i = 3 - q;
Serial.print(lim_i); Serial.println(lim_j);
clrPin(Clk);
delayMicroseconds(5);
setPin(Clk);
delayMicroseconds(5);

for(i=0; i<4; i++)
{
  for(j=0; j<3; j++)
  {
    if(i==lim_i && j==lim_j)
      one_pixel(1200, 0, 0);
    else
      one_pixel(0, 0, 0);
  }
}
clrPin(Clk);
delay(1000);
}
}

int one_pixel(int red, int green, int blue)
{
rapid_serialize(red);
delayMicroseconds(5);
rapid_serialize(green);
delayMicroseconds(5);
rapid_serialize(blue);
delayMicroseconds(5);
clrPin(Clk);
}

inline void rapid_serialize (uint16_t color) //just a copy for now , not a pointer
{
uint16_t bit_shift = 32768;
while (bit_shift)
{
 clrPin(Clk);
 bit_shift = bit_shift>>1;
  if ((bit_shift & color) == 0)
      clrPin(Data);
  else
      setPin(Data);
 delayMicroseconds(5);
 setPin(Clk);
 delayMicroseconds(5);
  }
 }

It sounds like you have some misconceptions.
In order to work with clocked signals like in SPI, you set your data line(s) to the desired value, and then raise the clock signal from low to high. The receiving device detects the low to high transition and reads the state of the data lines.
If you did it in the other order (switch the clock signal from low to high, then set the data pin(s).) then the receiver would detect the clock rising edge and try to read the data value before it was set correctly.
With a clock line like in your setup, the communication doesn't rely on fixed timing. The clock line tells the receiver when the data is available, and you can use whatever clock timing you want (up to the max speed supported by the hardware.)

Absolutely right , i figure out the solution after a nightmare of testing.
The problem was actually with the LED driver ,it's not working with any common serial protocol.
Thanks for the help


text:
ESP01 and Arduino - Serial port confusion
I'm trying to understand how to think about ESP01 devices and arduino connectivity
I purchased one of the USB programmers from Ebay to program the ESP01 - this works nicely, I can see the ESP doing things (I have it pinging a server sending data back and forth)
Obviously, the ESP01 has very few GPIO pins, so I'm interested in connecting to an arduino so I can combine the Arduino's IO with the Wifi on the ESP, and this is where I'm getting a little stuck. I'm assuming I have to connect the RX pin on the Uno to the TX on the ESP and the TX on the Uno to the ESP RX to set up the connection, but I'm confused as to which serial port to use on the Uno.
Specifically:

are the TX/RX pins on the arduino actually the same serial port as the USB connector - i.e if my intent is to plug the arduino into a computer to talk to it over USB, should I not then re-use the TX/RX pins to talk to the ESP
if so, should I look to software serial or something similar and use other IO pins on the arduino to connect to the ESP01

... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

yes and yes. and you can use the Arduino to upload to esp-01, but it is not so simple. I recommend you to upload a firmware to esp-01 with the programmer and use a corresponding library in Arduino. for example https://github.com/jandrassy/WiFiEspAT

Cool - thanks, so the first yes, is that the RX/TX pins are the same serial connection the USB port uses? (just making sure I fully understand)

yes. Atmega328p has only one UART  peripheral for hardware Serial.

It's a pity that all newbies get hooked on the artificial (and false) necessity of combine ESP01 and Arduino in a single project. A newbie should let the complexities of attaching one device to another to the future, and just start with a ESP8266 version with more GPIOs, like ESP12.

@mguima, esp8266 was developed to be used as WiFi adapter, not as standalone MCU. do you want to write sketches for CC2541 on HC-11 BLE adapter? it is a MCU too.

@juraj, this question is dumb and pointless. I didn't say anything about writing sketches for CC2541 or for HC11 - or for TMS1000, neither. But, for most of the things that a newbie could want to do, simple things like blink a LED or switch a relay, an ESP8266 is enough, and, YES, in a non-critical environment, ESP8266 can be used as a standalone CPU. A professional that would REALLY need to use Arduino and ESP8266 surely would not asking for help here in StackExchange. But, most of times, using ESP8266 as a Wifi adapter for an Arduino is just a unnecessary and complicated hype

@juraj It's NOT TRUE that "esp8266 was developed to be used as WiFi adapter, not as standalone MCU".  It seems that you said that only for disagree with what I said. Can you point to sources for this information? ESP8266 datasheet says "With the complete and self-contained Wi-Fi networking capabilities, ESP8266EX can perform either as a standalone application or as the slave to a host MCU."  If it were intented to be just a WiFi adapter, why would it have peripherals and available GPIO's?

@mguima, it doesn't say with what goal it was developed. It would be very strange to waste so many pins for boot configuration on a standalone MCU. Most of the  docs are about integration with a host MCU. There was no published SDK initially.

The Arduino UNO only has one serial port. That is pins 0/1 (RX and TX), which is mapped to the Serial object.
Those pins and that object are also used for communication with the PC through the USB connection. That means you can't easily use them for both PC communication and ESP8266 communication. It's possible, but it gets messy.
That is why many people use SoftwareSerial because that can work on any combination of pins on the Arduino that you like.

... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

Again, that is possible, but very messy. You could possibly get things to pass through from Serial to a SoftwareSerial instance, but it's not reliable (SoftwareSerial in general is not reliable for sustained transfers of data), and using the Arduino as a dumb UART interface would entail changing the wiring to pins 0/1 when you wanted to program.
So it's far simple to just use your USB interface for programming. Either that or set up OTA programming for the ESP8266 so you don't even have to use wires.

This is great, thanks for the guidance.


text:
How to compile Arduino Framework with GNU
I'm wondering if it's possible to use GNU (g++) to compile a arduino Sketch.
I wanna be able to unit test my code with catch2.
g++ -std=c++11 <filename> works well with catch2, but I obviously does not recognize Arduino's framework (Strings, Serial etc).
What I think is, maybe if I use Arduino's compiler [ which is compatible with -std=c++11 I would be able to do run the catch2 with the Arduino framework.
Does anyone knows where to find Arduino's compiler? or how to make GNU accept Arduino's framework?

Never heard of "catch2". But the  "arduino" compiler is g++. avr-g++ to be precise. If you're using Linux you can install it as a system package if you like.

But if you're asking if you can compile Arduino code to run natively on a PC, no, not without using a core and board written specifically for the PC. You might look at Wiring-Pi as a starting point for that.

https://forum.arduino.cc/index.php?topic=662682.msg4637993#msg4637993

Some keywords that may help: "arduino-builder", "Sudar Arduino Makefile", "simavr".


text:
How can I use multiple 7-segment displays in Tinkercad
I need to connect five 7-segment displays using Tinkercad.
We know that Tinkercad doesn't have an Arduino Mega to use its pins.
How can I do this without the Arduino Mega?

Multiplexing? No idea what tinkercad has / does.

use a display module with a control chip

It sounds like you will need to multiplex them.
Assuming common cathode LEDs:
Set up a transistor for each digit that activates the ground for that digit. (Lighting all the segments of a digit will probably exceed the max current sink of one of your digital pins.) You may be able to drive a single segment directly from an output pin, assuming it's current draw is ≤20 mA. If the segments draw > 20 mA then you will likely need transistors for the segment drivers as well. (The max output of a pin on most Arduinos is actually 40 mA, and if the average current when multiplexed across 5 digits is < 20 mA, you might get away with drawing up to 40 mA per segment. I'd ask somebody with more electronics experience than me to confirm this.)
Write your code to switch one digit's ground on at a time, after turning on the desired anode (segment) pins. Cycle through the digits rapidly and they will all appear to be on at the same time.
The pseudo-code:
setup {
   digit index = 0
   turn all pins (segment anodes and digit cathodes) to open state
}

loop {
   set up segments pins for digit[index]
   Turn on cathode for that digit
   short delay to allow segments of current digit to glow
   turn off cathode (ground) of current digit
   digit index = (digit index + 1) % num_digits
}

The above would require a digital pin for each segment, and a pin for the ground of each digit. (7 + 5 = 12 digital pins total.) Without multiplexing, you'd need 7x5 = 35 digital pins, and would still have to make sure you didn't exceed the total current output limits of the Arduino. (35 segments x 20 mA/segment would be 700 mA total.) Most Arduinos have a total current output of no more than 200 mA across all pins, so you could not light up all the segments of more than 2 digits at once, assuming 20 mA/segment.)
Note that it might be easier to ignore all of the above and get a serial LED display driver like a MAX7219. You just need 2 digital lines to drive that, and it will control 8  8-segment digits (7 segments plus a decimal point at each position)


text:
WIFI Bee ESP8266, MySQL and PHP
I am trying to update a db table using a WIFI Bee.
For the life of me, I can't figure out how to connect to and program the WiFi Bee ESP card. I've looked on DFRobot's website and other websites to no avail.
The PHP code is
try {
        include "../Common/ConnectionStringArduino.php"; // Create a connection

        // Update state
        $sql    = "Update `Status` SET `DateTime`='".time()."',`State`='".$_GET["CurrentState"]."' WHERE `Device`='Arduino';";
        $result = $con->query( $sql ); if($result === FALSE) { die(mysqli_error());}
        mysqli_close($con);
        echo "Success";
    } catch (Exception $e) {
        echo "Error";
    };

If i call the page by typing the URL of this page on a browser window it updates the database on a Raspberry Pi but so far I had no luck in doing it via the WiFi Bee module.
I have a Rome v2 board with inbuilt WiFi Bee socket.
I am familiar with AT commands (but not a ginus)
My Arduino code
#include "esp8266.h"

#define ssid "XXX"
#define pass "YYY"
Esp8266 wifi;

void setup() {
  delay(2000);            // It will be better to delay the setup for 2 seconds for esp8266 module to initialize
  Serial.begin(9600);     // Terminal serial port baud rate for USB debugging on the pc serial monitor
  Serial1.begin(115200);  // Xbee Serial port baud rate should be set the same to 115200

  // Items for WiFi Communication
  wifi.begin(&Serial1, &Serial);    // Setup the WiFi to use Setial1 and Serial to debug
  if (wifi.connectAP(ssid, pass)){  // Connect to the AP
    wifi.debugPrintln("Connection to AP sucessful!");
  } else {
    while(true);
  };
  wifi.debugPrintln("esp8266 ip:" + wifi.getIP());
  wifi.setSingleConnect();
  if (wifi.connectTCPServer("192.168.1.17", "80")) { wifi.debugPrintln("Connection to Pi Successful!");}
  else                                             { wifi.debugPrintln("Connection to Pi Failed!!!");};
}

void loop(){
  if(Serial1.available()) {
   ....
   For god sake how do I call this page : "http://192.168.1.17/Arduino/IAmAlive.php?CurrentState=1" to update the database entry using this beeeeeee
   ....
  }
}

The bee gets an IP upon successful connection
Connection to AP successful!
esp8266 ip:192.168.1.23

and i can ping the bee
Reply from 192.168.1.23: bytes=32 time=78ms TTL=255
Reply from 192.168.1.23: bytes=32 time=99ms TTL=255
Reply from 192.168.1.23: bytes=32 time=25ms TTL=255
Reply from 192.168.1.23: bytes=32 time=6ms TTL=255

But have no idea how to call the page to update the db. I have read endless blogs with no luck of solving my simple issue
Please help


text:
What methods are there for tracking presence in rooms?
Im wanting to automate the lighting in my house, e.g. turn on lights when entering a room without having to fumble around with my phone or switches.
I have looked at audio, PIR and radar sensors, are there any more alternatives? For example using a wifi mesh to triangulate which room a phone is in.
Any suggestions welcome.
P.s. I may end up with one of the earlier options, I just want to see what is out there.

check out opencv

Jsotola OpenCV seems a bit excessive for the number of rooms I need to monitor, but for a single location could work

Maybe a combination of PIR and door-switch (like those used in alarm systems). By combining both you know not to turn of the lights, even if the PIR hasn't picked up any movement for a few minutes, which you're sitting on the couch. I personally really like light-switches. I'm only half joking here. An automated system only rarely has to malfunction for it to be more annoying that having to flick a switch.

what's wrong with pir and radar?


text:
Writing and Reading data from RTC module EEPROM_Arduino
i have took below code from https://lastminuteengineers.com/ds1307-rtc-arduino-tutorial/. i am not understand what these codes are doing. please help me to understand.
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB

Thanks

how many bits long is eeaddress?

These two lines write a 16 bit (2 8-bit) value, which is signed -32768..32767 or unsigned 0..65535.
Assume a value in bits: 10101010 11001100
Statement 1:
Wire.write((int)(eeaddress >> 8)); // MSB

The first statement shifts the value 8 bits (positions) to the right; this is called the MSB (Most Significant Byte, the left 8 bits). Bits on the right are clipped / fall off. Thus
10101010 11001100

will become
00000000 10101010

When casted to an 8 bit value you get:
10101010

Statement 2:
Wire.write((int)(eeaddress & 0xFF)); // LSB

The second statement will get the LSB (Least Significant Byte). This used the AND operator, meaning a bit is only 1 if both values are 1. 0xFF is the 'mask'
Original value: 10101010 11001100
Mask:           00000000 11111111
                ----------------- AND (&) operator
Result:         00000000 11001100

As you can see only the right 8 bits are kept. When casting this to an 8 bit value:
11001100

Do you also know why there is an int cast ((int)...)?

@Gerben; actually I would either expect a 8 bit type cast (uint8_t or int8_t  cast as the result is always 8 bits, or no cast at all, as the caller probably expects an 8 bit variable. Even if the caller expects 16 bit (which would be unnecessary much), the 8 bit argument will automatically be casted to 16 bits, without a need for a cast in the two lines provided in this code.

Thank you. Seems like the Wire library will cast it (back) into an uint8_t anyways.

@Gerben, true, thus casting it within the calling write method is not needed.

Thanks @Michel Keijzers

If the answer helped you, upvote the answer (the arrow next to the answer). If the answer solves your problem, accept the answer (icon next to the answer).


text:
Sine wave using arduino uno
I am an adruino hobbyist, i want to make sine wave using arduino uno,
for that i using timer0 as interrupt, OCR0A set to 17 for 3.6khz interrupt(16000000/(100hz*36 interval)/256-1),
If i am using only one pwm pin i am getting correct frequency but when i enable two pwm pin i am getting only half if the frequency, kindly advise what is wrong and how to correct it.
.................................
This code i am getting correct frequency at PWM pin 9.
//
ISR(TIMER0_COMPA_vect)
{
OCR1A=(256+((((sin(num*3.14/180))*256))))/2;
//OCR1B=(256+((((sin(num*3.14/180))*256))))/2;
     num=num+10;
    if(num >= 360)
{
       num = 0;
    }
}

//
............................
This code i am getting only half of the previous frequency at PWM pin 9,10
//
ISR(TIMER0_COMPA_vect)
{
OCR1A=(256+((((sin(num*3.14/180))*256))))/2;
OCR1B=(256+((((sin(num*3.14/180))*256))))/2;
     num=num+10;
    if(num >= 360)
{
       num = 0;
    }
}

//

How did you configure your timer ? 2. The sin() function takes something like 100 µs per call.

You could use OCR1B=OCR1A since both are the same. But, assuming the problem is as StarCat said due to the ISR taking to long, I'd look into creating a table of SIN values.

A better method would be to generate a simple square wave then filter it into a sine wave. No need to mess with complex calculations or even lookup tables.

You are doing complex calculations inside an Interrupt Service Routine. This is not a good idea. Computing sines takes a large amount of time as this consists of multiple, complex floating point operations. Interrupt Service Routines should be short and as simple as possible.
This is probably the reason you can't have two PWM signals active at the same time at the same frequency. The ISRs simply take too long.
The solution would be to pre-calculate the desired waveforms or greatly simplify the waveform calculations (preferably without floating point). If you decide to pre-calculate, take care to stay within the limited amount of memory you have available on your Arduino. You can minimize the memory used by calculating and storing just 1/4 of a complete waveform and constructing the remaining 3/4 from these values.
This leaves the conversion of your PWM output to a real sine wave. How are you planning to do that?

If the table get too bit (uses too much RAM) you can look into using PROGMEM to keep the table in flash memory.

the lookup table needs to store only a 1/4 of the sine wave


text:
Come out of loop and execute Setup again
I want to end loop at a specific time and start setup again. Is this possible? (I can explain reason in case you require).

As others have suggested, that is not how an Arduino program works. It runs the setup function once, and then calls the loop function repeatedly and forever until it is powered down or reset. You'll have to explain what you're trying to do in order for us to help you get it working.

You could just call setup() yourself:
void loop() {
    if (some_condition) {
        setup();  // reinitialize everything
        return;
    }
    // etc.
}

But, as Majenko puts it, if you nee to do that it looks like there is
something wrong with your methodology.
That being said, it would be less suspicious if you only need to
reinitialize some specific part of your program. In this case you can
make a separate function for these initializations, and call it both
from setup() and, when needed, from loop():
void init_foo() {
    // ...
}

void setup() {
    init_foo();
    // other initializations...
}

void loop() {
    if (some_condition) {
        init_foo();  // reinitialize foo
        return;
    }
    // etc.
}

Not directly, no. You can reboot the Arduino though so everything starts from scratch (either through the watchdog timer or wiring a GPIO pin to RESET and pulling it LOW), but if you find you need to do this sort of thing then you should rethink your methodology so that you don't need to do this sort of thing.


text:
Make a code loop 100 times with a text on Serial Monitor
Ok, this is my code:
int rosso = 13;
int verde = 12;
int blu = 11;
int count = 0;
String command_on, command_off;
String s;
String enough = "stop";

void setup(){
  pinMode(rosso, OUTPUT);
  pinMode(verde, OUTPUT);
  pinMode(blu, OUTPUT);
  Serial.begin(9600);
  command_on = String("on");
  command_off = String("off");
}

void redToBlue(){
  if(count < 100) {
  rgb(0,255,0);
  delay(100);
  rgb(0,0,0);
  delay(100);
  rgb(255,0,0);
  delay(100);
  rgb(0,0,0);
  count = count+1;
  }
}

void switchOff(){
  rgb(0,0,0);
  delay(100);
}

boolean wait_command(){
  if(s == command_on){
    redToBlue();
  }
  if(s == command_off){
  switchOff();
  }
}

void accendi(){
  if(s == command_on){
  redToBlue();
  }

  if(s == command_off){
  switchOff();
  }
}

void rgb(int r, int g, int b){
  analogWrite(rosso, r);
  analogWrite(blu, b);
  analogWrite(verde, g);
}

void loop(){
 s = Serial.readString();
 Serial.println("What I have to do? ");
 wait_command();
}

When I open the Serial Monitor and type "on" there, the redToblue() function must loop 100 times. But in my case loops only one time then it stops. I think I have to change something inside loop() function and on redToBlue()...

You loop() function is the one that will be called when the program runs and it will keep looping around until you stop it.  So at the moment you have loop() doing the following:

Reading a string from the serial connection
Displaying a message to the serial connection
Parsing the string that was read and acting upon it.

So when your code runs you see it print the message and maybe do something with the light and then it stops/freezes.  Its not really frozen, its waiting for you to enter an answer.
So if you really want it to ask what to do and then then loop 100 times you need to do this:

Display the message.
Read the data.
Call wait_command() (after you have modified it)

void redToBlue(){
for (int count = 0; count < 100; ++count) {
rgb(0,255,0);
delay(100);
rgb(0,0,0);
delay(100);
rgb(255,0,0);
delay(100);
rgb(0,0,0);
}
} // Sorry I can't get the code to format.
I think you could also refactor the function to loop over an array of 4 rgb values.  I don't now if that would be better for the processor, it would look nicer :)

I'm not sure exactly what you want, but if you expect after a single command on to have it looped 100 times, you need to call the redToBlue function in every loop (within wait_command, that checks for a boolean if the on command has been requested, and when so, call the redToBlue function. When the off command is set, you reset the boolean.
Also wait_command is not a good name, as it does not wait for a command, but processes it.

yes I would like that If I type "on" loop 100 times, and if I type "off" doesn't do nothing, and rgb led is off.

It will also stop before 100 if you type "off" when 100 loops are not reached yet.


text:
Problem on color mixing lamp on Proteus Arduino starter kit
I set the circuit and couldn't illuminate, where is the problem?

Fritzing: https://fritzing.org/media/fritzing-repo/projects/c/color-mixing-lamp/images/Arduino%20Lamp%20Project.png

you have to run an appropriate sketch in the arduino

I thought my sketch was properly but there is a problem that rgb is not illuminating. i transferred hex code from arduino app, starterkit_basickit. on the book 9green 10red 11blue; a0red, a1green, a2blue, then i think set correctly.

what is the point of asking where the problem is, if you do not provide all of the available information ... determine where the problem occurs ... is it in reading LDRs or is it in lighting the LEDs? .... write a separate sketch to test each part

im not sure about the parts that i use. on arduino, parts were rgb led, 220 ohm resistor, 10k resistor, 3 photoresistor, 3 gel. i used 3 light dependent resistor for "3 photoresistor+3gel" is it correct? if it's correct, RGB should lit, but it doesnt. I'm new about using proteus and arduino. I just need to convert original arduino circuit to proteus. Here is the purpose: https://i.ibb.co/9yVtThk/image.png

just fixed by using TORCH LDR instead of normal ldr. FULLY WORKS.

just fixed by using TORCH LDR instead of normal LDR. FULLY WORKS.


text:
Is it possible to preform VIO from two cameras/IMUs on a dual-core ESP32?
Like the title says, I want to take in the synchronised data from two NXP breakout boards and two Ueye 1220LE cameras, and use VIO to fuse their data and get positions for both setups.
A lot of people have suggested running things like SLAM, which is similar to VIO, on something stronger than an Arduino, some specifically suggested using a version of a Raspberry Pi.
Now, I know that Raspberry Pis are stronger than an ESP32, but ESP32s are stronger than Arduinos, and since Pis are more expensive than an ESP32s and I need WiFi capabilities, before I buy a Pi, I was wondering if it would be possible to perform this on my dual-core ESP32.
And if the Pi isn't overkill and I needed all the processing power I could get, what version should I use? The Zero? The 3.0? The 4.0? Do let me know.

I haven't worked with the ESP-32, but it seems to me you're quibbling over pennies. Pis are cheap and very powerful. They run Linux, so there are tons of open source libraries available for them. You could install OpenCV, for example, and do computer vision quite readily.
I'd recommend at least a PI 3.
If you used an ESP-32 based system, would you run it as an Android device? The Arduino "OS" (And that the term OS is quite a stretch) is really just a setup function and a run loop. You should use a device with a real OS, including a file system, etc.


text:
Calculating fluid volume using arduino sensors
I would like to measure liquid sealant volume inside bike tires, using sensor located between rim beads.
I guess it would by possible, by using ToF sensor, that would measure distance between rim and fluid surface.

Yellow - fluid itself
Than I would like to calculate fluid volume by using a formula for torus ?cap?
In another words: drained fluid would look like this cut section (not to scale):

Is there any mathematical formula to calculate volume of such "cap", based on its height and two torus radiuses? I only found formula for "ball cap" volume...
Or maybe there is better approach to measure volume, and I am doing it wrong?

There certainly is a formula to calculate that torus cap volume, though this is Arduino SE and not Mathematical SE, thus off topic. How do you plan to get any kind of sensor inside the inner tube of the tire? You normally cannot cut them open and seal them again to still hold the typical 3 bar pressure

you could use a weigh scale to determine the mount of fluid inside the inner tube

Your question seems like about geometry. You should try another channel, not Arduino maybe.

How are you at integrals?

@chrisl - there are new bikes with tubeless tires and many users are converting to tubelesss. That's the only possibility for this type of measurement. I'm going to try another channel.

Ah, ok. Then it may be easier to make a capacitive sensor. Found this thread with a quick google  but there are certainly better resources, when you search for them

Thanks I would consider it.

This article doesn't have the answer, but it may be of some help in formulating an approach.

It may be helpful for someone: I haven't found any formula for torus cap yet. Only for ellipsoid cap, there: https://www.vcalc.com/equation/?uuid=7cbe5611-1e51-11e8-abb7-bc764e2038f2

If you need a ''small cap" compared to the rest of figure you can treat this cap as ellipsoid cap. Just tweak ellipsoid values, so that the curves matches circle of torus cross section in area I'm interested in.


text:
Fail starting Arduino IDE Ubuntu 18.04
for unknown reason, my Arduino IDE 1.8.12 stopped starting up ( worked OK before ).
Can anyone share some steps understanding why ?
edit1
after executing ./arduino
guy@desktop:~/arduino-1.8.12$ ./arduino
Picked up JAVA_TOOL_OPTIONS:
Set log4j store directory /home/guy/.arduino15
Gtk-Message: 17:15:18.630: Failed to load module "canberra-gtk-module"
java.lang.NullPointerException
    at cc.arduino.contributions.packages.ContributionsIndexer.parseIndex(ContributionsIndexer.java:134)
    at processing.app.BaseNoGui.initPackages(BaseNoGui.java:483)
    at processing.app.Base.<init>(Base.java:273)
    at processing.app.Base.main(Base.java:150)
guy@desktop:~/arduino-1.8.12$

it was a temporary problem with platform index file on server. to recover see https://forum.arduino.cc/index.php?topic=690045.0

did not solve the problem

then start ./arduino from command line to see the log

see edit 1 in question

Delete your arduino storage directory: rm -rf ~/.arduino15 being careful not to delete ~ instead.

it is the problem. did you delete the package_index.json file and the cache folder?

@Juraj I did delete the folder as noted on comment 1 ( in arduino15 older ), (in arduino folder ) there was nothing to delete

@Majenko I mv that folder, and now it is almost as fresh install ( what was important to me was all repositories that were installed ). it seems that additional boards should be configed again

and the file? did you delete package_index.json?

@Juraj - perhaps not, because I see it ( or it was re-created ). Lucky I was mv that folder. But again, I'll have to re-define boards. On the other hand, tools as: decoder, and 8266 Data upload, are there...

nothing should change if you only delete that one a file and the cache folder. stack trace decoder and SPIFFS upload tool are in Sketchbook folder in tools

@Juraj For some reason, I can't OTA now for that specific PC for every MCU I try - it is not a code problem. When I'm using my MAC laptop, same code, same MCU - it works as expected. Error ia " o response from device"

Firewall does this

@Juraj Mr.Know-all. Thankyou


text:
problem controlling rgb led with one button
I'm trying to make a lamp which quality to change color by pressing a
button, pressing once turns on red, pressing again turns on blue and so on, but I also want it to have a light effect in which it smoothly switches between different colors, my code does, however when pressing the button and getting to the last function and keep pressing the button no longer does the light change, it just stays in that state, I have been trying to solve it and investigating for hours but I do not get the expected result, I hope you can help me, thanks.
I enclose the wiring diagram and the code used.

#define varfija 0

int ledR = 11;
int ledB = 10;
int ledG = 9;
int pinButton = 7;
int buttonValue;
int count = 0;
int brillo;
int button_old = 0;

void setup() {
    pinMode(ledR, OUTPUT);
    pinMode(ledG, OUTPUT);
    pinMode(ledB, OUTPUT);
    pinMode(pinButton, INPUT);
}

void loop() {
    buttonValue = digitalRead(pinButton);
    if (button_old == 0 && buttonValue == 1) {
        count++;
        button_old = 1;
    }
    if (button_old == 1 && buttonValue == 0)
        button_old = 0;
    if (count > 4)
        count = 0;

    if (count == 0) {
        analogWrite(ledR, 0);
        analogWrite(ledG, 0);
        analogWrite(ledB, 0);
    }
    else if (count == 1) {
        analogWrite(ledR, 255);
        analogWrite(ledG, 0);
        analogWrite(ledB, 0);
    }
    else if (count == 2) {
        analogWrite(ledR, 0);
        analogWrite(ledG, 255);
        analogWrite(ledB, 0);
    }
    else if (count == 3) {
        analogWrite(ledR, 0);
        analogWrite(ledG, 0);
        analogWrite(ledB, 0);
    }
    else if (count == 4) {
        for (int i = 1; i < 255; i++) {
            analogWrite(ledR, i);
            analogWrite(ledB, varfija);
            analogWrite(ledG, varfija);
            delay(5);
        }
        for (int i = 255; i > 0; i--) {
            analogWrite(ledR, varfija);
            analogWrite(ledB, i);
            analogWrite(ledG, varfija);
            delay(5);
        }
        for (int i = 0; i < 255; i++) {
            analogWrite(ledR, varfija);
            analogWrite(ledB, varfija);
            analogWrite(ledG, i);
            delay(5);
        }
    }
}

sorry for my english, I don't master it

Do a Web search for “Arduino debounce button”.

It takes a 32555 milliseconds between button checks in state 4 (every 3.825s) so you have to hold it for some time and then it might get noticed...

You want to check the button, but at the same time run the animation that takes around 4 seconds. To combine these you'd have to change the animation code, so it no longer uses any delays. So it's no longer blocking the button code. But for example uses the time (millis) to determine the values or the red green and blue led. A simpler version of this problem is Blink without delay.

I posted an answer to a very similar question recently: https://arduino.stackexchange.com/questions/76084/rgb-led-and-a-push-button-in-tinkercad/76097#76097 Note how that code uses millis to debounce the button presses. You'll have to do something similar to get the LED color to change over time. I suggest a simple state machine where you have states for the different colors plus states for transitions between colors.


text:
Relative position using Accelerometer
I have a simple scenario please:
Two Arduino Nano 33 IoT devices started moving randomly from the same exact origin(Point = [X0, Y0, Z0]);
Can I use the coordinates queried from each device Accelerometer to get the Euclidean Distance between them?
In other words, Is the relative coordinate/position retrieved from the Accelerometer reliable?
Because I read that getting the relative position every time requires double integrations which leads to big accumulated error over time. Though I might be totally wrong.
Your help is very much appreciated.

What you heard (about double integration and accumulating errors) is correct. Mathematically, you can do this, by integrating each device's acceleration to get its current speed, and integrating the speed to get it's current position, then taking the vector difference in the their positions to get the distance between them.
If you had highly accurate accelerometers in a very noise-free environment (both mechanical and electrical noise), you could do it for a (short) while before the inevitable tiny errors (which are also being integrated!) begin to dominate the data and make the results useless. But as a practical matter - especially for us experimenters using inexpensive equipment and subject to a lot of mechanical and electrical noises on the experimental platform, plus environmental electrical noise - this will happen even more quickly.

Thanks for this level of details Robert.


text:
Boolean Logic With Chars For Motor Input Selection
Context of the code:
I am trying to control 2 DC motors through an H-gate, this means there are 4 inputs in total:
For DC motor 1: Input 1 (VCC) and Input 2 (GND).
For DC motor 2: Input 3(VCC) and Input 2 (GND).
Summary of the code:
The global variables are motinpN which are the pins connected to the different inputs.
An array, which is where the different PWM for the motor speeds are stored.
Char x, which is the variable used for the boolean logic.
Then comes the actual loop which consists of 4 similar functions, the "input selector" function and then the statements that turn the integers stored in the inpSpeedS[] arrays into motor speeds.
The issue:
The code won't enter the first loop, i.e it won't advance past
Serial.println("X equals:");
  Serial.print(x);"
I would like to know then, what I am doing wrong in order for this not to work?
   int Speed = 0;
const int motinp1 = 2;
const int motinp2 = 3;
const int motinp3 = 4;
const int motinp4 = 5;

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

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

void loop() {
  Serial.println("X equals:");
  Serial.print(x);

  if (Serial.available () && (x == '0')) {
    Serial.print("Which input?");
    x = Serial.read();
    Serial.println(x);
  }
  if (Serial.available () && (x == 'a'))
  {
    Serial.println("Input 1 selected");
    inpSpeedS[0] = Serial.parseInt();
    Serial.print("Input 1: ");
    Serial.println(inpSpeedS[0]);
   x = '0'; //reset x, goes back to input selection
  } if (Serial.available () && (x == 'b'))
  {
    Serial.println("Input 2 selected");
    inpSpeedS[1] = Serial.parseInt();
    Serial.print("Input 2: ");
    Serial.println(inpSpeedS[1]);
   x = '0';
  }
  if (Serial.available () && (x == 'c'))
  {
    Serial.println("Input 3 selected");
    inpSpeedS[2] = Serial.parseInt();
    Serial.println("Input 3: ");
    Serial.print(inpSpeedS[2]);
   x = '0';
  }
  if (Serial.available () && (x == 'd'))
  {
    Serial.println("Input 4 selected");
    inpSpeedS[3] = Serial.parseInt();
    Serial.print("Input 4: ");
    Serial.println(inpSpeedS[3]);
   x = '0';
  }
  analogWrite(motinp1, inpSpeedS[0]);
  analogWrite(motinp2, inpSpeedS[1]);
  analogWrite(motinp3, inpSpeedS[2]);
  analogWrite(motinp4, inpSpeedS[3]);
}

EDIT - I have turned the char 0 from a string literal null to an ASCII code for 0, and same for the other chars. It is still stuck outside of the function loops.

How it's possible that char  x = "0"; doesn't yeld on you that you are assigning pointer to C string into char variable?

@KIIV I haven't read any books on C yet, only done Udemy courses, so I unfortunately do not know what you're talking about, other than the most superficial I can google myself to in 10 minutes.
Could you please elaborate?

There is a huge difference between '0' and "0". First one is ASCII value of character zero, second one is pointer to memory, where the string containing {'0', '\0'}  is stored

Also note you have a shadow x variable in loop.  Probably not a good idea.

@Delta_G Maybe that edit should be removed anyway

Or just lose the "int" in front of x='0';

It's screaming on you:
sketch_jun13a.ino:7:11: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

 char  x = "0";

           ^~~

sketch_jun13a.ino: In function 'void loop()':

sketch_jun13a.ino:21:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "0")) {

                                    ^~~

sketch_jun13a.ino:21:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:26:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "a"))

                                    ^~~

sketch_jun13a.ino:33:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0"; //reset x, goes back to input selection

         ^~~

sketch_jun13a.ino:34:38: warning: comparison with string literal results in unspecified behavior [-Waddress]

   } if (Serial.available () && (x == "b"))

                                      ^~~

sketch_jun13a.ino:41:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:43:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "c"))

                                    ^~~

sketch_jun13a.ino:50:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:52:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "d"))

                                    ^~~

sketch_jun13a.ino:52:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:58:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

Basically this is char variable with assigned character literal: char x = '0';
And this is C string: char str[] = "0"; or its equivalent: char str[] = {'0', '\0'};. Where '\0' is so called NUL Terminal character.
Everything about C strings you need to know
EDIT:
Simple demo for the "parser" - it's not perfect but should be enough:
char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup() {
  Serial.begin(9600);
  Serial.println("Select channel [a..d] and speed [0..255]: ");
}

void loop() {

  if (Serial.available() > 1) { // wait for more characters in buffer
    switch (Serial.read()) {
      case 'a': inpSpeedS[0] = Serial.parseInt(); break;
      case 'b': inpSpeedS[1] = Serial.parseInt(); break;
      case 'c': inpSpeedS[2] = Serial.parseInt(); break;
      case 'd': inpSpeedS[3] = Serial.parseInt(); break;
      default : return; // skip invalid characters like line endings
    }

    Serial.print("Speeds: ");
    for (auto spd : inpSpeedS) {
      Serial.print(' ');
      Serial.print(spd);
    }
    Serial.println();
    Serial.println("Select channel [a..d] and speed [0..255]: ");

    /*
      analogWrite(motinp1, inpSpeedS[0]);
      analogWrite(motinp2, inpSpeedS[1]);
      analogWrite(motinp3, inpSpeedS[2]);
      analogWrite(motinp4, inpSpeedS[3]);
    */

  }
}

And the result:
-> Select channel [a..d] and speed [0..255]:
<- a547
-> Speeds:  547 0 0 0
-> Select channel [a..d] and speed [0..255]:

Ah thank you,
But by this logic, shouldn't turning [code]char x = "0"[/code]  into [code]char x = '0'[/code] then fix the loop?
If yes, then something else was also wrong with the loop, since it still is stuck at [code] Serial.println("X Equals:"); Serial.print(x);[/code]

You have to fix all of it including 'a', 'b', 'c', 'd'. But there might be another mistake, as the code cannot be compiled due to missing variables I was lazy to add up

Well, if you would like to help further, I have edited the code so that it should follow the reccomendation you gave.

Btw, it's not stucked, if you send for example  a154, it'll set the first channel to 154, but it should be set once, you don't want to send it each loop. The same as you don't want to send output every loop interation

@GeorgeWTrump I've added little bit simplified example but somehow working

This is strange, I am not getting the same results as you, using your code?
Are you using the Arduino IDE? Also, come to think of it, doesn't Arduino IDE use c++?

Let us continue this discussion in chat.


text:
Mac OS X Catalina Serial Monitor Problem
I have some problems on MacBook Pro running with Catalina. I bought new nodemcu LoLin board. Its clone. It has ch340 adapter to communicate. And writing on bottom side wemos.cc and use ch340g driver.
I succesfully installed drivers and I can see my lolin boards on port list
I upload a code that doing only print hello to serial port. I tried with 9600 and 115200 baud rates. My serial monitor show garbage data. I am using platform io with VSCode to upload code and upload time is too much.When I am uploading code I got this warning :
"Detected crystal freq 156.04MHz is quite different to normalized freq 40MHz. Unsupported crystal in use?"
I am using cheap thundeIrbolt usb converter too. But I connect with this converter to Windows pc, everything looks fine. I can see hello world on serial monitor. But on my Mac, I can see garbage only. I tried some serial monitors, Arduino IDE and platform io ide but still same.
Are there any solution about this problem?
EDIT :
I fixed issue last night. Catalina has ch340 drivers already and I setup oem driver from GitHub. Apples driver and oem drivers conflicting. If you use Mojave and higher os, you dont need any driver for ch340. So if you installed ch340 oem  driver you should delete it.
I am adding the post:
Platformio post

Can you post a photo of the board? You may have bought an ESP32 board about not an ESP8266. Also try baud rate 74400 - if it is an ESP8266 the boot loader will print messages at 74400.

I can read on chip esp12e. Its not esp32. And chip vendor is DOITING. On windows i can use 115200 or 9600 but on mac it send to serial garbage data.

And i used 74400 still garbage.

You should post the solution you found as a self-answer, and accept the answer...

I fixed issue last night. Catalina has ch340 drivers already and I setup oem driver from GitHub. Apples driver and oem drivers conflicting. If you use Mojave and higher os, you dont need any driver for ch340. So if you installed ch340 oem driver you should delete it.
I am adding the post: Platformio post


text:
Powering a system using batteries
I made an arduino nano IR sensor based auto liquid dispenser. Currently it is being powered by a 12V 2 amps adapter. The 12v adapter is connected to a LM2596 DC to DC buck converter which converts the 12V to 5V and powers the arduino, IR sensor and a regular green LED. Also I am using a RO valve solenoid (rated upto 24V DC) which is being powered by the 12V adapter. So whenever the IR sensor is triggered, the DC motor (5V 200mA) and solenoid (12V 300-500mA) are turned on for 3 seconds.
Now, I intend to power this system via batteries. I am considering the following 3 options.
a.) Lithium batteries in series (4 of 3.7V batteries). But again here I believe things would be complex as I have to make a BMS and charger for this. Is anything available off the shelf so that I can directly integrate the battery and charger with my existing system ?
b.) Connect 8 AAA batteries in series to get 12V. But how long would these batteries last for my application ?
c.) Connect 2 9V batteries in series. Again, can you guys please tell me how long these may last in the system.
Arduino nano I believe consumes 20mA and the IR sensor probably around another 10- 20mA.
If it wasnt for the solenoid, I was considering connecting a mobile power bank to power the system.

You should check out radio controlled model suppliers. They have the best offerings for batteries and chargers.

The 9V block batteries are out here. They cannot provide enough current to power the solenoid

Using AA would give you about 5 days of runtime, assuming it's activated once an hour (24 times a day) and the LM2596 running at 80% efficiency. With AAA you'd only get 2.5 days. Most of the power is used by the Arduino + IR sensor. So putting the Arduino in sleep mode most of the time, would give you a lot longer runtime.

I think you should go with 3 lithium batteries in series and for proper balance charging of batteries, you can use an off the shell 3s lithium charging circuit like this here.So you will get 4.2*3 = 12.6V on full charge and on full discharge you will get 3.7*3=11.1v out of the battery.
So still I think your pump motor would work on 11v and ther are chances that your solanoid also work on 11v it will just draw more current then usual.

Thank you. As per datasheet (https://aws.robu.in/wp-content/uploads/2017/09/DATASHEET_ROBU.IN_.pdf), I believe I need to connect 3S1P to get 12.6V. Also, can I charge the batteries simultaneously with a 12V 2A adapter while powering the load ? Also, how do I know when I should connect the charger? How long would my system last with 3s1p combination of 3 18650 batteries.

You should not run a device from batteries whilst at the same time charging the batteries. The charger will have a hard job knowing when the batteries are charged (dv/dt won't work right) and you risk overcharging.  For 3S batteries you need a balancing charger otherwise you can end up with a reverse charged cell as the cells discharge unevenly. That will kill your battery. You need an intelligent "In-place" charger that disconnects the battery while it's being charged and powers the device directly from the incoming power.

@Majenko As per the datasheet page 3 (https://aws.robu.in/wp-content/uploads/2017/09/DATASHEET_ROBU.IN_.pdf), I believe this has the power multiplexing mechanism in place as they have connected charger supply and load together.

Looks good to me, though that's not a charger, just protection. It should protect the batteries from over/under charge with a dumb charger, which is good.

@Majenko thank you. But still this doesnt have the auto disconnect from the battery and power the load directly when the dumb adapter is connected , right ? So simultaneously connecting adapter to power the load and charge batteries would not be possible.

The protection circuit will disconnect the battery when it's charged.

@user3796354  It will not make any issue if you charge under load condition because your load will get its power from the battery as well as the adapter so no worry.
but for charging voltage it will not charge fully if you give 12v it will make battery voltage level to 12v but not more than that so you need to provide more than 12.6v to 13v as per the datasheet.
And for time calculation that how long your battery last you can use online converters like this

@dharmik Thanks. Instead I can also use a battery pack like this one (https://robokits.co.in/batteries-chargers/skycell-li-ion-battery/11.1v-skycell-li-ion-batteries/li-ion-11.1v-2200mah-2c-with-inbuilt-charger-protection), right ? It has built in BMS and can be charged from a 12V 1A adapter.

@user3796354 yes you can because this battery pack has the same circuit inside.

Dharmik, Do you think the battery in the link above can be charged with a regular charger ? Because I was researching about charging lithium batteries and I believe the charger should be able to maintain absolute max @4.2v per cell which regular chargers wont be able to do.

@user3796354 It will charge your battery pack with 12v regular but not full charge because the voltage has a property of flowing from high potential to low potential voltage so it will do charge to the max voltage of 12v not more than that until you give more voltage to it. So you can do one thing if you want full charge battery and regular adapter you can add an 2amp DC-DC bust converter in betwen for changing 12v to around 12.6 to 13v.

@dharmik ok. thanks

That is not a charger; it is a protection circuit aka BMS. Try getting a 3S balancing BMS for building your battery pack and use a proper charger to charge the pack.

Consider using a 12V sealed cell lead-acid battery. Those are fairly cheap and easy to find in a wide variety of capacities, and chargers are also simple and easy to find.
A car battery would power your system approximately forever, since they have such huge capacity.
Figuring out how long a given type of battery will last is a simple question of math. Figure out the average current draw of your entire project, in milliamps. (You need to include the power consumed by your voltage regulator. The linear regulators built into Arduinos are quite inefficient, and work by dissipating excess voltage as heat.)
The total power of a battery is expressed in milliamp/hours. (where 1 milliamp/hour is a milliamp of power drawn for a full hour.) If you your system draws 2 amps, or 2000 milliamps average current, and your battery is rated for 2000 mAh, or 2 amp/hours, the battery will last 1 hour.
For battery-powered systems you should think about skipping the built-in linear regulator in your Arduino and instead using a switching regulator and providing regulated 5V directly to the board. Switching regulators can run at 90%+ efficiency, compared to something like 40% - 50% efficiency for linear regulators (I don't have a specific efficiency figure for linear regulators on hand, and it depends on input voltage compared to output voltage. The 40% - 50% number is an educated guess.)


text:
Error passing a `time_t` and `struct tm`, ESP32
I need to create a converter from epoch time stored in a time_t variable, to a struct tm variable, in order to check / create a certain task every hour or a day. This function should get also a past time_t for other uses.
Converting function, inside a library, works OK ( last two lines are for verification purposes, meaning conversion was done as expected ):
void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);
  char time_char[40];
  sprintf(time_char, "%04d-%02d-%02d %02d:%02d:%02d", convTime->tm_year + 1900, convTime->tm_mon+1, convTime->tm_mday,
            convTime->tm_hour, convTime->tm_min, convTime->tm_sec);

  Serial.print(" from funct: ");
  Serial.println(time_char);

Now, when calling it from my code and try to use time tm var, it causes the code to crash. In code below, I just try to print it to console:
void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion
  char timeStamp[50];
  // Serial.print(newtime->tm_year);

}

What may be the problem ?
Guy

struct tm newtime; to alocate on stack. struct tm *newtime is a pointer to nowhere

void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);

Here you are overwriting the parameter convTime. There is no point in
passing such a parameter if you are not going to use the value provided.
void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion

newtime is initially uninitialized. The call to iot.convEpoch()
doesn't change that (the parameter is passed by value, not by
reference).
  Serial.print(newtime->tm_year);

This is dereferencing an uninitialized pointer, which is undefined
behavior and can crash the program.
The simplest solution I see is to have myIOT32::convEpoch() return the
pointer it got from gmtime(). Note that this points to static storage,
which makes the method not reentrant.
Example (not tested):
struct tm *myIOT32::convEpoch(time_t in_time)
{
  struct tm *convTime = gmtime(&in_time);
  // ...
  return convTime;
}

void sendnewNotif()
{
  time_t t = 182423032;
  struct tm *newtime = iot.convEpoch(t);
  Serial.print(newtime->tm_year);
}

thank you for your kind and comprehensive reply :), but your answer rised some more: a) why does it matter if it is initialized ? since it get its value later on ( though as a pointer ). b) are there guide lines when to use as a return value ( as you just suggested ) or as I did, passing its value/ reference ( in a case it works as expected... ) ?

a) It does not get it's value later on. b) You could in principle pass the pointer by reference, but mixing pointers and references can quickly become highly confusing.


text:
Transmit datastring using SIM7600 4G hat
I've been using Adafruit Fona with SIM800 chip to transmit data through the phoneline. SIM800 is a 2G chip but this network is closed in Norway so now I bought a Waveshare SIM7600 hat for Arduino instead. When using Fona I set up the call with this command: "ATDphonenumber" and when the connection was established I got this message: "CONNECT 9600". Then Fona went into data mode and I could send and receive datastrings before returning to command mode using +++. On the SIM7600 I need to write the call-command this way: "ATDphonenumber;" and the respond is "BEGIN: VOICE CALL" when connection is established. The problem is I can't get into datamode. The manual says use this AT command: "ATO" but that gives me "NO CARRIER" in return.
Now I wonder how I can make a call to another device and be able to send datastrings just like using Fona.

LTE doesn't have a "data mode". It's a direct internet connection. Set up the APN for your carrier and start a session, then you can make TCP and UDP connections directly.

OK, that makes it all more clear. I will check out that. Thank you so much for your reply!


text:
WS2812B LEDs start flickering after some time
I've built a WordClock with a NodeMcu and some ws2812b LEDs some time ago and it worked really well for like half a year but now the LEDs are starting to flicker when the WordClock runs longer than some days.
Video of the problem
I've got a 25w meanwell power supply, has this something to do with undervoltage? The strip is connected on both side to the PSU and I've measured stable 5V on the strip back when I installed them.
Any recommendations?

That looks more like a communication problem than a power supply problem.

that looks like a flash, not a flicker ... the LEDs brighten suddenly ... they do not waver in intensity like candle light .... maybe your code turns off all of the LEDs and then lights some of them, and the code loop gets paused when the leds are lit

It seems, that only the already lighted LEDs flash. Is that correct? (Is not easy to see behind the letters). Are you sure, that the voltage is really stable? If you have an oscilloscope, you could check for that. Please also show your code. Maybe it can give a hint about what is wrong. Just a wild guess: Have you checked, if the controlling Arduino maybe resets for some reason? Depending on the code that might cause such a problem

@chrisl the lighted LEDs are working normally but rather the LEDs right next to them have this flashing problem, I tweaked my code a little bit and reduced the update cycle of my FastLED library to only update when the minute actually changes, maybe this could prevent this from happening because before I used called my update lights function every 30ms.


text:
Voltage issue on an esp32 wvroom 32D development board
I have an esp32 wroom 32 dev board. I'm running into power issues and I'm not sure what's going on.
When I try to upload sketches the uploads fail if I have any jumpers running to the 5v or 3.3v pins which is weird.
Also, when I have nothing plugged into the board other than the usb cable and try to measure voltage across the ground and power pins I get 1.5v from the 5v pin and 0 from the 3.3 pin

This is a brand new out-of-the-static-bag board and I'm having the same issue with another board of the same type.
I feel like there's something I'm missing. Any ideas?

Please verify your black wire is connected to GND and not to D3.

@VE7JRO yeah, the angle is odd in the picture, but the ground is definitely connected to the ground pin and not d3. I hooked it all back up just now to double check, still the same readings.

Is it possible to measure the voltage with the ESP32 un-plugged from the prototyping breadboard? One last suggestion, try a different volt meter if you have access to one.

Try measuring the voltage against a different ground pin? I had a similar problem and discovered the pin next to the 5v input pin wasn't actually ground. Not sure why this would affect sketch uploading though..