text:
Encoder coupled with motor shaft.Encoder is giving larger redings than expected
I am a rookie and i dont have much experience on arduino. please help me.
I intend to build a robot that will drive on a straight path even on nonuniform surfaces like the ones we see in agricultural fields(It is just a prototype, so i want to run it on normal offroad surfaces).The robot has 4 motors, one for each wheel. I plan to use encoder feedback method to drive straight.
Right now, I have coupled a slotted disc to the shaft of a dc motor and i am trying to get the counts from the encoder and display the count after a certain interval(5 seconds) on serial monitor. The count that i get is way off the mark. The disc is having 30 slots. With just 2 to 3 rotations I am getting a count of around 180.
I am using arduino R3.
Encoder output:- Pin2 (external interrupt)
motor Pins :- 8,9
I am attaching the code below.
const int motorPin1  = 8;  // Pin 14 of L293
const int motorPin2  = 9;  // Pin 10 of L293
const int encoder_pin = 2;
volatile unsigned int count = 0;
 int time1 = 0;
 int time2 = 0;
void setup() {
  // put your setup code here, to run once:
  pinMode(motorPin1, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    pinMode(encoder_pin,INPUT);
    digitalWrite(encoder_pin,HIGH);
    attachInterrupt(0,encoder,RISING);
    Serial.begin(9600);
     digitalWrite(motorPin1,HIGH);
    digitalWrite(motorPin2,LOW);
    time1 = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
    time2 = millis();
    if(abs((time2 - time1) > 5000))
    {
    digitalWrite(motorPin1,LOW);
    digitalWrite(motorPin2,LOW);
    Serial.println(count);
    }
}

 void encoder()
 {
  count++;

 }

the end of code
The disc that i have mounted on the shaft doesn't rotate in vertical plane exactly. But i do get the blinks on the encoder when i rotate the shaft with my hand.Can that misalignment be the reason.

I guess this is a kind of debouncing problem, caused by noise on the interrupt pin. The behaviour might also get worsened by the disalignment you mentioned. You could verify this by manually rotating the shaft, even though you "get the blinks" I doubt they are accurate in count.
If that is the case there are two things you could do:

add a capacity or a RC filter to the interrupt pin to smoothen out voltage peaks if there are some. This will decrease the chance that the interrupt gets triggered accidentially (and will not solve the problem), but as a low pass it also limits the maximum count rate you are able to detect.
implement debouncing in software. This is usually done by ignoring the input signal for a specific amount of time ("deadtime") after an interrupt has occured. As you are expecting a periodic signal and debouncing behaviour might be different at different speed it could be a good idea to capture the time span between two "blinks" and make the deadtime dependend on this calculated speed.

Something else: the way you check for the timestamp is little incorrect. You should instead do something like this:
void setup() {
  unsigned long starttime=millis();
}

void loop() {
  if (millis()-starttime > 5000) {
    starttime=millis();
    // put code here to run every 5000 ms
  }
}

Usually a rotary encoder has at least 2 sensors.
Incremental rotary encoders usually only have 2 sensors. Absolute or positional encoders have more, and let you figure out the absolute orientation of your sensor by reading a bit pattern.
To read an incremental encoder you write your code to only pay attention to alternating changes in the sensors. That gives you automatic debouncing of the contacts. I suggest you search for Arduino code for decoding rotary encoders.


text:
Trigger countdown with 433MHz transmission
I would like to use an arduino to read 433 MHz transmission from multiple Soil Moisture Sensors. Since I can never be sure all transmissions reach the receiver I'd like to set a countdown from the moment the first transmission is received. If another transmission is received, the countdown starts again.
After a defined amount of time (e.g. 10 Minutes) without any more signals or if all signals have been received (e.g 4 Sensors) the receiving unit should stop and come to decision based on the data it got to the point.
For transmitting and receiving I am using the <RCSwitch.h>library.
The loop of the receiving unit and one Sensor looks like this:
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
void Setup(){
Serial.begin(9600);
mySwitch.enableReceive(4);
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();

if (value == 0) {
  lcd.clear();
  Serial.print("Unknown encoding");
  }
  else {
  Serial.print(mySwitch.getReceivedValue());
  Serial.print("%");
}

The full code includes some differentiation mechanism for all sensors but I figured that might not be relevant for my question.
Question:
What's the best way to do this without a real time clock module. As far as I know I can't wait by using delay(...)since then I won't receive any data while the processor waiting.

You say The full code includes some differentiation mechanism for all sensors so I'll assume there's some function GetSensorId() that returns 0 to NUM_SENSORS - 1.
So, you need to keep track of a) how many sensors have reported in and b) time since the last report. You can't just count how many sensors have reported in since there may be a chance one could report in more than once. So I would use an array:
// Assume you never receive 0 from sensor.
const int NO_DATA = 0;
const int NUM_SENSORS = 4;
int sensor_data[NUM_SENSORS];

void setup() {
    // Initialize array
    for (int i = 0; i < NUM_SENSORS; i++) {
        sensor_data[i] = NO_DATA;
    }
}

Also, a variable to keep track of time of last message:
uint32_t last_message_time = 0;

So, in loop():
void loop() {
    // Check for data
    if (mySwitch.available()) {
        int value = mySwitch.getReceivedValue();
        if (value == 0) {
            lcd.clear();
            Serial.print("Unknown encoding");
        }
        else {
           // Determine which sensor sent the data
           int sensor_id = GetSensorId();
           Serial.print(value);
           Serial.print("%");
           // Save the data and the time of the message
           sensor_data[id] = value;
           last_message_time = millis();
       }
    }
    // See if all sensors reported
    byte sensors_reported = 0;
    for (int i = 0; i < NUM_SENSORS; i++) {
        if (NO_DATA != sensor_data[i]) {
            sensors_reported += 1;
        }
    }

    // When 0 sensors have reported in, do nothing
    if (0 != sensors_reported) {
        // Otherwise, at least one sensor
        // check the time
        uint32_t elapsed = millis() - last_message_time;

        // If have all data or time's up, do something
        if (NUM_SENSORS == sensors_reported || elapsed > SENSOR_TIMEOUT) {
            // Do something

            // Reset state
            for (int i = 0; i < NUM_SENSORS; i++) {
                sensor_data[i] = NO_DATA;
            }
        }
    }
}

Sorry for the long delay .. it took me some time to try everything . It seems to work just the way i wanted. Thank you very much.

source: Stack Exchange

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

sort: votes


text:
How can I define integer inputs to a function and get array as an output?
I am trying to write a function that takes integer values as an input and gives an array as an output. I have tried the following code but it doesn't show the output result in the serial monitor:
int *phi (int cur,int vol,int t) {
  int z[4];
  z[0]=1;
  z[1]=cur;
  z[2]=vol;
  z[3]=t;
//z=cur+vol+t;
  return z;
}

void setup() {
  // put your setup code here, to run once:

}

void loop() {

int result;
result=phi(1,2,5);
Serial.begin(9600);
Serial.print(result);

}

You cannot return an array. What's your final purpose?

You are asking an XY problem.

I'm voting to close this question as off-topic because it's purely a programming question.

If we narrow the scope too much, we end up with nothing but "Did I burn up my Arduino?" and "My PC won't recognize my Arduino" questions. While this is a programming question, Arduinos are all about learning to build and code embedded systems, which means learning programming. We accept questions about using pullups, FET switches, and the lengths of OneWire busses, which strictly speaking, are electronics questions, not Arduino topics either, but are part and parcel of what we do with Arduinos. I vote to reopen the question and perhaps take our guidelines as guides more than lines.

@EnricBlanco While you can't technically return an array, you can return a pointer to the first element, which is what the function does an often sufficient if you obtain the length by some other means.  However in this case the stack address returned invokes undefined behavior, and the improper assignment of an int * return value to an int variable strongly suggests the code we're looking at isn't even a version actually tried, but a mid-experiment mishmash.

-1 for posting code which does not compile and claiming that you have tried its behavior, which is not possible.  Your improper assignment of an int * to an int will be rejected by any sane compiler.  To receive help you must post the actual code.

Just a reminder for everyone to be humble and civil in the comments here. Name calling is strictly not allowed, especially to those that are trying to help others.

like this: https://www.programiz.com/cpp-programming/passing-arrays-function

Defining the array in phi() returns a pointer to unassigned memory - it is no longer reserved once phi() returns. The next function call or interrupt (which you have no control over) will likely clobber the data.
A better choice would be to define z in the caller (loop() in this case) as an uninitialized array and pass it to phi() to fill and return. This is the more usual case, as it:

avoids using globals,
permits multiple calls to the function without clobbering previously returned data (you would pass different arrays in this case), and
it avoids statically defined arrays that may not be needed after the caller returns, in a memory-starved environment (this may not be applicable if loop() is the caller).

In short, it gives the calling function the greatest flexibility, while committing the least amount of memory.

It appears you have created an array which only has scope with in the method "phi".
In practical terms, the array "z" is a local variable declared inside of the method and, as such, will likely end up in temporary RAM.  When the method has completed, the RAM reserved for that method's local variables is released and is available for other purposes.
To fix this you could make "z" a static or you could give "z" global scope.

There are some other problems you need to sort through.  Like mixing "integers" and "pointers to integers".  But the problem addressed by the above answer is usually the one that causes people the most confusion / problems.

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


text:
Differences between nodemcu and arduino processer
I have an arduino Uno and nodemcu development board.
I have an OV7076 camera and used with arduino UNO. It worked flawlessly with it and the code used is provided in the [Instructables tutorial][2] named as FromComputerNerd.ino.
Now i want to use it with Nodemcu. Whereas Nodemcu have a single Analog input but OV7076 uses two analog inputs [shown in][2]. So to get it I am trying to use Multiplexer. I can change the code so that it would adjust for analog pins.
But will the code be compatible with Nodemcu. Since it was written for arduino uno.If not, What changes can be done to make it compatible?
http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/

OV7076 doesn't use any analog signals. They are all digital.

the hardware can work. the sketch will need stripped of all it's AVR-specific refs like hard-coded ports.

Camera doesn't send data via Analog to Arduino.
A5 and A4 are I2C bus beside Analog.
NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.
see : https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library

I am suggesting you to buy NodeMCU because it is having inbuilt WIFI, you can connect NodeMcu to internet without much effort compare to connecting UNO to internet, and the best thing is NodeMCU is arduino compatible you can do all possible stuff that can be done with UNO. We can also program NodeMCU in 'C' language using Arduino IDE directly
Hardware comparison
NodeMCU

128KB RAM
4MBytes ROM(flash)
micro USB port
Small Board Size

Arduino UNO

2kB RAM
32 KB ROM
USB type B connector
Bigger in size than NodeMCU

Both are having nearly same prices.

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


text:
Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins?
I'm using a CD4094 shift register to power my LEDs along with a ULN2003A darlington transistor array. I want to hook up the LEDs to an external power supply of 12V (common anode).
The cathodes of little groups of LEDs will be connected to the ULN2003A which is connected to the shift register which will get its data from the arduino (the digital pins which i assume work at 5V).
My question is, if I connect the Vdd pin of the shift register to the 12V external power supply, will it still function as intended through the Arduino?

No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.
Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.

Is that TPIC drop-in compatible for a HEF4094?  Basically I'm trying to repair a display that uses these chips. My first goal is use the chip (acquired an extra from ebay) to drive ~8 LEDs off 1.  I realize this isn't the best way to learn (I'm trying to fix something, by first replicating parts of the circuit) and the biggest impediment is finding good examples to mimic and learn from.

@Crossfit_and_Beer: It's drop-in compatible with a 74HC595 (except for the whole OD bit), but I'm not sure it would substitute for something in the 4k series.

@Crossfit_and_Beer: Having looked at the datasheets now, you'd have to put it on an adapter to use it, and it still expects a 5Vish supply.

Good to know. I'll add (since there's a dearth of examples for this chip) that the "BP" chip version accepts a VDD (VCC) of up to 15V. Sadly while I have good reputation on other SE sites, I don't have rep "here" and cannot post questions yet, so a good definition of my problem will have to wait...


text:
Arduino GSM Implementation
I want to send sms to a number if and only if that number is in the radius of the arduino with GSM module.
I already have GPS into it.
Should i integrate a ultrasonic sensor to get the distance and then send the message??? let me know if there is anyother option.
Thank you in advance.

What kind of radius are we talking about? Line-of-sight ultrasonic sensor radius? But how are you planing to determine the number with ultrasonic sensor?

Can't be done without writing a special app for the phone - and then the sending of the SMS is pointless.

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


text:
Arduino keeps looping
I made a program where I give a number(4 bit) as input and four led on the breadboard lights up according to its binary. The problem is the program works all well only for (2-15) but if I give 0 or 1 as input it keeps looping and the serial monitor keeps printing that number. If I remove the "prbline" from the code the program works but the serial monitor only prints the input number if it is 0 or 1. Why is it like this?
#include<stdlib.h>
#include<string.h>
int red1=2;
int red2=3;
int red3=4;
int red4=5;
int num=1; // this is the input number
char number[4];
int len;
char str3[]="000",str2[]="00",str1[]="0",str[]="0000";

void setup() {
  // put your setup code here, to run once:
  pinMode(red1,OUTPUT);
  pinMode(red2,OUTPUT);
  pinMode(red3,OUTPUT);
  pinMode(red4,OUTPUT);
  itoa (num,number,2);
  len=strlen(number);
  Serial.begin(9600);
  Serial.println(num);
  Serial.println(number);
  Serial.println(len);
  Serial.println(str);

  if(len==1){
    strcat(str3,number);
    strcpy(str,str3);
    }
  else if(len==2){
    strcat(str2,number);
    strcpy(str,str2);
    }
  else if(len==3){
    strcat(str1,number);
    strcpy(str,str1);
    }
  else {
    strcpy(str,number);
    }
  Serial.println(str); //prbline

}

void loop() {
  // put your main code here, to run repeatedly:
  if(str[0]=='1'){
    digitalWrite(red1,HIGH);
    }
  if(str[1]=='1'){
    digitalWrite(red2,HIGH);
    }
  if(str[2]=='1'){
    digitalWrite(red3,HIGH);
    }
  if(str[3]=='1'){
    digitalWrite(red4,HIGH);
    }

}

How are you providing the input?

I change the value of the 'num' variable from the IDE and upload

So many mistakes in such a short code:

number is too short for more than 3 bit numbers (8 and higher)
strcat is modifying first string, so all strings str1, str2, str3 are too short too
if you want to use them more than once, it'l be adding string to them over and over.....

Basically, if you can see output from the setup over and over, it means crash and start from the reset vector.
But, the main question is why don't you use bit manipulation on num directly:
  digitalWrite(red1, (num & 0b1000) != 0 );
  digitalWrite(red2, (num & 0b0100) != 0 );
  digitalWrite(red3, (num & 0b0010) != 0 );
  digitalWrite(red4, (num & 0b0001) != 0 );

Or with using bit positions:
  digitalWrite(red1, (num & (1 << 3)) != 0 );
  digitalWrite(red2, (num & (1 << 2)) != 0 );
  digitalWrite(red3, (num & (1 << 1)) != 0 );
  digitalWrite(red4, (num & (1 << 0)) != 0 );

Bit positions little bit more readable by using macro _BV (which is translated to 1 << ..)
  digitalWrite(red1, (num & _BV(3)) != 0 );
  digitalWrite(red2, (num & _BV(2)) != 0 );
  digitalWrite(red3, (num & _BV(1)) != 0 );
  digitalWrite(red4, (num & _BV(0)) != 0 );

or more interesting macro wrapper bit_is_set to be more readable:
  digitalWrite(red1, bit_is_set(num,3));
  digitalWrite(red2, bit_is_set(num,2));
  digitalWrite(red3, bit_is_set(num,1));
  digitalWrite(red4, bit_is_set(num,0));

And, as a bonus, it can be even done in a loop:
byte reds[] = { 5, 4, 3, 2 }; // to preserve the same order as in the question
byte num    = 1;

void loop() {
  byte tmp = num;
  for (byte pin : reds) {
    digitalWrite(pin, tmp & 1);
    tmp >>= 1; // bit shift by one to the right (= division by 2)
  }
}

Thank you very much for the answer it really helped me.

To add to KIIV's concise response, the line
Serial.println(str); //prbline

can be easiest created without itoa and leading zero helper strings by
int num = 9; // Test input 0 .. 9 ( or even 15 = 0x0F )
void setup() {
 char str[] = "0000";
 byte tmp = num & 0x0F; // limit to valid values
 for (byte i=3; tmp != 0; i--, tmp >>= 1)
   if (tmp & 0x01) str[i] = '1';
Serial.begin(9600);
Serial.print(num);
Serial.print(" = ");
Serial.println(str);
}

You are overwriting memory.
 if(len==1){
    strcat(str3,number);
    strcpy(str,str3);
    }

There is room for 3 characters in str3, however you are using strcat to add more characters.
I don't understand your technique, however this might help make it work:
char str3[6]="000",str2[6]="00",str1[6]="0",str[6]="0000";

Thank you very much for the answer it really helped me.


text:
Arduino Mega - Enabling CTC mode disables timer
I'm trying to use timer3 on an Arduino Mega 2560 in CTC mode. However, enabling CTC disables the code entirely.
Here is the function I call in setup() to setup the times.
void SetupInterrerupt() {
  cli(); // Disable interrupts

  // Setup timer
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // Setup compare match register
  OCR3B =  CMP_FAST; // CMP_FAST = 40

  // turn on CTC mode:
  TCCR3B |= (1 << WGM32); // Commenting out this line makes the code work
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  sei(); // Enable interrupts

  Serial.println("Timers enabled");
}

And the interrupt vector.
// Timer 3 Interrupt
ISR(TIMER3_COMPB_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
  // do stuff...
}

As is, the interrupt doesn't execute at all. As noted in the code, commenting out "TCCR3B |= (1 << WGM32);" actually executes the interrupt, except the frequency is more like 1Hz instead of 720.
I'm using the arduino-lmic library, as well as some other data structure libraries. I don't think they use any timers, but since lmic is designed for Uno's, I figured that using timers 3 and up would be fine.
I'm a little rusty on my timers unfortunately. Is anyone able to spot my mistake?
Thanks.

I think your problem is that you are using the wrong "TOP" counter value register.
OCR3B =  CMP_FAST; // CMP_FAST = 40

should be:
OCR3A =  CMP_FAST; // CMP_FAST = 40

I am not too familiar with the workings of the AVR times, but according to the datasheet:

In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution.

(Note: it only mentions the register for timer 2, but the same holds true for all the timers in the same class, including timer 3).
Since OCR3A is zero it never triggers a match.  And since there is only one counter (TCNT3) which gets reset to 0 on a match, there can only be one register to compare to, and that is the "A" register. The "B" register appears to be redundant in CTC mode.
You may also need to switch to the COMPA vector (I am not sure on this one TBH)

Thanks for the response! Unfortunately, that didn't seem to work. Switching from OCR3B to OCR3A doesn't change the behavior. Switching to the COMPA vector causes the Arduino to reboot continuously (I suspect whenever the interrupt occurs).
Enabling TCCR3B |= (1 << WGM32); simply disables the timer again.
I think I've also tried using timers 0-2, to no avail.

Maybe you should switch to using a library to manage it for you instead. I'm sure there's some variation on the TimerOne library for Timer 3.

Besides changing OCR3B to OCR3A, you also need to change OCIE3B to OCIE3A, and TIMER3_COMPB_vect to TIMER3_COMPA_vect.


text:
ESP8266 Bootloader Firmware (on the ESP8266)
It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.  If that firmware is corrupted, the ESP8266 is dead.  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.  Does anybody know how to do that?  Thank you.

what has SPI to do with bootloader (or application) flashing? classic AVR used the same pins for ISP (in system programming), but even new AVR MCU models don't use SPI pins to flash the bootloader (or application)

Possible duplicate of Wiring when burning the bootloader of esp8266

It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.

Indeed there is.

If that firmware is corrupted, the ESP8266 is dead.

Well, if that firmware gets corrupted, then yes indeed the chip is dead. That's because the firmware is in ROM, not flash - and the only way it can get corrupted is for the chip to be physically damaged internally.

I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.

No. They are SPI. SPI has nothing to do with flashing firmware. It just happens that AVR chips share the same pins as SPI for their debug protocol.
You cannot replace the bootloader on an ESP8266. It is in ROM. It's unchangeable - except as mentioned earlier by physical trauma to the silicon itself.


text:
time delayed LEDs
I have two LEDs an I want the first one getting linear brighter and the second one do the exact same thing just one ore two seconds later. When one LED has reached 100, it should getting darker until there's no light and then start again from the beginning. I#m trying now for quite a long time but couldn't get it going.
int LED = 11;
int LED2 = 10;
void setup() {

Serial.begin(9600);
}
int x;
int x2;
void loop() {

for(x = 0; x<=100;x++)
{
while(x > 30)
{
for(x2 = 0; x2<=100;x2++)
{
analogWrite(LED2,x2);
delay(100);
}
}

analogWrite(LED,x);
delay(100);
Serial.println(x);

}
}

I just wanted to do the beginning but it isn't working. Can somebody pleas help me?

I'd be inclined to use sin and cos to create a sinusoidal brightness profile. Loop from 0 to 2xPI at whatever increment you want (maybe use a DEG2RAD conversion so you can work in degrees) and cycle around a circle. Use sin to calculate the brightness of one LED ((sin(angle) + 1) * 50.0) and cos for the other. The two LEDs will then be 90° apart around the circle.

@gamma, what about a graph that shows the brightness of both leds in time. I'm still confused what you want to achieve. Do you want other patterns as well ?

Here is one way to do it.

Set up two output compare channels. They are identical except that they have slight different periods.
In their respective isr, flip the led

The next effect is that the duty cycle on the led goes from 0 to 100 and then 0 and then ....
The periods determine how long the 0 to 100 to 0 cycle is. The period differential determines how fast the led goes on and off.
You can do that to the other led, either in the same isr or through two other channels.


text:
polynomial change of LED brightness arduino
I try to change the brightness of an LED following the formular in out1. I'm pretty sure that something is going wrong because it doesn't really change its brightness and it never stops lightening. Can pleas somebody help me. It should basically do the same than a sin wave but instead of the sin I try to use my equation!
const int LED = 11;
const int LED1 = 10;
const int LED2 = 9;

void setup()
{
}

void loop()
{
float in1, out1, out2, out3;

for (in1 = 0; in1 < 10; in1++)
{
out1 = 8.8 * pow(10,-4) * pow(in1,4) - 0.0034 * pow(in1,3) +0.37* pow(in1,2) -6.7 *in1 +1.7 *pow(10,2);
//out2 = 1.207*pow(in1,4)-0.0011*pow(in1,3)+0.16*pow(in1,2)-5.5*in1+2,0763;
//out3 = 4.829*pow(in1,4)-0.034*pow(in1,3)+0.37*pow(in1,2)-6.7*in1+2,076;

analogWrite(LED,out1);
delay(10);
//analogWrite(LED1,out2);
//analogWrite(LED2,out3);

}

analogWrite(LED,LOW);

/*analogWrite(LED,out1);
analogWrite(LED1,out2);
analogWrite(LED2,out3);
//analogWrite(LED1,LOW);*/
delay(500);

You wrote: “8.8 * pow(10,-4)”. You mean 8.8e-4. And you should implement Horner's method instead of using the (very expensive) pow() function.

Don't cross post. You already asked this on SO.

You wrote: “The formula [...] comes from data I've plottet in Matlab”. Why don't you tell us what you actually want to achieve? Your code is probably working just fine, and the Arduino is doing what you asked for. Only you know what you actually want it to do.

Here is the proper way to implement a polynomial function. It's a direct
application of Horner's
method:
// Polynomial function for output 1.
static float f1(float x)
{
    return (((8.8e-4 * x - 0.0034) * x + 0.37) * x - 6.7) * x + 1.7e2;
}

You would use it like this:
void loop()
{
    for (int x = 0; x < 10; x++) {
        analogWrite(LED, f1(x));
        delay(10);
    }
    digitalWrite(LED, LOW);
    delay(500);
}

Thank you for your help.It's hard for me to tell if it's working but the plot of the function looks like this : link I'm not quite sure but i think the brightness should not fall down at a certain point. Do you have any idea what the issue could be? I was also wondering if I could do more steps with the brightness....

The most likely issue is your poor choice of polynomial. You are varying the brightness over a tiny range: the variation will be hardly visible.

anlogWrite uses 0...255, that is only 8 bit. A led intensity with a curve into a 8 bit intensity resolution ? That is not very useful. The first 10 steps are far too coarse. The Neopixels and other RGB leds often have more bits, and those can be programmed with a nice visual brightness curve. As far as I know, all led PWM modes are linear, but the human eye is not linear. Therefor you need more bits for finer steps when the led is dim.

@Jot: The Neopixels (and the WS2811, WS2812 and SK6812) are 8-bits per channel.

@EdgarBonet, thanks, so the most common 5050 RGB leds are still 8-bits per color. That's disappointing. Even the 5050 RGBW leds are 8 bits (times four for each 'color'). Some PWM led driver chips are 12 or 16 bits. Sometimes I use two digital outputs with different resistors to get more resolution.

You should make sure that your code works with known good values for out1.
After dthat, try to make sure that your formula produce values in a valid range - check analogWrite to see what values it expects.
Then you should make sure that your code formula is what you want. Aka the code reflects your intent correctly.
edit: here is what I use to calculate polynomial functions.
//return poly functions
//x: independent variable
//degree: degree of the polynomial function
//p[]: array for the coefficients
double poly(double x, int degree, double p[]) {
  double tmp=0;  //temp variable

  while (degree--) tmp = tmp * x + p[degree];

  return tmp;
}

by providing different "degree" and "p[]/coef", you can calculate any polynomial function with one call to poly().
I generally use a set of macros to further simplify the calling to that function.

The formular is a little bit strange but it comes from Data I've plottet in Matlab and afterwards I did cirve fitting. Is there no easy way to have more steps? Maybe by doing a fourrier transformation?

Think simple. Your problem isn't the lack of complexity. So adding more complexity will not get you where you want to go. Instead, focus on the basics

Ok first of all my possible maximum vallue is 255. So everything above will not be displayed right? I've normalized the values with Matlab so no value is above 1. Is there a way to do the same thing with ardouino? Because in this case I could Multiplay the normalized Vector by 100. I'm probably thinking to complex, you're right! So could you give me an instruction I can follow to solve this? It would really help me a lot! Thanks!

Your problem doesn't require Fourier transformation to solve. It only requires common sense and basics, as laid out to you earlier.

In poly(), you should increment degree before the while loop, otherwise you fail to add the leading term. Alternatively, you could rename degree and document that this parameter is the length of the p array, which is not the same as the degree of the polynomial.

Ok so here is what I did: I multiplicated my function with 10^-1 so I have a bigger range. Afterwards I changed the range of my loop up to 245 because for this number the result is 244.33 so it's a possiple value. By changeing the steps to 2.47, I have exactly 100 steps.
for (int x = 0; x < 245; x++) {
analogWrite(LED, f1(x));
delay(100);
}
analogWrite(LED, 0);
  delay(10000);

What do you say? Is ther any mistake?


text:
Using Thinger.io Wifi together with HX711 library soft resets ESP8266 (NodeMCU)
I'm trying to get my NodeMCU v1.0 board to read from a load cell connected to a HX711 amplifier and send the data through Wifi to Thinger.io. I managed to make the readings from HX711, works perfectly. I also managed to send data to Thinger.io separately (ran the example without problems). However putting these together just doesn't work for me, the board soft resets:
[NETWORK] Starting connection...
[NETWORK] Connecting to network xxxxxxx

Soft WDT reset

ctx: cont
sp: 3fff0c60 end: 3fff0ec0 offset: 01b0

>>>stack>>>
3fff0e10:  4021e91f 00000001 3ffefe64 3ffefd48
3fff0e20:  3fff18dc 40203d38 3ffefe64 40203f0c
3fff0e30:  3ffe8e7f 3ffefcd8 3ffefe64 402023fc
3fff0e40:  3ffe8e81 00000015 3ffefe64 402051c0
3fff0e50:  00005173 3ffefcd8 3ffefe64 402051e4
3fff0e60:  3fffdad0 3ffefcd8 3ffefe64 3ffefe90
3fff0e70:  3fffdad0 00000001 3ffefcd8 402034b9
3fff0e80:  feefeffe 3ffefcd8 3ffefe88 40203768
3fff0e90:  3fffdad0 00000000 3ffefe88 402037e0
3fff0ea0:  feefeffe feefeffe feefeffe 40205824
3fff0eb0:  feefeffe feefeffe 3ffefea0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

And if I wrap the thing.handle(); with
  ESP.wdtDisable();
  thing.handle();
  ESP.wdtEnable(0);

Then I get hard reset after few seconds.
This is minimal code where I reproduce the issue:
#define _DEBUG_

#include <HX711.h>
#include <ESP8266WiFi.h>
#include <ThingerESP8266.h>

#define USERNAME "zink"
#define DEVICE_ID "xxxxxxxx"
#define DEVICE_CREDENTIAL "xxxxxxxxx"

#define SSID "xxxxx"
#define PASSWORD "xxxxxx"

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

HX711 scale;

void setup() {
  // put your setup code here, to run once:
  thing.add_wifi(SSID, PASSWORD);
  scale.begin(D6, D5);
}

void loop() {
  // put your main code here, to run repeatedly:
  thing.handle();
}

While this sketch works perfectly:
#define _DEBUG_

#include <ESP8266WiFi.h>
#include <ThingerESP8266.h>

#define USERNAME "zink"
#define DEVICE_ID "xxxxxx"
#define DEVICE_CREDENTIAL "xxxxxxx"

#define SSID "xxxxxxx"
#define PASSWORD "xxxxxxx"

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

void setup() {
  // put your setup code here, to run once:
  thing.add_wifi(SSID, PASSWORD);
}

void loop() {
  // put your main code here, to run repeatedly:
  thing.handle();
}

And also this one:
#include <HX711.h>

HX711 scale;

void setup() {
  // put your setup code here, to run once:
  scale.begin(D6, D5);
}

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

But combining them triggers a soft reset. What am I doing wrong here?

When an ESP resets its usually a segmentation fault.  The first area I would look at is string manipulation, but you aren't doing any.  So maybe reversing the order of:
thing.add_wifi(SSID, PASSWORD);
scale.begin(D6, D5);

might stop it, but it will only be temporary.
If it isn't you, and I can't see anything in your code that would cause it, then it must be the libraries.  I think you will have to sit down and look at those two functions and see if you can see any string manipulation that might be causing it.
My money (£1) is on the add_wifi function and the cause being because it wants variables passing to it rather than #defines, but that's just a pure guess.


text:
Programming arduino with FT232RL, not in sync: resp=0x00
I realize this generic error has been asked about lots of times before, but I have been unable to find an answer that works for me.
I have a bunch of pro mini's that I program with an FT232RL. It works perfectly fine for some time, but eventually it stops working and I get the error:
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
Using the same FT232RL on an unused pro mini still works fine. Burning a new bootloader through an Uno as ISP works fine, as well as uploading code to the pro mini that way, but even after burning the bootloader the FT232RL does not work on that pro mini again.
I have experienced this exact behavior on three different pro minis in a row now. Is there any sort of factory reset-ish thing I can do other than the bootloader to try to get these back to square one?

Are they 3.3V or 5V Pro Minis?

They're 5V pro minis.

Bang goes my idea then. Oh well. Still, try this anyway: Write some small code to test that the UART is actually functional, and burn it using another Arduino.

do not upload a sketch over ISP after you burned the bootloader. it erases the bootloader


text:
Can i use a sparkfun rfid qwiic without an id-xxla?
Sparkfun rfid qwiic
id-20la
I am using an Arduino UNO R3.
You should assume that i don't know anything. If yes can you give some information about how to do it? Thanks for any help.

No. It is not an RFID reader. It just interfaces to an RFID reader. You need an RFID reader to read RFID tags. That Sparkfun board just controls the reader and reads the data from it.


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

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

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

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

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

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

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

The = is optional.

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

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

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

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

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


text:
how to fix USBASP Unknown USB Device (device descriptor request failed) - Win 10?
I just recently purchased Usbasp from Ali Express, when i'm connecting it to the windows 10 desktop in device manager its Unknown USB Device (device descriptor request failed). How to fix this error? Even in Linux its not detecting.

Sounds like you've got a dud. Contact the seller and get a replacement or refund.

@Majenko I just pick my rework station hotair gun to destroy this board and melt all the solder on the board, then i plugged it in for last time and its stated working but now i'm getting this error https://arduino.stackexchange.com/questions/65321/usbasp-arduino-uno-bootloader-flash-error-win-10


text:
Arduino UNO R3 clone acting as Arduino Nano
I just got a bunch of Arduino Uno R3 (ATmega328P + CH340).In arduino IDE when i'm selecting board as Arduino UNO then i'am getting this error
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM7
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xaf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xaf

But, When i'm selecting Arduino Nano it's working fine. How to fix it?

why do you feel that something needs to be fixed? .... are you having problems compiling sketches? .... upvote for investigating and finding a workaround

burn the Uno bootloader

@jsotola https://arduino.stackexchange.com/questions/65321/usbasp-arduino-uno-bootloader-flash-error-win-10

@Juraj  https://arduino.stackexchange.com/questions/65321/usbasp-arduino-uno-bootloader-flash-error-win-10

@Juraj i have selected  target board type in Tools menu, on linux arvdude cli i'am getting same error

@Juraj I received the UNO with Nano Bootloader so i am trying to flashing it


text:
Passing a time_t array as a function parameter
I'm trying to log reconnections and disconnections of a network. For that I've created 2 time_t arrays to store such occurances:
const int logSize = 10;
time_t conLog[logSize];
time_t disconLog[logSize];

Now, down the road, I have some manipulation and time calculation to do, and for that I wish to pass those log as a variable.
For example - zeroing its values:
void initLog(time_t log[], time_t init_val = 0)
{
        int sizeLog = sizeof(log) / sizeof(log[0]);
        Serial.print("size: ");
        Serial.println(sizeLog);
        for (int i = 0; i < sizeLog; i++)
        {
                log[i] = init_val;
        }
}

in order using it in a simple way : initLog(conLog);
But unfortunately this is wrong.
I've tried to replace time_t log[] with time_t &log - but still no luck.
What do I do wrong ?

you must pass the size as an additional parameter. the size of the array entering the function is unknown at runtime

@Juraj - Meaning that it is ref OK but its size can't be calculated ?

pointer or reference is the beginning address only

@Juraj that I know....

so how would the size be calculated? there is no information about the end address or length. the way you calculate the size works for a specific array when the compiler knows the definition of the array. but array of any length can be passed to this function

@Juraj well I thought there is some kind of a null termination sign. It works - thank you!

for char array that is a convention. for array of pointers you could use a null pointer as mark. here you could choose some time_t value as end mark, but generally all have a meaning.

When you pass an array to a function it "collapses" the array into just a pointer. All the receiving function knows is the type of the contents of the array (time_t) and where it starts in memory - it knows nothing about the size of the array.
The sizeof() call just gives you the size of that pointer, not the size of the memory it points to.
sizeof() is not actually a function, it's a compile-time construct. It can't know anything about runtime values, only what is there at compile time.
Instead you must pass the length of the array with the array as a separate parameter, which can only be calculated in the same scope as where the array is defined, and then only by using the original name of the array.  It is typical to create a macro to do this for you at the time you make the array:
time_t conLog[logSize];
#define CONLOG_SIZE (sizeof(conLog) / sizeof(conLog[0]))

Then pass that to your function:
initLog(conLog, CONLOG_SIZE);

Alternatively, since you already have the size in a constant in this case, you could just use that:
initLog(conLog, logSize);

Good answer, except... If you have a constant logSize that you use to create conLog, why write code to calculate it? Just use logSize directly.

@DuncanC In this instance that is true, but it is seldom the case.

Why? For arrays who's size is defined at compile time, using a compile-time constant to express that size is a good, clean way to do it.

@DuncanC Yes. You know that. I know that. Very few Arduino users know that. You have to remember: these are Arduino users, not programmers.

Some of us are both...

But most aren't. That is why you answer questions and don't ask questions. Just remember to tailor your answers to the level of the audience. If in doubt read up on Wittgenstein's ladder, and "lies to children".

I like your edit, proposing the best option. Why are people downvoting this answer? It is the correct answer.

...Jealousy...?


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:
Accessing struct's variable parametrically on ESP8266
I have 2 instances of a struct. One has def values stored and second stores values read from a file on SPIFFS.
I'm trying to use a for loop over all struct's variables - if file was read OK and key was found, store its value in final_par else get value from def_par.
For that, I've created keys array - but I can't find a way to iterate, in a for loop
as final_par.keys[i] = def_par.keys[i] - but this is not possible.
How can it be done ?
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

If you want to copy every value use memcpy(&final_par, &def_par, sizeof(parameters));

it is not possible to access a field by name. how to do it depends on what you want to do with it.

The names only exist in the source code. Once compiled the program has no knowledge of any names.

for dynamic name value pairs with basic data types ArduinoJson can be used. especially if it should be stored in FS

You can create a 'hardcoded' copy function:
void CopyParameter(int parameterIndex)
{
    switch (parameterIndex)
    {
    case 0: final_par.ext_inputs = def_par.ext_inputs; break;
    case 1: final_par.auto_relay_off = def_par.auto_relay_off; break;
    ...
    default: // Error
    }
}

Of course you can also pass final_par and/or def_par as arguments.
If you don't want to use an index, create an enum with the index values for each parameter, like:
enum EParameters
{
    ExtInputs,
    AutoRelayOff
    ...
};

void CopyParameter(EParameter parameter)
{
    switch (parameter)
    {
    case ExtInputs   : final_par.ext_inputs     = def_par.ext_inputs    ; break;
    case AutoRelayOff: final_par.auto_relay_off = def_par.auto_relay_off; break;
    ...
    default: // Error
    }
}

The disadvantage is that you have to keep the structure and the copy function manually synchronized.
The advantage is that you can do a shallow, deep copy or even add more logic depending on each struct member.

You can do it but it can be awkward. You'll need an array of structs, each member of which describes one member of your 'struct parameters' - essentially, an expansion of your present 'keys[]'.
Then you can consult this array randomly or in order to find the name, data-type, and memory offset of a given parameter (indexed by parameter order), or search it, to access the same information by parameter name.
Here's your parameter struct with some (incomplete but runnable) code to list the descriptor array, and incidentally, show how to build and use the array. Note that the code compiles but with a warning that a member of your 'parameters' was not initialized. I chose not to fix that; it isn't used here and doesn't prevent compilation.
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
//char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
//                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
//                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
//                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

// A couple of functions to extract data from an array or struct:
#define countof(a) (sizeof(a)/sizeof(a[0]))                             // ret # of array elements (not bytes)
#define offsetof(struc, member) ((int)(&(((struc*)(0))->member)))   // ret byte-offset from start of struct to the given member

// Enumerate possible parameter types
typedef enum {
   t_bool,
   t_char,
   t_int
} parType;

// Descriptor table - contains name, type, and offset of each parameter
// Could go in flash to save a bunch of RAM
struct descriptor {
   const char *name;
   parType pType;
   uint8_t offset;
} Descriptors[] = {
   { "ext_inputs", t_bool, offsetof(parameters, ext_inputs) },
   { "auto_relay_off", t_bool, offsetof(parameters, auto_relay_off) },
   // ...
   { "inputUpPin", t_int, offsetof(parameters, inputUpPin) },
   // ...
   { "auto_relay_off_timeout", t_int, offsetof(parameters, auto_relay_off_timeout) }
};

void setup() {
    Serial.begin(115200);
    Serial.println("parameter        type          offset\n");
    // List the parameters' names, types, and offsets within 'struct parameters'
    for( uint8_t i = 0;  i < countof(Descriptors);  ++i ){
        Serial.print(Descriptors[i].name);    Serial.print(", ");
        Serial.print(Descriptors[i].pType);   Serial.print(", ");
        Serial.println(Descriptors[i].offset);
    }
}

void loop(){
    ;
}


text:
Is it possible to HTTP inside an ISR
I am developing a 247 monitoring system with Arduino. The values need to be sent to server periodically as well as upon interrupt (Watchdog). To access the internet, I am using the SIM800 module. Now, Is it possible to HTTP inside an ISR? As far as I know, Serial communication should not be used in ISR. Then how can I communicate with SIM800? Any suggestion will be valuable.

No, you cannot do HTTP in an interrupt, and you certainly can't use SoftwareSerial in an interrupt.
To trigger a heavy task in an interrupt you just set a flag (variable) which means "this task is due to be performed". Your main loop then checks that variable, runs the task, and resets the variable ready for the next time the interrupt triggers.
In multithreading environments these flags are called semaphores (yes, from the old signalling system using flags on ships). One thread (the interrupt) signals to the other thread (loop()) that it can do something.


text:
Controllino Debugging
Its a well known fact, that you can debug your arduino board with the help of an Atmel Ice. However, you might know the Controllino which is an arduino compatible device.
It has an ATmega2560 on it.
Do you have an idea how to debug a controllino? I neither see any ICSP port nor did I found anything useful around this topic.
Any help is greatly appreciated!

Connector X1 has the pins you want.
ICSP is shared with the SPI pins. Wire those to your ICE in the same way as you wire the SPI pins of the ICSP header on a normal Arduino to an ICE.

Thx for the fast answer. Is there anything else I need to know before I can start debugging? I read about cutting the reset line when debugging arduinos...


text:
Reading bits from a const char pointer
I'm getting a bit tripped up on const char pointers lately.
I'm getting a message from a server that comes through as either a c style string, a standard library string, or a WString:

I'm sending down a buffer of 32bit values from my server that aren't ascii or utf text, they're just bit values I want to parse and read on the esp32 side:

I thought "oh, I'll just mask the bit values 32 bits at a time and right shift the data to get the message (in reverse order, but still I can work with that). The problem that I'm running into is that I can shift numbers but not strings or byte arrays.
I wrote out a function to allow me to grab a piece of the string 32 bits at a time and convert that into a number while using an offset:
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 8; i++)
  {
    payload <<= 0;
    payload += data[i + offset];
  }
  return payload;
}

But when I try to grab the first couple of 32 bit chunks the data isn't what I expected:
void handleGameFrame(const char *data, uint32_t length)
{

  uint8_t phaseAndColission = get32BitInt(data, 32);
  uint8_t player = getByte(data, 32 * 2);

  Serial.print("data: ");
  Serial.println(data);
  Serial.print("phaseAndColission: ");
  Serial.println(phaseAndColission, DEC);
  Serial.print("player: ");
  Serial.println(player, DEC);

}

yields:

I know the Serial.println(data); isn't going to output anything b/c it's a c-string of non-printable values, but the other chunk grabbing isn't giving me the same output from my server. It's hard to verify everything without being able to see all of the bits in the overall data pointer and I think I tied myself in (another) knot.
Is there a good way to parse 32 bit values out of a const c-string?

"they're just bit values". You mean, they're just uint32_t that are being pointed at with a const char * ?

Oh, I just mean data (the const char *) holds bits in it that can't be Serial.println-ed because because even in 8 bit form they're not ascii/utf valid characters so nothing goes to the monitor.

but yeah, data is a c-string of bytes and I know that I want to interpret it as 32 bit integers, I just can't figure out how to do it.

Well, "c-string" basically means zero or more non-'\0' followed by '\0'.  If any of your numbers happen to have a zero byte in them, that will terminate the "string" before the end of your actual data. E.g. 0xAA00BB.  It's really just not a string at all.  In terms of how you get the data out of it, if it's properly aligned for uint32_t, you can just const uint32_t *ui32p = reinterpret_cast<const uint32_t *>(mycharptr);  If it's not aligned, you would do something like memcpy it into an array or individual elements into a single uint32_t variable.  There's nothing really "Arduino" here.

might have to hex encode the values to transmit them.

it looks like a X->Y problem. "I'm getting a message from a server that comes through as either a c style string, a standard library string, or a WString" why?

@Juraj those are the message formats that the library I'm using gives me. There's not an option for just a buffer of bytes. I would think that the c-string is the equivalent of the buffer, but there's the null terminator issue.

You wrote:

I wrote out a function to allow me to grab a piece of the string 32
bits at a time and convert that into a number while using an offset

This function is almost correct. Try this:
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 4; i++)
  {
    payload <<= 8;
    payload |= data[i + offset];
  }
  return payload;
}

Compared to your version, the differences are:

It reads 4 bytes instead of 8, as 32 bits are four bytes.

For each byte being read, it shifts the payload by 8 bits (i.e. one
byte) instead of zero. Shifting by zero has no effect.

It uses |= instead of +=: just a micro-optimization for the sake
of 8-bit MCUs. It shouldn't make much if a difference on a 32-bit
micro.

Oh my god. I can't believe I missed that bit shift by zero :facepalm: I know the for loops conditional check is also wrong, but I can't believe I missed the shift error. Thanks for pointing those out and also the bitwise or optimization. I appreciate you taking the time to correct the function :bows:


text:
Two batteries sharing ground?
I need to power my arduino and 2 DC motors requiring 6V each, I want to power the DC motors with a 6V battery through the vM pin on an h-bridge and use a 9V battery to power the Arduino itself.
On my breadboard I have a dedicated power line and ground line on each side, is it okay to share the ground between both batteries and consequently share grounds for any servo motors or sensors i connect?

What sort of H-bridge?  If it's the dreaded L239D or L298 you probably want more than 6v for the motor supply anyway, 6xAA would likely run your motors and your Arduino.  Anyway, yes, you need a common ground between the battery packs, though preferably the Arduino and the power side of the motor driver have independent wires to the battery packs, and only meet there.

@ChrisStratton It's actually a motor controller my bad, it's this one: Sparkfun TB6612FNG. I just wasn't sure if I could power the DC motors with an external battery and connect ground to common arduino ground.
So you're saying it's okay to use a 9V battery to supply voltage to arduino via its Vin and gnd pins AND use the external battery to power the motors and share ground with the Arduino?

@DenKart that driver requires some additional protection, pay attention to flyback when reversing polarity (changing direction of motor) and stopping the motor. The collapsing EM field can kill your arduino as well. Google for ways to protect your hardware. Do you have an oscilloscope?

The TB6612FNG is much better than the L293.  That might be okay with 6v (4 cells) though you could also consider five or six - you can just run the motor at a lower PWM.

@ChrisStratton Also here's a sketch of my circuit, could you tell me if this is fine? https://ibb.co/iEhKMc I included the specs of the h-bridge too as a note

@user2497 Could you elaborate on more protection? I've been using it just fine to drive my motors forward, backward and stopping.

Your sketch does not show a TB6612FNG, it shows an L293D workalike that shares most of that obsolete design's problems.

@ChrisStratton Couldn't find the motor controller on Fritzing so I put that one and included the pins on the TB6612FNG. I'm just wondering if my circuit is fine with the two batteries?

@DenKart Well, no problem then. The datasheet advises caution. I guess I’ll not need to worry about this then.

Not only can you share the grounds - sharing the grounds is required for there to be any form of meaningful circuit for signals to get around the place.
To copy-and-paste a blog post I wrote some time back:

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:
Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.
The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally, you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to [the new] ground.
So ground has to be a single point in your circuit against which all voltages “make sense”.
Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It doesn't matter. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?
The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.
That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?
Well, seen from the Arduino’s point of view, with respect to its ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?
Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.
There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.
In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device.  If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.
So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.
In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.
Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.
But isn’t it dangerous?
Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:
I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.
This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.
Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.
So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.


text:
put_index = (put_index + 1) % 100;
Can someone interpret the code in the Title line for me?  Specifically the function of the "%" sign?  It is a line having to do with a 100 element circular buffer.

More a simple coding question.  Not really a question about the Arduino.

which programming language?

use http://symbolhound.com/ for research

The % is the modulo operator in C/C++, which basically means:

Divide the value to the left of the % by the value to the right of it
Discard the quotient and keep only the remainder.

For instance, 10 % 5 = 0, because 10/5 = 2 with no remainder. Whereas 11 % 5 = 1, because the remainder of the division is 1.
In your case, the modulo operator is likely being used to keep the value of put_index less than 100 at all times. If it became 100 because of the operation put_index = put_index + 1, then the modulo operation would make the 100 into 0, so put_index will keep incrementing 0–99 repeatedly.

In C the % symbol is the modulo operator : https://en.m.wikipedia.org/wiki/Modulo_operation


text:
Is it possible to transmit radio signal with cheap 433Mhz transmitter as strings and receive it with an RTL-SDR
I have these Arduino transmitters and receivers.
They are very common. I am just trying to transmit a "Hello" Message using this code.
#include <RH_ASK.h>
#ifdef RH_HAVE_HARDWARE_SPI
#include <SPI.h> // Not actually used but needed to compile
#endif

RH_ASK driver;
// RH_ASK driver(2000, 4, 5, 0); // ESP8266 or ESP32: do not use pin 11 or 2
// RH_ASK driver(2000, 3, 4, 0); // ATTiny, RX on D3 (pin 2 on attiny85) TX on D4 (pin 3 on attiny85),

void setup()
{
#ifdef RH_HAVE_SERIAL
    Serial.begin(9600);   // Debugging only
#endif
    if (!driver.init())
#ifdef RH_HAVE_SERIAL
         Serial.println("init failed");
#else
    ;
#endif
}

void loop()
{
    const char *msg = "hello";

    driver.send((uint8_t *)msg, strlen(msg));
    driver.waitPacketSent();
    delay(200);
}

But they have to be received from the receiver module using another set of codes which I have done it.
But my question is, is it possible to receive the transmitted message with one of RTL-SDR's INSTEAD of using the receiver module? If so, How to do it?

yes, it is possible ... use a PC or a Mac ... run an audio recording program such as Audacity to see the waveform

@jsotola Ah I see, then how do I decode the audio into a string?

i saw an article on the web once ... i think that it read the data from a weather station.... google sdr decoding weather station

Found it thanks, i will just put the link here for anyone interested: https://www.rtl-sdr.com/tag/weather-station/

In general you can use RTL-SDR to decode any AM and FM modulated signals (+some digital modulations) that lie within the frequency range form roughly 50MHz to about 1GHz. So 433MHz is confortably within that range.
There are many projects on GitHub that leverage the RTL-SDRs ability to decote 433MHz OOK modulated signals like:
RTL_433
Which comes with a ton of decoders for various appliances.
OOK_Decoder
Which will give you the demodulated raw output for you to decode the bits yourself.
I'm sure you will find more but those are in my opinion the most noteworthy for the 433MHz OOK space.


text:
Arduino Nano IOT33 - Using flash
I'm looking for a way to store data on flash as on ESP8266 or ESP32 using FS.h,  LITTLEFS.h but it fails.
Is is possible on Nano IOT33 ?

the SAMD21 on Nano IoT has only 256 kB of flash. esp has at least twice as much. and file system is usually used on esp with 4 MB flash

It seems this library can be used:
https://github.com/cmaglie/FlashStorage
Library: FlashStorage library for Arduino
About info: A convenient way to store data into Flash memory on the ATSAMD21 and ATSAMD51 processor family
Mentioned in external related article (thanks to Juraj): https://forum.arduino.cc/t/persistent-storage-for-arduino-nano-33-iot-no-eeprom/623137
UPDATE
(See remark of Juraj below: this is NOT for a Nano IOT33)
See Library: https://github.com/khoih-prog/FS_Nano33BLE
About info: Wrapper of FS (LittleFS or not-advisable FATFS) for Arduino MBED nRF52840-based boards, such as Nano_33_BLE boards. This library facilitates your usage of FS (LittleFS or FATFS) for the onboard flash. FS supports power fail safety and high performance
Mentioned in:
https://forum.arduino.cc/t/fs-nano33ble-library-for-nano-33-ble-using-littlefs-fatfs/900463

That one I saw, but it seemed as EEPROM more than FS

It's not the same thing, but you can kind of mimic it (it both stores data).  As Juraj already mentioned, it also is about the amount of memory.

I updated my answer with a FS library.

Nano BLE is a different board with a different MCU and a an Arduino core based on mbed. the nRF52840 has 1 MB flash memory

@Juraj Thanks for that remark, I will keep the answer but make a comment just to keep others informed.


text:
Understanding MOSFET parameters - Dimming/Switching LED strip
I'm trying to create a dimmable/ switchable 12v LED strip using an Arduino board and a MOSFET. Many tutorials can be found doing so such as this youtube link.
I've bought a LM317T before I had any substantial knowledge regarding MOSFETs. Trying to understand using some tutorials ( each one used different MOSFET ) made it partialy clear what parameters to look for in such project mainly using this link, but some left in the dark - and this is the reason for this post ( and to understand why my MOSFET is not suitable ).
I'll compare with one suggested, FDC855N
1) It has to be "Logic Level" MOSFET, meaning Vgs has to be 5v: from what I understand, 0v at the gate you get 0v at the drain and at 5v at the gate you get maximum Vsource. it is correct ?
1a) FDC855N Vgs's value is +/- 20v, how is it Logic Level ? will Vdrain @Vgs=5v will be different when @Vgs=17v ?
1b) Why in FDC855N Vgs have 2 values when Rds(on) is noted?  one is 10V and other is 4.5v ?
2) Vgs(th) stands for minimal voltage needed for current flow at to drain. it is correct ?
2a) why is it noted as @Vgs=Vds ?
3) why Rds(on) is important for ? only for power dissipation purposes ?
I'll be glad to have answers for those question in comparison to the 317T MOSFET, since 317T datasheet has a different terminology :(
Appreciate any help,
Guy

Why are you mentioning LM317T in the same sentence as MOSFET? It's adjustable linear voltage regulator. And about the voltages: gate is insulated from D-S channel by really tiny insulation layer with breaking voltage somewhere just over maximum voltages between G-S or G-D (doesn't matter which one). That also means gate has its capacity. Thats the only current to the gate - charge or discharge gate.

@KIIV - is it not a MOSFET ??

No, LM317T is not a MOSFET.

@KIIV - OK, so it is not :) can you please explain parameters not in comparison to 317

you need mosfet that is fully open with Vgs=5V (most arduinost are 5V). 1a) 20V is maximum voltage between gate and source. Higher voltage may destroy the insulation and whole transistor.

1b) Rds(on) is not only one nor two values. It's a function of Ids and Vgs. 2) Vgs(th) I'm not sure about this one, it might be voltage the transistor starts opening. It's voltage, only current you'll see is current needed to charge/discharge the gate capacitance. 3) yes, it's really huge difference if you have 10A on 20mOhms and 100mOhms. The first gives you voltage drop 200mV and therefore 2W of power dissipation and the second 1V voltage drop and 10W power dissipation (voltage drop times current).

regarding 1 - so even though 20v may be applied, 5v will supply max Vsource ?

@KIIV would you post it as an answer ?

MOSFET aren't binary devices. They aren't just ON or OFF. Think of them like water taps. Vgs(th) is the voltage at with the mosfet starts to turn on. A bit like how much you have to turn a tap before it starts dripping. To turn it on more, you require a higher voltage. The amount of water flow also depend on what's attached to the tap. Like for example a dripper hose, sprinkler, or a kinked/blocked hose.

2a that just what they used during their measurements. That the downside of those datasheets. Sometimes the voltages or currents you use in your applications aren't specified in the datasheet. You'd have to interpolate from the values that are specified. Sometimes you can use the graph to lookup your case.

3 indeed. The lower the Rds(on), the less heat is being generated. This mostly applies to high current loads. This resistance will also generate a voltage drop. The voltage across the load therefor gets (a bit) lower. Depending on the application, this could have unwanted effects.

First of all, the LM317 and the are FDC855N different types of devices.  The LM317 is a voltage regulator whereas the FDC855N is a discrete MOSFET.
A MOSFET will act as a fast switch allowing you to control the LED's brightness using Pulse Width Modulation.
For what you're trying to do, you can think of the MOSFET as a voltage-controlled switch.  If the voltage between the gate and source (Vgs) is greater than the threshold (Vgs(th)), then the current will flow from the drain to the source (Ids).
1) Yes, anything over the typical Vgs(th) of 2.0V, will turn on the switch and cause current to flow; you need to provide a voltage across the drain and source (Vds).
1a) 20V is the maximum rating of Vgs, if you applying anything greater, you'll damage the device.
1b)  In reality, the MOSFET is more complicated than just an on/off switch.  The gate to source voltage (Vgs) determines how hard the switch is turned on, so increasing Vgs will turn the switch on harder and reduce the resistance (RDS(on)) between the gate and source.
2) Yes, this is essentially correct.  The relationship follows a curve and Vds(th) represents an inflection point.  This plot from page 3 in the datasheet shows the curve for different temperatures.  You can see that the 25C line is basically zero until Vgs reaches about 2.75 volts and then it increases rapidly.

3) RDS(on) is the resistance between the drain and source when the MOSFET is on.   You can treat the drain to source path like a resistor and use RDS(on) to determine the power dissipation.  For example if your RDS(on) were 0.1 ohm and the current through the drain is 1.5A, then you would be dissipating I^2*R = (1.5)^2*(0.1) = 0.225 , which is below the maximum allowable steady-state power dissipation of the device (Pd) of 0.8 W.


text:
Local char* - keeps its value
Sorry for novice question in Arduino, but I'm trying to figure out why res is keeping its value when up_cmd0 is being called again.
for example - if num=8 in first run and the result is :up_cmd0_res: 8, and second run num=12, the result is: up_cmd0_res: 812
void up_cmd0(){
  char num[8];
  char *res = "up_cmd0_res:";
  itoa(counter2, num, 10);
  strcat(res ,num);
  client.publish(inTopic,res);

char *res = "up_cmd0_res:";

In principle, res should be a const char *. Const because it is
pointing to a literal string, and you cannot (ar at least, you are not
supposed to) change a literal string. The compiler should warn you on
that... if you enable compiler warnings.

strcat(res ,num);

This is very wrong. strcat() expects as its first argument an pointer
to a modifyable array large enough for the resulting concatenation
(and the terminating \0). In other words, you have to allocate enough
room for the whole string, then fill the beginning of the allocated
array with the first substring, then only call strcat():
char res[24];
strcpy(res, "up_cmd0_res:");
strcat(res, num);

What happened is that you initially had, in memory, something like this:
<----- memory reserved for the string literal ---->
'u' 'p' '_' 'c' 'm' 'd' '0' '_' 'r' 'e' 's' ':' NUL
 ^-- res

On the first call to stracat(), you overwrite the terminating NUL and
end up with
<----- memory reserved for the string literal ---->
'u' 'p' '_' 'c' 'm' 'd' '0' '_' 'r' 'e' 's' ':' '8' NUL
 ^-- res

Note that the new terminating NUL is now occupying a byte in memory that
hasn't been allocated for this purpose. You have likely overwritten some
global variable. Next time you call strcat(), you again replace the
terminating NUL and continue to overwrite whatever happens to be stored
in this part of the RAM. Expect a crash or program misbehavior.

thank you for your answer- can you please explain in what cases should I use char* instead of char ? and why def of res at the begining of the code as a predefined value- at the begining of function does not override is value ?

@Guy.D: 1. Re char* vs char[]: that's not a simple topic, but it's thoroughly covered in the section Arrays and Pointers of the C FAQ. Read it: it has in one place the answers to all the questions you are asking here. 2. Re def of res does not override is value: res is not a string, it's defined as an address and initialized at the beginning of the function to the place in RAM where the compiler stored the anonymous string literal. See also the other answers.

Only the pointer, *res, is a local variable. The string "up_cmd0_res:" itself is elsewhere in RAM, stored as a literal and not meant to be modified.
Your strcat() call overwrites (extends) the literal each time you call it - which, by the way means that the growing string will be overwriting something else - whatever was following the string literal in global memory!!
You need to provide a character buffer within your function, large enough to hold "up_cmd0_res:" plus the longest thing you might ever append to it, plus one more byte for the zero-terminator. That buffer should be re-initialized on every function entry, before you append anything to it. Then make the strcat call to append to it. (These two calls will each manage the terminator for you).
The fact that this program didn't crash (or did it?) is only just by happenstance. If you call this function as it is initially written, enough times, your string literal will grow until it overwrites something important and either produces incorrect results (by over-writing some other data, or crashes (by overwriting the stack, especially the current function's return-address).

no. it did not crash

It will, in time.

It is incorrect to strcat into a field pointing to a literal. The code below is shorter, easier to understand, and does not corrupt memory:
 char res [20];
 sprintf (res, "up_cmd0_res:%i", counter2);
 client.publish(inTopic,res);

The field res needs to be long enough to hold the literal string (which is not modified doing it this way) plus the number you are adding to the end, and a terminating 0x00 byte.

can you please explain what "literal" is?

OK. A literal is when you literally put a string into a variable. For example:
char *res = "up_cmd0_res:";

So res isn't pointing to some variable, it is pointing to a literal string in the code. Now check this out:
void setup() {
  Serial.begin (115200);
  char * a = "foo";
  Serial.println (a);
  strcpy (a, "bar");
  Serial.println (a);
  char * b = "foo";
  Serial.println (b);
}

void loop()
{
}

Are you expecting this code to print:
foo
bar
foo

It should, right?, because the variable b contains "foo".
However it actually prints:
foo
bar
bar

This is because the strcpy has modified a literal string ("foo") to now contain "bar". The compiler is smart enough to think that every time it sees "foo" in the code it can place a single piece of memory with "foo" in it, because it is a literal (and literals don't change). But now you have modified that.
The compiler does give a warning:
/tmp/arduino_modified_sketch_905830/sketch_aug19a.ino:7:12: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
 char * b = "foo";
            ^

Imagine if you were able to change the literal 5 so that every time you added 5 to something it actually added 42? That wouldn't be so great, right?

Your code was worse than that, because you didn't just replace a string with something the same length, you used strcat which replaces it with something longer.

thank you for your answer. can you please explain what "literal" is ?

Because you're changing a string literal. These literals are in static memory, so they persist between function calls.
On top of that, changing them results in undefined behaviour.
You're also writing out of the bounds of the string.
My recommendation:
void up_cmd0(){
  const size_t int_max_digits = floor(log10(pow(2, 8 * sizeof(int) - 1))) + 1;
  char num[int_max_digits + 2]; // max digits + minus sign + null terminator
  const char *str = "up_cmd0_res:";
  char buffer[strlen(str) + sizeof(num)] = {};
  strcat(buffer, str);
  itoa(counter2, num, 10);
  strcat(buffer, num);
  // ...
}

You shouldn't be using globals to get values from one function to the other (counter2), try to pass it as a parameter to the function.