text:
How arduino PORTB pins are addressed if I want to access them with pointer?
So Let say I want to access Digital Pin 13. Thats port B pin. Is there an memory address associated with this pin 13 of Arduino Uno r3?
How Port B pins are addressed with corresponding pin numbers like What is the address of digital pin 13?
Currently I am assuming its pin address is 0x05 so my pointer looks like this
    uint8_t *adr=0x00+0x05;

Now If I do
  *adr |= 0x20;

then should I expect that I am writing to some pin so I like to know which data sheet I should refer for pin addresses of port B?
Currently my code is not working because no matter which pin I connect my LED to it blinks. What if I dont want to use any library and just write to address and I need PORT B pin address how to refer to different pins?
Now assume I have a code that uses avr gcc
#include <avr/iom328p.h>//avr/io.h
#include    <util/delay.h>
#include <avr/sfr_defs.h>

#define     BLINK_DELAY_MS  18000

int main (void)
{
    DDRB |= _BV(DDB5);

    while(1)
    {
        PORTB |= _BV(PORTB5);
        _delay_ms(BLINK_DELAY_MS);

        PORTB &= ~_BV(PORTB5);
        _delay_ms(BLINK_DELAY_MS);
    }

    return 0;
}

What is the values correspond to DDRB and _BV(DDB5); and PORTB and _BV(PORTB5);? I like to do it with pointers so I need addresses of PORT B all pins I know the macros but I like the actual addresses . there should be a some datasheet for this what  its called. Does arduino has it that gives memory mapped addresses?
The above code is simply for blinking LED light

What did you find when you looked into the included header files? What did you find when you read the documentation of avr-libc? What did you find when you looked into the Mega128 data sheet? Why did this not help you?

@thebusybee what not making sense to me is this PORTB |= _BV(PORTB5) and DDRB |= _BV(DDB5); why PORTB generic address is used and what the hell is DDRB |= _BV(DDB5);  where is the documentation on this memory mapped io. This is simple question. I checked gcc avr it's has addresses. But shouldn't  there be some description for these macros and addresses. It's must be in data sheet but wait what I actually found was tuns of pages about pin layouts when search for arduino uno r3 datasheet.

That's why this question. It should have been pretty simple for what I am looking for but seems like there is lack of info. I need explanation

Exercise your web search skills and look for "atmega128p data sheet" and "avr-libc". You might need to read and think a bit, not everything in the real world is answered right away in the first link especially for you. We expect a bit of effort on your own.

I think your problem is some misconception about how are io pins handled. Port is for multiple io pins. One io port is handled with one bit of the port register.

The address of PORTB can be found in the ATmega328P datasheet,
section “I/O-Ports”, subsection “Register Description”. It is repeated
near the end of the section “Register Summary”, where it is documented
as:
0x05 (0x25)

Admittedly, this is confusing: there are two addresses! There is a
footnote that gives some hint on the reason:

When using the I/O specific commands IN and OUT, the I/O addresses
0x00 - 0x3F must be used. When addressing I/O Registers as data space
using LD and ST instructions, 0x20 must be added to these addresses.

To clarify, this register is mapped in two different address spaces:

It has I/O address 0x05. The I/O address space is a small (6 bits)
address space dedicated to I/O registers. It is actually too small to
host all the I/O registers. It can be accessed with the in and out
instructions. Addresses lower than 32 can also be bit-addressed with
the instructions sbi, cbi, sbis and sbic.

It has data address 0x25. This is a much larger address space that
gives access to all the I/O registers and to the RAM. It is used with
the ld/st family of instructions.

Since the C and C++ languages are not aware of the I/O address space, a
regular data pointer is assumed to always point to the data address
space. Thus, if you want to create a pointer to this register, you may
write:
volatile uint8_t *adr = 0x25;  // PORTB

Note the volatile qualifier. This is required to prevent the compiler
being too “smart” and optimizing out some of your writes under the
assumption that this is just RAM.
Then you may turn the LED on with:
*adr |= 1 << 5;  // set PORTB5

Withe the proper optimization options, the compiler may be able to
optimize this into sbi 0x05, 0x05, if it can prove that the address
stored in the pointer doesn't change.

I need addresses of PORT B all pins I know the macros but I like the
actual addresses.

I would recommend this:
volatile uint8_t *adr = &PORTB;

This avoids having magic numbers in your code, and makes the
programmer's intent clear.
One last comment. When compiling your code I got:
include/avr/iom328p.h: [...]
error "Include <avr/io.h> instead of this file."

Just include <avr/io.h>: this header takes care of including both the
correct <avr/iomXXX.h> and <avr/sfr_defs.h>.

I'd just dropped a comment about memory mapping the SBI part on the other answer. It's like having my mind read.

re: "if it can prove that the address stored in the pointer doesn't change": you can give it a hand by making the pointer const, e.g. volatile uint8_t * const adr


text:
Working with two analog sensors, ATmega16
I want to work with two analog sensors connected to ATmega16. The first one is the temperature sensor (LM35), connected to PA0. The LED should be ON when the temperature goes high. The second one is the photo-resistor and it's connected to PA1. I want to turn the LED ON when the lighting is low.
I was looking for a solution all over the internet, but couldn't find something similar to my situation. They all just say one thing- you can't read two analog sensors at the same time.
I have this code that works just for one sensor:
#define F_CPU 1600000UL
#include <avr/io.h>

void ADC_Init() {
    DDRA = 0x0;
    ADCSRA = 0x87;
    ADMUX = 0x40;
}

uint16_t ADC_Read(uint8_t channel) {
    ADMUX = (ADMUX & 0xF0) | (channel & 0x0F);
    ADCSRA |= (1 << ADSC);
    while (ADCSRA & (1 << ADSC)) ;
    return ADC;
}

int main(void) {
    ADC_Init();
    DDRB = 0xFF;
    while (1) {
        uint8_t value;
        value = ADC_Read(0);
        if (value > 70) {
            PORTB |= (1<<0);
        } else {
            PORTB &= ~(1<<0);
        }
    }
}

Can you somehow help me to modify this code, give me advice on how can I do it, or some example?

What happens when you change ADC_Read(0) to ADC_Read(1)?

@devnull it works just for one sensor at a time. If I go with ADC_Read(1), it will work for the second sensor. I tried to adjust it using a switch loop, the first case ADC_Read(0), the second one ADC_Read(1), but it won't work.

Good. Since the MCU can't do any two things programmatically at the same time, you can read from channel 0 to one variable, read from channel 1 to another variable, than decide what to do with the LED(s) accordingly to the two values. You may also edit your question to show this second code you mentioned, since your test indicates that the hardware/ADC part is already working for the two sensors.

I reformatted the code for legibility and, while doing so, I took the liberty to add the closing brace that was missing from ADC_Init().

I’m voting to close this question because the user has not been here for over one year, so the chances of this question being accepted is very slim.

I just skimmed over the ATmega16 datasheet, so perhaps take this answer with a grain of salt.
It is technically true that you cannot read two ADC channels at the same time because there is only one ADC and you must multiplex the various channel inputs to that one ADC. You can, most likely, change the ADC source at runtime to switch between the different channels.
Take a look at the ADMUX register description in the datasheet
Right now, you set the mux once during the init() function and then never change it. In your new code, you will have to change the value in the register at runtime (in addition to any other configuration/housekeeping that is required) which should happen in your main loop()
High level description:
int main()
{
    system_init();

    while (1)
    {
        set ADMUX to read from PA0
        read ADC

        set ADMUX to read from PA1
        read ADC

        do stuff
    }

}

I understand what you mean, but if I do it in the main loop it won't run infinitely, and the channel will be changed only once. How can I constantly change between those two sensors?

@cerouno If you put the above code in your while (1) loop it will run indefinitely. I will edit the pseudocode above to show this.

If you read the datasheet carefully, you will find the fact, that you should throw out the first reading after the input switch operation.

source: Stack Exchange

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

sort: votes


text:
Arduino Wire library and Type Cast help
I'm having troubles understanding this line of code that I see with every Arduino EEPROM tutorial.
int saveLocation = 4095;
Wire.write((int)(saveLocation >> 8));

Question 1: Do the parenthesis indicate that the bitshift happens BEFORE the type cast? What's the order of operations?
According to the wire library documentation, you can use wire to send the following:
Wire.write(value) // value to send as a single byte
Wire.write(String) // a string to send as a series of bytes
Wire.write(data, length) // an array of data to send as bytes, the number of bytes to transmit.

So my variable, int saveLocation = 4095 is not a string or array, so it must be a considered as a 'value', which means it's being sent as 1 byte.
Question 2: If it's being sent as 1 byte, why would I cast it to an integer of 2 bytes?
Question 3: If saveLocation is already an integer, why would cast it to int?
Question 4: Since int is two bytes, does wire.write only send out the lower byte?
Thanks in advance for the help.

you're missing 1/2 of the EEPROM addressing code

You are right about being confused. This casting doesn't make any sense.

Question 1: Do the parenthesis indicate that the bitshift happens BEFORE the type cast? What's the order of operations?

Yes, the bitshift happens before the casting because of the parentheses.

Question 2: If it's being sent as 1 byte, why would I cast it to an integer of 2 bytes?

You wouldn't. It is cast to uint8_t (aka byte) anyway by the parameter type.

Question 3: If saveLocation is already an integer, why would cast it to int?

Doesn't make sense to me either. You don't need to. Though it also doesn't hurt here (same goes for question 2)

Question 4: Since int is two bytes, does wire.write only send out the lower byte?

Yes, only the lower byte. The function parameter is of type uint8_t, which is exactly one byte. Thats the reason for the bit shifting. By shifting the value right by 8 you effectively shift the high byte to the low byte position.

Dude I thought I was nuts! But what I don't understand is if you search online for code to address EEPROM chips, they all use that line for sending data. I thought that surely I had to be missing something because EVERY tutorial has that same stupid line of code. Thank you for helping me clear this up!

Often when an example code is written it gets copied over and over throughout the internet.

Question 1: Do the parenthesis indicate that the bitshift happens BEFORE the type cast? What's the order of operations?

Yes. What's in the brackets is evaluated then the result cast to int.

Question 2: If it's being sent as 1 byte, why would I cast it to an integer of 2 bytes?

You wouldn't.

Question 3: If saveLocation is already an integer, why would cast it to int?

You wouldn't

Question 4: Since int is two bytes, does wire.write only send out the lower byte?

Yes, just the lowest 8 bits.
The cast to an integer is completely redundant here. It's not performing anything other than making the code harder to understand. You can remove it and it won't make any difference.
In fact the presence of the int cast triggers an overloaded function:
inline size_t write(int n) { return write((uint8_t)n); }

So it just re-casts it to an unsigned 8-bit integer (byte) anyway.

Thank you Majenko as well. I don't understand why all the code online for EEPROM chips use this line of code, it's beyond confusing.

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


text:
Can't read through I2C from RTC
I'm using an ESP32 which I connected to a MAX31329 RTC through I2C.
Unfortunately I can't read any register from the RTC. After modifying the MAX31328 library didn't work, I tried reading single registers directly. Here is the code:
#include "Wire.h"

int seconds = 0;
int ret = 0;

void setup() {

Serial.begin(115200);
delay(500);

Wire.begin(33,32,100000);

delay(500);
Wire.beginTransmission(0x68);
  Wire.write(0x06);
  Wire.write(13);
  ret = Wire.endTransmission();
  if(ret != 0)
    Serial.println("i2c Setup failed");

  delay(500);
}

void loop() {

  Wire.beginTransmission(0x68);
  Wire.write(0x06);

  Wire.requestFrom(0x68,1);
  seconds = Wire.read();
  ret = Wire.endTransmission();
  if(ret != 0)
    Serial.println("Read failed");

  Serial.println(seconds);

delay(1000);
}

The register always returns 0.
Do you see the error in my code?
The datasheet of the MAX31329 can be found here.
I'm trying for days now and have no clue what the problem is.
Thanks a lot for your support in advance.
Best regards,
Martin

You are doing things in the wrong order.

 Wire.beginTransmission(0x68);
 Wire.write(0x06);
 Wire.requestFrom(0x68,1);
 seconds = Wire.read();
 ret = Wire.endTransmission();

The request is sent on the endTransmission call, so you need to do that before trying to get a response. In other words:
  Wire.beginTransmission(0x68);
  Wire.write(0x06);
  ret = Wire.endTransmission();

  Wire.requestFrom(0x68,1);
  seconds = Wire.read();

To read the max31329 you do need to do the following as Nick Said
Wire.beginTransmission(0x68);
Wire.write(0x06);
ret = Wire.endTransmission(false); //No Stop, so the request is a restart

Wire.requestFrom(0x68,1);
seconds = Wire.read();

But it needs to be a repeated restart following the write to register 0x06, hence the false in Wire.endTransmission(false). It took me ages to figure out as the DS3231 and MAX31328 don't required this, I actually found this writen in the data sheet for the MAX31343 which has a similar set of registers with seconds starting at 0x06 unlike the previous clocks that start at 0x00. Interestingly with these ones, reading the status register 0x00 will return to you any flags for interupts and automatically reset them after reading the register, which I think is new and better.

I have been using the ESP32 for about 10 years now and it can be finicky
I2C is an Open Collector interface requiring Pull-up resistors to work.
If you are using a board module it likely has the pull-ups if not make sure you have them (around 1.5K OHMS) from SDA and SCL to 3.3 Vcc.
I suggest starting with Arduino's i2cdetect.ino and debug if it is being seen.
If not you have a wiring issue.
while both other answers are fairly good, you show no schematic or mention if you are using a RTC board.


text:
What is the default baud rate without calling Serial.begin?
I cannot find the answer from official document and also surprised no one asked the same question.
What is the default baud rates if I didn't call Serial.begin?

There is no default baud rate. When the sketch starts, the serial port
is disabled (thus non-functional). Calling Serial.begin() enables the
port.

Really appreciate! I just found even though I use Serial.println in loop function. The TX LED light won't blink unless I added Serial.begin in setup function.

Just for completeness: On some alternative boards that are also compatible with Arduino IDE (like e.g. ESP8266 and ESP32 boards), some information is transmitted on serial before your sketch even starts. The default baud rate then is dependent on the chip and/or board.


text:
Arduino Leonardo/Pro Micro sleep and USB
I am using an Arduino Pro Micro (basically a Leonardo in a smaller form factor) in a mobile application where power consumption is really important.
To reduce power consumption, I put the Arduino to sleep, but that disconnects USB. That's not really acceptable in this application, since reconnecting USB after the Arduino wakes takes pretty long (a second or two).
Is there some way to keep the USB connection alive while still conserving energy? E.g. by waking the ATMega32u4 frequently to keep the connection alive? Or is there some not-as-deep sleep moden where the USB connection stays alive?
Edits for clarification:
The device is an USB HID device. If the device goes to sleep after a few minutes of inactivity, having to reconnect after the user pressed a button causes quite a long delay between pressing the button and a reaction on the device.
I am using the ATMega32u4's native USB implementation, so no V-USB or anything similar.
I am putting the device to sleep like so:
Keyboard.end();
USBCON = 0;
LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF);

This is how I wake it up again:
USBDevice.attach();
delay(50);
Keyboard.begin(KeyboardLayout_en_US);

Did you try LowPower.idle(...);?

No, not yet, I will try that, thanks!

@EdgarBonet That's exaclty what I needed, it works perfectly, thanks! Do you want to post this as an answer so I can accept it?

Removing the power LED can reduce power consumption also.

@sa_leinad Thanks for the input, I was planning to do that!

The Arduino has several sleep modes. They differ mainly by the clocks
that are kept running, the peripherals that are enabled, and the
possible wake-up sources. All these modes are described in the
datasheet of the ATmega32U4 microcontroller, section 7:
Power Management and Sleep Modes.
You may see here that “Power-down” is one of the deepest sleep modes:
all clocks are disabled, the main oscillator is turned off, and only
asynchronous wake-up sources are available. As you have experienced, the
USB port is not functional in this mode.
In contrast, “Idle” is a somewhat shallow sleep: the CPU is halted but
the peripherals remain clocked. Any enabled interrupt can be used as a
wake-up source. This is a good option if you want the USB link to remain
connected while sleeping, and you can get it with the LowPower.idle()
function.
If you are worried about the sleep mode to be too “shallow” and not save
enough energy, note that the parameters if LowPower.idle() let you
specify which peripherals you want to keep running during sleep. If you
keep running only those that are needed, this should limit the power
consumption to what is strictly needed.

Thanks a lot, this solved my problem! Thanks also for the really nice write-up!

This would better serve as a comment, but I can't post comments (yet)...

What is your application doing? Is it supposed to be asynchronous? Why are 1-2 seconds too long?
By the "USB" connection, you mean the UART/Serial peripheral?
How are you putting the board to sleep? Are you using the Arduino Sleep Modes? If so, which one are you using?

I'll speculate a bit: if you are using the ASP, then you might have to change the source code for the functions you are using to accommodate for keeping that peripheral awake. Do note that it might make the application more power-hungry than you want it to be.
Waking up more often could be done, but ideally you would need a synchronization mechanism, because at least eventually you'll run into an issue where you might miss the data or you'll wake up the device so often, you'll lose your power savings.

the ATmega32u4 on Micro has native USB peripheral

I added the requested information to the question.

@Dakkaron thanks! I'll have to look at this more, this is not necessarily a trivial problem. I'd suggest trying out the standby mode and seeing if the USB is more responsive. Does your application require the powerdown mode? Also, why do you do "USBCON = 0" vs "USBDevice.detach()"?

Thanks for the feedback, I will try that. The main reason I didn't try that, is because my solution is what Google turned up. Thanks for the input!


text:
Using a Microchip Fubarino with the Arduino IDE, how to acces and configure all pins
I recently got a Microchip Fubarino, contains a PIC32MX250F128D and I'm totally new to the Arduino IDE, i uploaded the blink sketch all fine and well.
Schematic: FubarinoMini_v15_sch
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
//pinMode(LED_BUILTIN, OUTPUT);

//asm ("BSF PORTA,10");
//pinMode(RA10, OUTPUT);
//TRISA10 = 0;
TRISAbits.RA10 = 0;
//PORTAbits.RA10 = 1;
//PORTAbits.RA10 = 0; // set to output
//mapPps(20, PPS_OUT_SDO2)
}

// the loop function runs over and over again forever
void loop() {
//digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
PORTAbits.RA10 = 1;
delay(500); // wait for a second
//digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
PORTAbits.RA10 = 0;
delay(500); // wait for a second
}

restults in:
 Blink:45:12: error: 'volatile union __LATAbits_t' has no member named 'RA10'
LATAbits.RA10 = 0;

changing:
void loop() {
  //digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  PORTAbits.RA10 = 1;
  delay(500);                       // wait for a second
  //digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  PORTAbits.RA10 = 0;
  delay(500);                       // wait for a second
}

doesn't work either.
I also tried this example code:
https://github.com/fubarino/fubarino.github.com/wiki/Fubarino-Mini-pps
It does work.
#define LED 1
#define SCK2 4
#define SDI2 18
#define SDO2 20

The led on the Fubarino board is not connected to pin 1, but to RA10.
Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 & SDO2 to the above defined numbers.
Normally on a PIC16F84 or so, you would do something like this.
bank1
movlw b'00000001'
movwf TRISA

movlw b'11110000'
movwf TRISB
bank0

the Arduino "code" seems a bit abstract.
I Would like to experiment with the button.
The Chipkit pps example shows you can use the Microchip keywords from the devices datasheet.
Can the Fubarino be setup like a classic PIC device in the Arduino IDE?
Configuring all the pins before going in to loop, using the Keywords from the datasheet.

BTW, it's not a Microchip Fubarino. The Fubarino is made by Fubar Labs. Jacob would be furious if you tried claiming he was Microchip ;)

@Majenko, this is when i found the schematic from the board that's all i "knew/know", the microchip box that it came said chipkit, as does the Arduino IDE. however the schematic on the page of Microsoft is the same and the file name says that, witch i downloaded from microchip. By: Brian Schmalz and Rick Anderson
what is it?
further: 02/25/2013 - Microchip version
Changed USB connector to Microchip standard
Added CE, RoSH, and chipKIT graphics to silk on back

chipKIT was originally formed as a collaboration between Microchip and Digilent. Since then both have pretty much divested their interests in it and chipKIT is now a standalone entity, consisting of a number of dedicated community engineers (me, Jacob, Brian, Rick, Guy, etc), some ex-Microchip employees, some just people that love the PIC32 chips, like myself. Anyone can make a board that works with chipKIT, but to use the chipKIT name you have to have a trademark agreement with Microchip (we're trying to get control of the name from Microchip but they are dragging their heels).

The three main board makers now are myself (the chipKIT Lenny for example), Brian (Schmalzhaus boards, like the Quick240) and Jacob & Rick (Fubar Labs, the Fubarino boards). Most of the original boards (UNO32, MAX32, etc) were made by Digilent. I'm not sure if they're still making and supporting those or not. Many of the boards have been sold via Microchip's market place (who have also provided some manufacturing facilities in the past too) although they seem to have lost interest in that now.

Ever since Microchip bought Atmel they seem to have lost interest in chipKIT and focus all their attention on Atmel based Arduinos now. Even though the PIC32 is by far a vastly superior chip and the chipKIT framework boasts a much better codebase than Arduino ;) The main problem we are facing at the moment though is that of a compiler - Microchip have traditionally provided us with an open source version of their XC32++ compiler, but since OS X went 64-bit only they have really struggled with producing a new version for us.

I'm in the process (slowly) of adapting vanilla mips-gcc to work properly with chipKIT but it's a long hard job. The compiler part is fine, it's the low-level chip support libraries that are not simple, especially for the more complex PIC32MZ chips.

i made a midi sequencer with 23LC512 sram using a PIC18F452, by far not a consumer product, but it was 100% accurate in tempo or  synced to Albeton to what ever speed up to 999 BPM, 8 steps + button and leds, the statemachine i made was brilliant. but the 74hc595 and 74hc126 are kinda slow, used a microchip picdem 2 plus board.    but now i'm back newby again ... i love that i have a microchip programmer ICD3, i like PICs.

The entries in the "bits" structures are named after the bits.
It's not
TRISAbits.RA10

but
TRISAbits.TRISA10

The same goes for
LATAbits.LATA10

The only exception is the "port" one
PORTAbits.RA10

Which is a hangover from the old PIC16 chips that didn't have a LATx register.

The led on the Fubarino board is not connected to pin 1, but to RA10.

Pin 1 is RA10. If you look in the file Board_Data.c for the Fubarino_Mini variant (packages/chipKIT/hardware/pic32/2.1.0/variants/Fubarino_Mini/Board_Data.c) you can see all the pin mappings. There's a bunch of arrays there that define how everything fits together.
The second entry in most of those arrays (pin 1, starts counting at 0) is for RA10.  As for

Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 & SDO2 to the above defined numbers.

the PPS is a whole other mess on those chips. Pin 18 is not the 18th pin on the board, but digital IO pin number 18, which is the 19th entry in those pin array tables - RA4.  Mapping RA4 is done through the file packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/pingroups_1xx2xx.h which contains an entry:
#define _PPS_RPA4       (2 + _PPS_SET_C)

and the file packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/peripherals_1xx2xx.h which has:
PPS_IN_SDI2     = (35 + _PPS_SET_C + _PPS_INPUT_BIT),

Those are then used by the mapPps() function to map RA4 to SDI2. Something which is perfectly possible.
Yes, it's convoluted and a bit of a mess, but the best we could come up with given how limited the PIC32MX2xx IO multiplexer is.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
How to receive data from Xbee in AT mode on Arduino Nano
I need to print data on the Arduino serial monitor received from the Xbee in AT mode. I have searched on most forums and have not found anything on how to do this.
I have my Xbee tx connected to Arduino nano Rx and rx connected to tx.

You connected the Xbee to the single hardware serial interface that the Nano has. Is is also used by the USB to Serial chip, which connects to the Serial Monitor. So what you are sending to the Xbee is also sent to the Serial Monitor. What the Xbee sends is only sent to the Arduino (since the Xbee TX pin is connected to RX of Arduino and also TX of the Arduino's USB to Serial chip).
But you can separate then by using a SoftwareSerial interface on any other pins of your liking. Then you can connect the Xbee to it. Then forward the output of the SoftwareSerial interface to the Serial interface. To see how this works have a look the first example of the SoftwareSerial library. It's basically checking both interfaces, reads available data from one interface and writes it to the other (note the write() in contrast to print() since when forwarding you don't want to interpret the data again to another format like print() does).
Also there are plenty examples and tutorials about SoftwareSerial on the web. An important restriction is that only one SoftwareSerial interface can listen to data at any time. The Hardware Serial interface doesn't have such a problem.

Thank you for your reply. I will try this. You said that only one Software Serial can listen to data at once. Does this mean that I would not be able to connect a GPS module to a software serial interface on different pins as well as the Xbee module? How would I solve this problem?

When you are interfacing a module, which only will send data, when you ask for it, you can implement time sharing. So listen to one interface, asking the corresponding module for info and reading it. Then listen on the other interface, asking that module for info and reading it. Rinse and repeat. Though this only works if you cannot miss data from one module while you are reading the other. If you would miss data, you can change to a microcontroller with more Hardware Serial interfaces, like the Arduino Mega.

Ok thank you this makes sense.

How do I add the SoftwareSerial Library? It does not seem to come up in the Library Manager?

Because its already part of the Arduino Core. You don't need to install it. You can use it directly with the Arduino IDE.


text:
Arduino Micro digital output pins floating / high Z
so i recently got an arduino micro for a project needing the control of two stepper motors with the A4988 driver. previously i was prototyping on an arduino uno and everything was working fine, but on the switch to the micro the motors started behaving erratically such as random step direction and a random number of steps being taken. i've pretty confidently narrowed it down to the output pins floating, i've recorded the direction pin on the micro floating with ~2v being "off" and ~3v being "on" with a multimeter.
the thing is is that i can't find anything about fixing this other than doing.
pinMode(DIR, OUTPUT);
digitalWrite(DIR, HIGH);

or external pull resistors and i've tried both pull up and down resistors at 100k and 330 ohm with no luck.
right now i have one motor connected to uno and one to the micro, the motor on the uno still runs fine with no external pull resistors. the below schematic shows a simplified version of how both the uno and the micro are wired.

simulate this circuit – Schematic created using CircuitLab
and here is the code both arduinos are running.
#include "A4988.h"

#define MOTOR_STEPS 200
#define DIR 10
#define STEP 9

A4988 stepper(MOTOR_STEPS, DIR, STEP);

void setup() {
    pinMode(DIR, OUTPUT);
    digitalWrite(DIR, HIGH);

    pinMode(STEP, OUTPUT);
    digitalWrite(STEP, HIGH);

    stepper.setRPM(100);
}

void loop() {
    stepper.rotate(360);
    delay(1000);

    stepper.rotate(-360);
    delay(1000);
}

here are some links to other related post
https://stackoverflow.com/questions/14174162/arduino-micro-triggering-with-no-contact
https://forum.arduino.cc/t/high-impedance-output-pin/655236

the arduino is plugged in with usb and im using the 5v output on the micro (and i can confirm its 5v), and im also lead to believe that the digital pins operate at 5v

Ah, sorry, mistook it for the Pro Micro.

When you measure such voltages on the digital output of the Arduino there is something electrically wrong. Do these voltages persist, when you are not connecting the stepper driver (only the Arduino without anything connected)? Is the 5V pin staying at 5V when you have the stepper driver connected?

ok after waking up and taking a second look at it it appears to be a wiring mistake on my part, instead of being wired to pins 10 and 9 dir and step where on 9 and 8 and i feel a bit silly, but before moving to 10 and 9 the driver was connected to pins 3 and 2 and was still having the same erratic behavior. and the motor simply wont turn if plugged into the adjacent pins ((2 & gnd) / (4 & 3)) and the program adjusted. so i guess problem solved for me at least

You could write an answer to your own question


text:
Can not burn arduino pro mini 8 MHz bootloader with usbasp
I am using schematic of Arduino Pro mini 3.3v/8 MHz version. Please see below circuit diagram I built.

Power supply to circuit is 3.3V.
I have a USB ASP programmer which I used in previous version of same circuit running at 5V/16MHz. It was working fine.
It is connected to board like this.

I want to burn bootloader in this controller so that I can use with arduino IDE. I have done following settings.

When I connect USBASP to PC (Windows 10), in device manager, I see the USBASP. Driver installed through Zadig.

When I click Tools -->  Burn Bootloader in arduino IDE , I get this error
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

Error while burning bootloader.

What I have tried:
1 - Changed firmware of USBASP to official fishl.de website.
2 - Put JP3 on USBASP.
3 - Changed driver of USBASP from libusb-k to libusb-win32 from Zadig. Error changes to
Arduino: 1.8.15 (Windows 10), Board: "Arduino Pro or Pro Mini, ATmega328P (3.3V, 8 MHz)"
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override

     this check.

4 - Replaced microcontroller from some other board to this board.
5 - Checked voltage on 8 MHz crsytal pins of controller. 3.12V and 3.28V. Cant see wave on oscilloscope.
Nothing works. Same error. I was hopeful that maybe atemga328 is faulty but even after changing it, it doesnt work and I cant burn bootloader and get same error.
Can this be due to crystal capacitor values of 10 pF instead of 20pF? (I chose 10nF after reading datasheet carefully).
Any ideas why this problem?

The problem was related to crystal. When I changed to another crystal (different part number), it worked.


text:
Please help me navigate the stepper motor object definition in the documentation
I am trying to use the stepper library and the stepper object is documented like this

This function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board.
Use it at the top of your sketch, above setup() and loop(). The number of parameters depends on how you’ve wired your motor, either using two or four pins of the Arduino board.
Syntax
Stepper(steps, pin1, pin2)
Stepper(steps, pin1, pin2, pin3, pin4)
Parameters
steps: the number of steps in one revolution of your motor.
If your motor gives the number of degrees per step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps).
pin1, pin2: two pins that are attached to the motor.
pin3, pin4: the last two pins attached to the motor, if it’s connected to four pins.
Returns
A new instance of the Stepper motor class.
Example
Stepper myStepper = Stepper(100, 5, 6);
"""

The problem is that "two pins" and "last two pins" do not tell me anything about which pins go where on the motor driver. I am using a DM320T stepper driver
Can anybody tell me what "pin1 pin2 pin3 pin4" actually correspond to?

The standard Stepper library does not support stepper drivers, which only have a step (in this case labels "PUL" for pulse) and a direction pin (labeled "DIR"). So you need to use a different library. I suggest using the Accelstepper library, which is also more capable than the standard Stepper library. Then you can define the AccelStepper object like this:
AccelStepper stepper(AccelStepper::DRIVER, STEPPER_DIR_PIN, STEPPER_STEP_PIN);

About the connections: The shown driver is meant to be connected with twisted wire pairs, so in this case one wire for signal and the other for ground or 5V. Look at the documentation for your stepper driver. There you should be able to find a wiring diagram.


text:
Transfer a single pulse from Tektronix function generator to Arduino UNO
I have set up a single pulse (width of ~400 ms) using the burst feature on the Tektronix AFG3102 function generator and I want to transfer this signal to the digital pin of Arduino UNO. Essentially I want to continuously (in a loop) perform reading on pin 7 using the built-in digitalread() function. So I'm expecting to see 0 when I did not trigger the signal and 1 when I trigger the signal for a duration of 400 ms and then back to 0. However, this is not the case here as I'm just reading 0s even though I trigger my signal. Interestingly when I change the width of the pulse to 1ms I can see the signal coming through, but It does seem to work with 400 ms.
I have placed my code here for your review. I would highly appreciate some help on this.
void setup() {
    Serial.begin(9600); // start serial for output
    pinMode(7,INPUT);
}
void loop() {
      Serial.println(digitalRead(7));
      Serial.print('\n');
}

Thank you,
Nikan

To what voltage did you set the function generator? Also currently you are very fast filling up the Serial buffer. Have you tried a delay at the end of loop(), like 50ms, and/or increasing the baudrate to something like 115200?

Does your AFG share its ground with the Arduino? What does the pulse look like on the scope? Side note: there is no point in Serial.print('\n');, as Serial.println() already adds "\r\n". @chrisl: Filling the serial buffer should be no issue: it justs adds a small latency (< 7 ms) to the transmitted data.

@chrisl: the voltage from the function generator is at 3 Vpp, Also What Im not understanding is that when I send continuous square waves, PIN 7 starts to pick up at the voltage above 2 Vpp. Of course I need to keep this below 5.

@chrisl: Also to answer your questions regarding the ground. In fact they are connected.


text:
HOW convert momentary button to touch sensor TTP223?
I am trying to convert
this project https://maker.pro/arduino/projects/simple-fm-radio-receiver-with-arduino-uno-and-rda5807m
to  3 touch sensors TTP223.
But so far  my new code don't work.
Please can you have a look at these changes?
Update:
The code goes in loop and the serial monitor show:
push 3
push 4
push 2
push 3
push 4
push 2
and so on
I can also see in the oled, the 3 menu options change cyclically.
TTP223 sensor linked to pin 4 stay always with his red light on.
If I touch the sensor connected to pin 3,  menu does not change (Manual tune,  Volume, Auto tune).
(I have checked Touch sensors if they work alone).
|
|
//TTP223
#define Pin_DOWN 4   //  destra
#define Pin_UP 2     // sinistra
#define Pin_SET 3    // menù
#define FIX_BAND 1

int menu;
#define MAXmenu  3
int menux;
#define MAXmenux  3

|
|
void setup()
{
  Wire.begin();
  //Serial.begin(9600);
  Serial.begin(57600);

//TTP223
pinMode(Pin_DOWN,INPUT_PULLUP );
pinMode(Pin_UP,INPUT_PULLUP);
pinMode(Pin_SET,INPUT_PULLUP);
boolean SET=digitalRead(Pin_SET);
boolean UP=digitalRead(Pin_UP);
boolean DOWN=digitalRead(Pin_DOWN);

|
|
void loop() {
  int newPos;
  unsigned long now = millis();
 // static unsigned long nextFreqTime = 0;
  static unsigned long nextRadioInfoTime = 0;
  char c;
  /*entradaV = analogRead(entrada);

   #if DEBUG
      Serial.print("sensor = " );  Serial.println(entradaV);delay(50);
   #endif
   */
// Boton menu   d
/* if(entradaV>500 && entradaV<524)
   { */
//TTP223
if(digitalRead(3) == HIGH) {
    delay(150);
    Serial.println("push 3");
    menu++;
    if(menu>MAXmenu)menu=1;
    Visualizar();

    #if DEBUG
      Serial.print("menu = " );  Serial.println(menu);
    #endif
    //while(1020>analogRead(entrada))delay(5);

   }

// Boton derecho
/* if( entradaV<50)
   { */
//TTP223
if(digitalRead(4) == HIGH) {
    Serial.println("push 4");
    menux++;
    if(menux>MAXmenux)menux=MAXmenux;
    #if DEBUG
      Serial.print("menux = " );  Serial.println(menux);
    #endif
    switch(menu)
      {
        case 1:
          frecuencia++;
          if(frecuencia>210)frecuencia=210;
          delay(130);
        break;
        case 2:
           volumen++;
           if(volumen>15)volumen=15;
           // while(1020>analogRead(entrada))delay(5);
        break;
        case 3:
           busqueda(0);
           // while(1020>analogRead(entrada))delay(5);
        break;
        case 4:
           // LcdClear();
            tft.clearDisplay();
           // visualPI();
            delay(3000);
           // LcdClear();
            tft.clearDisplay();
            frecuenciaOld=-1;
        break;
      }
   }

// Boton izquierdo
/* if( entradaV<700 && entradaV>660)
    { */
//TTP223
if(digitalRead(2) == HIGH) {
    Serial.println("push 2");
    menux--;
    if(menux<1)menux=1;
    #if DEBUG
      Serial.print("menux = " );  Serial.println(menux);
    #endif
    switch(menu)
      {
        case 1:
            frecuencia--;
            if(frecuencia<0)frecuencia=0;
            delay(130);
        break;
        case 2:
            volumen--;
            if(volumen<0)volumen=0;
            // while(1020>analogRead(entrada))delay(5);
        break;
        case 3:
            busqueda(1);
            // while(1020>analogRead(entrada))delay(5);
        break;
        case 4:
           // LcdClear();
          tft.clearDisplay();
            //tft.print(frecuencia);
            //visualPTY();
            delay(3000);
           // LcdClear();
            tft.clearDisplay();
            frecuenciaOld=-1;
        break;
      }

   }
|
|

I guess you want to replace the momentary buttons in the project with touch sensors. How exactly doesn't your code work? Please provide a more detailed description. Did you try to read the touch sensors by themselves (without any other code or project part) to make sure that they work correctly?

And as the TTP223 gets configured via its jumpers, have you tried something like this to check their behavior?

I have update the post


text:
Problem deseralizing some fields in JsonRequest
I'm almost successfully able to GET a json blob and print it to the console. It seems to be failing on some string fields I am guessing because of the length. Any thoughts/ideas/suggestions to make this work?
The requested json blob (I can see this entire string from the console, it is spaced out here for readability). The entire length of the original string happens to be 597 characters.
{
    "expand":"schema,names"
    ,"startAt":0
    ,"maxResults":50
    ,"total":2
    ,"issues":[{
         "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
        ,"id":"94245"
        ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9425"
        ,"key":"BP-4349"
        ,"fields":{
            "summary":"QM: API Timeout Error on Checkout "
        }
    }
    ,{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields"
        ,"id":"93129"
        ,"self":"https://myServer.atlassian.net/rest/api/3/issue/9319"
        ,"key":"BP-4078"
        ,"fields":{
            "summary":"Search \"term\" options - broken in loader see sproc"
        }
    }]
}

The code I'm using to fetch this json object reduced as much as possible:
JsonRequest request(2048);
//...snip...// (inside JsonRequest object)
WiFiClientSecure *client = new WiFiClientSecure;
HTTPCliernt download_client;
download_client.begin(*client, url);
download_client.collectHeaders(headerKeys, 5);
download_client.setAuthorizationHeader(authValue);
download_client.setUserAgent( HARDWARE_NAME );
int httpCode = download_client.GET();
if(httpCode == HTTP_CODE_OK)
{
    String result = download_client.getString();
    download_client.end();
    client->stop();
    dsError = deserializeJson(*this, (uint8_t*) (result.c_str()) );  //this refers to this object which is the JsonRequest
    if(!dsError)
    {
        ...
        return true;
    .....
(outside JsonRequest object, request is a deseralized `SpiRamJsonDocument` )
//...snip...//

int total = request["total"].as<int>();                         //working: 2
int startAt = request["startAt"].as<int>();                     //working: 0
int maxResults = request["maxResults"].as<int>();               //working: 50
int totalRecords = total + startAt;
for(; startAt < totalRecords && maxResults > 0; startAt++, maxResults--)
{
    log_i("%s: %s - %s"
        ,request["issues"][startAt]["key"].as<String>()                 //working: BP-4349
        ,request["issues"][startAt]["fields"]["summary"].as<String>()   //broken? (garbage string)
        ,request["issues"][startAt]["self"].as<String>()                //broken? (garbage string)
    );

}

I don't know why some strings worked and some did not. I assume that the length of the string is the problem ?
How would you suggest I retrieve the longer strings ?
How do I know when the length dictates the use of .as<String>() vs something else?

Maybe it chokes on the escaped quotes (\") within the last string?

@EdgarBonet thanks for the thought. I tried removing the quotation marks (from the json result) this did not change the result.

Turns out there is a arduino json troubleshooter specifically for this type of issue here: https://arduinojson.org/v6/troubleshooter/  wow awesome. If you are having an similar issue I would start there.
This didn't fix my problem, for myself if I cast the types to const char * meaning
...snip...
const char* x = request["issues"][startAt]["self"].as<const char *>()
log_i("%s", x);
...snip...

this worked every time for every string


text:
SPI protocol with multiple devices
I need to write and read the measurements received by a sensor on an SD card. The card reading would be to display the data on a TFT screen. Specifically, I am using the 1.8-inch ST7735 screen. To use the card with Arduino I am using an SD card reader module (ANGEEK brand). Both devices work with SPI protocol.
To verify that this would be possible I make a test code. In it, two functions (measure_V and measure_I) simulate the voltage and current measurements. So what I do is call those two functions to get 10 measurements and save all of them to SD. Then I read them and display them on the screen. I show them both on the serial monitor and on the TFT screen. In order to map the values of V_data and I_data I use two functions that give me the maximum value in each measure. However, nothing appears either on the serial monitor or on the screen. The two devices share the MISO, MOSI, and SCK pins. Could someone help me with this? It is the first time that I use the SPI protocol with more than one device.
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SD.h>
#include <SPI.h>

#define TFT_CS 10
#define A0_pin 8
#define RST_pin 9

#define SD_CS 7                                              // CS pin of SD card connected to pin 7 of Arduino

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, A0_pin, RST_pin);

const uint8_t rotation=2;                                    // Origin of coordinates top left

float V_data[10], I_data[10];                                // Store voltage and current measurements

File V_points;
File I_points;

const uint16_t  Display_Color_Green = 0x07E0;                // Green color

int measure_V(int x){
  int voltage;
  voltage = x;
  return voltage;
}

int measure_I(int x){
  int current;
  current = pow(x, 2);
  return current;
}

int max_V(){
  int maxVal = 0;
  for (int i=0; i<sizeof(V_data)/sizeof(float); i++) {
    if (maxVal < V_data[i]) {
      maxVal= V_data[i];
    }
  }
  return maxVal;
}

int max_I(){
  int maxVal = 0;
  for (int i=0; i<sizeof(I_data)/sizeof(float); i++) {
    if (maxVal < I_data[i]) {
      maxVal= I_data[i];
    }
  }
  return maxVal;
}

void setup() {

  Serial.begin(9600);
  tft.initR(INITR_GREENTAB);                                                // Initialize a ST7735R chip, green tab
  tft.setSPISpeed(40000000);
  tft.setRotation(rotation);                                                // We set type of rotation
  tft.fillScreen(ST7735_BLACK);

  Serial.print("Initializing SD card...");

  if (!SD.begin(SD_CS))
  {
    Serial.println("SD initialization failed!");
    while (1) ;
  }
  Serial.println("SD initialization done.");
}

void loop() {

  int static n = 0;                                                              // Measurement number (initial measurement = 0)
  uint16_t pixelV, pixelI;

  // We perform and save on the memory card 10 measurements
  for(int i=0; i<=9; i++){
    V_points.print(measure_V(i));                                                // New voltage value
    I_points.print(measure_I(i));                                                // New current value
    }

  // We read the 10 measures of the card
  while (V_points.available() && I_points.available()){
    V_data[n] = V_points.parseFloat();                                           // Read voltage value from file
    I_data[n] = I_points.parseFloat();                                           // Read current value from file
    Serial.print("Voltage= ");
    Serial.print(V_data[n]);
    Serial.print(", ");
    Serial.print("Current= ");
    Serial.println(I_data[n]);
    pixelV = map(V_data[n], 0, max_V(), 0, 128);                                 // We map tension
    pixelI = map(I_data[n], 0, max_I(), 0, 160);                                 // We map current
    tft.drawPixel(pixelV, pixelI, Display_Color_Green);
    n++;
    }

}

Check the specific details of your sensors to check that they properly put the MISO pin into high-impedance when SS is pulled high.  See my answer to a similar question for a possible workaround.

it could be this problem: https://arduino.stackexchange.com/questions/36912/slave-spi-does-not-work/36915#36915

Thanks, I will take a look at what you have gone through and see if it fixes it.

You appear to be neither opening nor closing the files that you are attempting to write or read.
See this for an example of using an SD card: https://www.arduino.cc/en/Tutorial/LibraryExamples/ReadWrite


text:
Joystick reading erroneous values
Under normal operation, the value of a joystick's ADC range on my board is from 0 to 1023 (10-bits). However, my graph for either axis is not continuous. Rather, there is more than one min and maximum for both axis. I am running this thread on a MSP432P401R however the code isn't any different than an Arduino.
int jumpFlag;
int backwardsFlag;
int forwardsFlag;
int selPin = P5_1; //Select digital pin location
int xOutPin = A14;
int yOutPin = A13;

void setupPlayerActions() {
  pinMode(selPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(selPin),jumpISR,RISING);
  //pinMode(xOutPin, ); //Analog X pin setup
  //pinMode(xOutPin, ); //Analog Y pin setup
}

void jumpISR() {
  Serial.println("Jump Detected!");
  jumpFlag = 1;
}

void loopPlayerActions() {
  int x_adc_val, y_adc_val;
  int leftThreshold=50,rightThreshold=900;
  float x_volt, y_volt;
  x_adc_val = analogRead(xOutPin);
  y_adc_val = analogRead(yOutPin);
  x_volt = ( ( x_adc_val ));  /*Convert digital value to voltage */
  y_volt = ( ( y_adc_val));  /*Convert digital value to voltage */
  if (x_volt < leftThreshold){
    Serial.println("Move Backwards");
  }
  else if (x_volt < rightThreshold){
    Serial.println("Move Forwards");
  }
  Serial.println("X_Voltage = ");
  Serial.print(x_volt);
  Serial.print("\t");
  //Serial.print("Y_Voltage = ");
  //Serial.println(y_volt);
  delay(100);

  //delay(250);
}

The graph goes to zero for all positive x and y integers however it briefly reaches a maximum past a small value on the -x and -y axis then sinks to about ~420. What could be causing this?

Re “if (x_volt < rightThreshold)”: do you mean if (x_volt > rightThreshold)?

@EdgarBonet will not change the fact the graph of the potentiometer is not linear

Can you show the graph?

it could be a problem of analogRead implementation or the ADC itself. for example for AVR it is recommended to wait a little or do a dummy reading between consequent readings on the same ADC.

A 10 bit ADC may not have 10 bits of resolution for a given sample.  It might only have 5 or 6 bits due to random noise and other factors.  Consult the chip manufactures specifications / recommendations if you need a specific number.
What can be done?

If response time is not an issue, consider averaging the ADC reading.  A common coding practice is to use an exponential moving average.
Consider a better ADC.  Many times a dedicated ADC chip (not integrated into a processor) will have better specifications.

For more in depth reading this NXP (aka: Motorola, Freescale) application note discusses "How to Increase the Analog-to-Digital
Converter Accuracy in an Application".


text:
parseFloat() function
I have noticed that the parseFloat() function returns decimal numbers, but only up to 2 decimal places. Would it be possible for it to return the numbers with more decimal places? In case we need more precision

how did you get to that conclusion?

the parseFloat() function returns decimal numbers

No, it doesn't. It returns a binary (not decimal) floating point
number.

only up to 2 decimal places

The number returned by parseFloat() has 24 significant digits.
Binary digits, that is, also called “bits”. This is roughly equivalent
to 7 decimal digits.
That being said, beware of Serial.print(). This function converts
binary floating point numbers to decimal, and defaults to showing only
two digits after the radix point. You can ask for more:
Serial.println(x, 6);  // display x with 6 digits after the radix point.

If you want to gain some basic understanding of how floating point
numbers work, I recommend reading The Floating-Point Guide - What Every
Programmer Should Know About Floating-Point Arithmetic.

Thanks for the explanation, very educational!


text:
Adafruit feather helium integration
So I have an adafruit feather M0 LoRa 900 MHz and try to connect it to a helium hotspot (add to my helium console). For that I use the official helium documentation provided by helium and I get to the point of uploading the sketch to the board, but (as stated guide) if I open the serial monitor afterwards I only get an error message called: EV_JOIN_FAILED with a seemingly random number behind the error message. The output of the serial monitor looks like this:
22924969: EV_JOIN_FAILED
24125790: EV_JOIN_FAILED
25510651: EV_JOIN_FAILED
26731900: EV_JOIN_FAILED
28546725: EV_JOIN_FAILED
29506788: EV_JOIN_FAILED
30549623: EV_JOIN_FAILED
31955928: EV_JOIN_FAILED
33169043: EV_JOIN_FAILED
34528464: EV_JOIN_FAILED
36263160: EV_JOIN_FAILED
37424536: EV_JOIN_FAILED
38958548: EV_JOIN_FAILED
40127470: EV_JOIN_FAILED
40996827: EV_JOIN_FAILED

I made sure to edit the config file of LMIC and also triple checked that I entered the correct AppKey, Device EUI and App EUI into the test program.
My goal is to connect my adafruit feathe M0 to the helium console and send a Hello World packet and get developing.
Help would be apreciated.
Edit: Here is a screenshots of the adafruit feather M0 itself

Can you please include the number behind the error message? Does it change or does it stay the same? Did you make sure to attach antennas and flip the jumper as stated in the guide?

the number is always changing and I will include a an example of the output of the monitor in a minute. The antenna is properly installed and the jumper should be as well but I will include a photo of the board just in case.

Okay, the number that you see is the "timestamp" of the device or the ticks number. Your setup looks right. Could you please include the serial monitor output right after you flash? It should at least tell you it tried to join the network. Also, you've unlinked the guide you used - now it just points to the image of the board.

Okay, it´s good to know that the setup is right. I included the official helium documentation again, sorry for messing that up. The problem is that this is really the only output that the serial monitor displays. It doesn´t tell me that it tried to join the network or anything.

It might be also worth mentioning that, since I´m in the EU, I tried to modify the lmic config.h file to, instead of using the #define CFG_us915 1 line, use the #define CFG_eu868 1 line. That just gives me the following error while compiling:
'LMIC_selectSubBand' was not declared in this scope; did you mean 'LMIC_setupBand'?

Looking on GitHub, could you try commenting out that function? What happens when you do that?

I have the same issue!! I’m connecting to AU_915 so had to change frequency in the lorabase.h file. I can see the join attempt and the join accept on helium console, but my feather M0 doesn’t seem to hear the response. This means I get ‘EV_JOIN_FAILED’ over and over.


text:
Externally powering Arduino while reading voltage off it via USB
I have an Arduino UNO R3 where I’ve set Pin 13 to “HIGH” (as shown here) and I’ve connected an LED to Pin 13 and GND which glows brightly using a USB attached to my MacBook Air providing (I think) 5V.
Now, I’m powering the Arduino externally using a 3V (1.5+1.5) battery and the 5V/GND connection. The green light blinks showing the Arduino is being powered and the bulb glows since it’s the same circuit.
Now, I wish to connect the USB to the Arduino and basically read the voltage of the LED via Pin 13 and the GND connection. Of course, I could accomplish this by simply attaching a multimeter but that’s not the problem since it’s not the true aim of the project (which I can state if required but it’s more complicated and not too different).
But when I connect the USB the LED glows brighter and the voltage across it is around 3.5V (higher than what the battery is supplying). I want the computer to read the voltage of the battery and not supply the arduino with it’s own power. How do I accomplish this (note: I’m allowed to break certain circuitry on the Arduino but I’d prefer to do this as last resort)?
Basically, how do I read voltage readings on a computer off an arduino without powering the arduino i.e. How do I convert the USB port and my computer into a multimeter with the arduino?
(I'm very new to experimenting with this so may have made crushing mistakes. Any help is appreciated)

why do you want to do this? ... you can measure the battery voltage without using the battery to power the arduino ... otherwise, use an external USB serial adapter

When powering the Uno with 3V at its 5V input, then its underpowered. It might work (since the microcontroller on it is technically capable of working at 3V), but it might be unstable, especially when your batteries voltage goes lower while you are emptying them. And: Please explain what you want to learn from the voltage on the LED pin? It is mainly determined by the LEDs forward voltage and the resistor values in relation to the current supply voltage. And are you adding another LED to that pin? Since pin 13 already is connected to an LED you would need to also take that into account.

Pin 13 is a digital pin, it does not have the capability to read voltage. You need to use one of the analog pins to read voltage, they are prefixed with the letter "A" (A0 for example). You also need to note the Analog reference (maximum voltage reference point for the A/D) is the Arduino's +5 volt supply so if that changes so will the readings. You will get 0 with zero input and 1023 when the voltage matches the reference voltage. Note this voltage cannot exceed VCC by more than a very small amount (0.6V)or you will damage the Arduino. The USB supplies about 4.5 volts, depending on the protection circuit. If you power it via Vin with the appropriate voltage it will have nominally 5 volts and of course the ever changing battery voltage. All of these change your reference voltage changing your voltage measurement. The best solution is to power it externally and then connect the battery - to ground and the battery + to one of the A/D inputs. With a little math in your code you will have a voltmeter. There are many fine examples on line complete with code for the Arduino.


text:
Unable To Upload Source Code on Arduino UNO(Windows 11)
I was trying to upload the source code of a project to the Arduino UNO and this is the error that I keep on receiving.
After I closed and reopened it again, the Port option is gray. I tried everything (installing new drivers, uninstalling it) but nothing works. This board works on my PC (Win 10) but doesn't work on my laptop (Win 11).
avrdude: ser_open(): can't set com-state for "\\.\com3" an error occurred while uploading the sketch.

Is it a genuine Arduino UNO or a Chinese clone? If a clone, what USB chip does it have on the board?

@Majenko It's a Chinese clone with an Atmega328p chip

That's the MCU. What's the USB chip? Is it an ATMega16UI2 or a CH340G?

@Majenko It's Atmega16U2.


text:
Arduino battery capacity selection based on the current measurements
I'm sorry for this stupid question...
I'm not an electronic/electric expert..
In order to select the battery capacity as well as the solar panel I'm measuring the Arduino current consumption.
So, I connected my multimeter (in line) (I rotated the selector on 200mA) and I'm able to see the values that are:

around 85mA for  few seconds (around 8seconds) when the system works;
around 0.38 mA during the remaining 52 seconds when the system is in sleep mode.
I'll enable my system around 8s for each 15minutes (basically 4 times for hour)

In order to have a general idea, I would like to use a site like this https://www.digikey.it/en/resources/conversion-calculators/conversion-calculator-battery-life
Now, It's not clear for me how can I use the retrieved values:
Do I calculate the current consuming in 1h?
The values that I obtained are related to the current consumed for a second?
What I have to punt into the field "Device Consumption" on the linked web-site?

You have two current values and the approximate time those currents run for.  From that you can calculate the average current.
If you have 8 seconds "on" and (15*60-8) 892 seconds "off" that gives you:
(85 * 8) + (0.38 * 892)
------------------------
         900

Which comes out as 1.13mA on average at any point in time (that's a simple ratio calculation - the times don't matter, only the ratio between them).
Over the course of 1 hour you will consume around 1.13mA on average, which is 1.13mAh.
To run for 24 hours you will need 1.1324 = 27.2mAh. To run for a week it's 27.27 = 190mAh.
The calculations, as you can see, once you have the average current are pretty simple.
Of course you need to "derate" the results since batteries never hold the stated amount - that is both a "theoretical maximum" under ideal conditions, which degrades over time (as you will know when your phone battery starts dying too soon), plus you never run a battery completely flat.  Personally I like to double the capacity to err on the safe side.
You also know that you need to charge the batteries with at least an average of 1.13mA from your solar cells. That means working out what ratio of the time will be available for actual charging (daylight with good sun brightness) and calculating how much current you will need to generate during that time to allow the system to run in the dark.

How you obtained 1.13mA?
((85 * 8) + (0.38 * 892))/900 = 38.42
Do I missed some others calculation?

@Safari 858 = 680. 0.38892 = 338.96. 680+338.96 = 1018.96. 1018.96/900=1.13217...

:D :D :D Yeah! Sorry... wrong copy and paste :s


text:
Connecting various devices to Arduino
I need to connect the following devices to an Arduino UNO board. The problem is that I run out of pins to be able to connect them all. Is there any way to do it?

ultrasonic sensor
yellow led
green led
red led
buzzer
keypad 4x4

I'm doing the project in Tinkercad
In the picture below I tried to do it, but I am missing 2 pins for the ultrasonic sensor trig and echo

You can use the analog pins as digital input / output pins.

Another option would be one of these: https://www.instructables.com/PCF8574-GPIO-Extender-With-Arduino-and-NodeMCU/

As cguck70 already stated in the comments: The pins A0 to A5 can be analog input pins, but they can also be normal digital input/output pins. You can use them to your liking, just like any other digital input/output.
So just connect two of these pins to your ultrasonic sensor and use the pin names A0, A1 and so on in your code.


text:
Can't get input from 4x4 keyboard
I'd like to make some basic calculator. Currently, I'm struggling with inputs. I wanted to get from user some numerical input, then, I'd like to have an information, which type of calculation he is about to do. I'm not sure why, but I can't get any numerical input from user, because the program "jumps" ahead to the operation type. Here's some code:
void loop(){
int a = getNumber();

if(a != NO_KEY){
    do{
    operationType = getOperationType();
    }while(!operationType);
  }

}
getNumber
  int getNumber(){
  char userInput = customKeypad.getKey();
  int value;

  if (userInput == '0' || userInput == '1' || userInput == '2' || userInput == '3' || userInput == '4' || userInput == '5' ||
  userInput == '6' || userInput == '7' || userInput == '8' || userInput == '9'){
      value = userInput - '0';
      Serial.println("value");
      Serial.println(value);

    }
  return value;
  }

getOperationType
char getOperationType(){
char userInput = customKeypad.getKey();

  switch (userInput){

      case '+':
//      add(a , b);
        Serial.println("add");
        break;
      case '-':
//      subtract(a , b);
        Serial.println("subtract");
        break;
      case '*':
//      multiply(a , b);
        Serial.println("multiply");
        break;
      case '/':
//      divide(a , b);
        Serial.println("Divide");
        break;
      case 'C':
//      TODO
        break;
    }
    return userInput;
  }

Can I have any hint, why I can't just get simple inputs from the keyboard?

your program logic assumes that your program waits for a key to be pressed .... reduce your code to get keypress, print value of keypress ... that will show you what you are dealing with

You need to watch out for what you return and if your variables are initialized. So, what happens here:
In loop() you call getNumber(). There you declare two variables:

userInput, which you initialize to the return value of customKeypad.getKey(). So this variable will have the value NO_KEY if no key is pressed.
value, which you don't initialize. Thus its value is whatever was there in the variables memory space before it was allocated. This can be anything, but it is not random in most cases. It depends on what your program does prior to this, but you don't have any control over it.

Then you check for userInput being an ASCI digit. As you didn't press a key this obviously is false, so the variable value gets never written. And then you return that variable.
In loop() you check if the return value of getNumber() is unequal to NO_KEY. And since you didn't initialize value, it probably is. Thus the program goes directly to the operation type part.

What to do now?
First: Always initialize every variable that you declare in a function. Global variables get initialized implicitly, but not local variables. To be sure that I don't make an error, I just always initialize ALL my variables when declaring them.
Second: Currently value will not be NO_KEY since you don't assign that value to the variable. But doing so wouldn't fit with your program logic. value is the real numeric value, not the ASCI representation of it. And NO_KEY is defined in the Keypad library as \0 (the null character, with numeric value zero). So NO_KEY is actually equal to 0. And zero is also a valid input to your calculator.
Instead I would suggest returning -1 if no key was pressed and then in loop() checking for that. So something like this:
int getNumber(){
  char userInput = customKeypad.getKey();
  int value;

  if (userInput == '0' || userInput == '1' || userInput == '2' || userInput == '3' || userInput == '4' || userInput == '5' || userInput == '6' || userInput == '7' || userInput == '8' || userInput == '9'){
    value = userInput - '0';
    Serial.println("value");
    Serial.println(value);
  } else {
    return -1;
  }
  return value;
}

void loop(){
  int a = getNumber();

  if(a != -1){
    do{
      operationType = getOperationType();
    }while(!operationType);
  }
}

That said, I have some suggestions for you for going further:

For checking if the returned key is an ASCII digit there is actually a simple function for that: isDigit(). So instead of your chained equal conditions you can just use
  if(isDigit(userInput))

If you go on in this style you will find yourself wrapping multiple loops in one another as you need to loop for waiting on a keypress. That can get rather messy and it gets difficult to add additional functionality. Instead you could implement a Finite State Machine (FSM). Here the code in loop() consists mainly out of a switch case structure, where every case is one state of your program. For example you could have the states NUMBER1_INPUT, OPERATION_INPUT, NUMBER2_INPUT, DISPLAY_RESULT. The switch structure uses a single int variable as a state marker. For example when you set that state variable to NUMBER1_INPUT it will stay there and loop. When the user as done the number input you can change the state variable to OPERATION_INPUT and let it continue there. It is an important concept and it will change your way of Arduino coding for the better.
There are many resource for learning how to program a FSM. I've once written a longer answer about this, but you can search for something like "Finite State Machine" on this site or the web to find out more.

Thank you so much for such explanation. I will take a look on your answer about FSM. I really appreciate your effort.


text:
USB-C to USB-C cable Arduino is not responding even not powered by this cable
Hi I want to connect arduino NANO to my laptop with Type-C (USB-C) ports (on below image left side [4] and other side 3). Now I bought a USB-C to USB-C cable, because it appeared to be the right tool, but the Arduino is not even powered by this cable. if I use regular USB 3.2 Gen 2 Port (on below image [5]) everythings for fine. but this usb-c ports not recognize the Arduino NANO even NANO's power LED is not switching ON.
On the other hand If I plug in my phone to this usb-c cable it works both ports. It means that cable is working good. I have changed 2 times cable stil not responding.
On the docs, it look usb-c and regular usb 3.2 ports works same. But why usb-c ports not working with Arduino. also my laptop is MSI GS66

I'd appreciate if anyone has a solution or an idea to fix it. Thanks!

Maybe that port does only provide power if you draw enough power from it (like powerbanks often do). When the power LED isn't on but the Arduino works with a USB3 to USB-C cable from another port the problem is not with the Arduino. You can verify the absence of power by measuring the voltage between 5V and ground.

does Arduino Nano have a USB-C connector?

@jsotola https://urun.n11.com/arduino-urunleri-ve-setleri/type-c-cikisli-yeni-nesil-arduino-nano-type-c-kablo-hediyeli-P508671734

@jsotola Not the official Nanos, but there are many clones that do have USB-C.

@chrisl just because it has a USB-C connector, it does not mean that it has the circuitry to make it a USB-C interface

The pair of 5.1K resistors (CC1/CC2 pull-downs) seen in their product picture constitute the only extra circuitry a type C connector requires over the original  Nano's mini-B.  For C to C it's important that CC1/CC2 are doing their job because the negotiate the direction of the connection. For an A to C cable CC1 and CC2 and their resistors go unused. What I'm getting from this is that CC1/CC2 are failing to be pulled to GND, because one of the board/connector/jack are bad. If one (but not both) of the CC# lines are bad, rotating the cable 180 degrees would switch to the good CC#.

That Nano is not USB-C compliant. Yes, it has the connector, but it doesn't do all the required handshaking to put the USB-C port on the laptop into host (and provide power) mode. This is needed because those ports are also power inputs and have to be told to output power - otherwise plug in power to them and bang horrible things happen.
You have to use the larger USB 3.2 ports which are always power providers and never power consumers.

I understood. thanks. you mean if I use usb-c to usb-b converter cable arduino uno should work. or  usb-c to mini usb can work original nano.


text:
How do you deal with balancing the limited storage of Arduino with the decrease in speed if you just print everything as it gets measured?
I am working on a simple data acquisition system based on an Arduino Uno. Each run would ideally collect up to 10k data points (all doubles). Obviously, the Arduino doesn't have the capacity to hold all that at once. However, as one would expect, printing out the data as its being acquired significantly slows the process down (by about a factor of 7). I have looked around to find if there's a standard way to deal with this issue in the world of Arduinos, but have come up short. I come from a background where memory is never an issue, so I'm not as well versed in this side of things.
Obviously I don't expect perfection, but any insight or sources would be helpful.

Have you tried a higher baudrate? And transmitting binary data instead of ASCII text? Without code there isn't much else to say besides getting a microcontroller with more memory

I have maxed out the baud, but I'm unfamiliar with the idea of sending binary data instead of ASCII. I'll look that up. Is the idea there that it's sending bits rather than bytes?
And I was afraid you were going to say that last part.

it sounds like you need something newer/better than an Uno. I like the esp8266, even w/o wifi enabled.

You are still sending bytes. But 1 byte can hold a number between 0 to 255. If you want to send 255 in ASCII text you already need 3 bytes for that. Though I would second dandavis with that you will be way better off with a better microcontroller

This is all about choosing the right tool for the job.
At the moment you're trying to fit 50 clowns into a mini. While there are ways of doing it (by extending the "mini" outwards with extra "room") it's not what you'd normally do.
Instead you'd hire a coach.
If you have a scenario whereby you need to store more data than an Uno can store then you would typically use a different board with a more powerful chip.
There's plenty out there, many that are cheaper than the Uno...
If you desperately do want to use the Uno then:

Reduce your data size: consider using smaller variables, such as 16 bit integers and fixed point arithmetic instead of floating point values.
Improve your data transmission: send binary data instead of ASCII data, and increase your baud rate to the highest that can be reliably achieved
Consider adding external storage, such as an SPI SRAM chip or an SD card.

My solution is to use FRAM, it is much faster then printing and has almost unlimited read and write cycles. It is also non volatile so if power fails the data does not. They can be gotten I2C or SPI your preference. I purchased 32K x 8 devices for well under $6.00 last year from my favorite china supplier. You can treat it as one big ring buffer and print from it while you load data into it.

Don't use String and others dynamic allocated object in your code. There is not any reason for slow down serial output, only inefficient memory management.

What do you mean by your second sentence? Why exactly is there no reason that the Serial output slows things down?

I'm not actually using Strings, and all the variables I have are allocated in stack. I'm inclined to disagree with you that printing doesn't slow programs down; that's always been my experience.

Serial use ring input and output buffer. Its mean that you can output some count of characters to this buffer. If you send 10k double you overfill this buffer. Then you must wait for transfer chars by UART. Maybe this you consider as slow down printing. But transfer speed for serial line is baudrate/10 bytes per second (one char consist from 1 start bit, 8 data bits and one stop bit) This speed is guaranteed by hw UART and not change in time.

Si transferring over Serial does slow the code down, since it has to wait for the data to be actually send. Sorry, your answer doesn't make much sense to me in this context


text:
Powering LEDs with Arduino uno 5v
I'm working on the sound reactive led lamp as my first project and have slightly different materials to start with. First I'd like to simply learn to power the LED strip.
from https://www.youtube.com/watch?v=5oRir4dck_w
I'm attaching pictures so it's as simple as possible, but I'd like to confirm where to attach the wires on the uno and the basic logic behind how to get from the attempt I have now, to actually turning on the LEDs. Thanks so much!
(I think the images show up but please let me know if not)

A good question, best asked as you did before frying something. My Arduino rule #1 A power supply the Arduino is NOT! Connect the ground of the LED power supply to the ground of the arduino. Then connect the data line, as you have it in your picture. If you try to operate as it is in the picture the odds are high that you will fry the regulator on the Arduino depending on the output of the wall wart. You have a 5V power supply connected to the Vin connector, that does not work as it goes through the regulator and protection circuitry before getting to the processor. You need to power via the 5V pin with a 5V power supply. This can also be used to power your LEDs assuming they do not pull much over 1 amp. If you want to power by the connector, my preference, you need about 7.5 to 12 VDC. The additional filtering does not hurt and can only help. It also helps to protect from transients.

Thanks for taking the time to help me. So the vin is what it has built in and I need a different power supply module connected to the 5v pin?

Your 5V DC power supply should work on the +5V and power the arduino just fine. Be careful and do not connect backwards even for nanoseconds as there is no protection for that as there is on the Vin. An external DC power supply between 7.5V 12VDC will work. As you approach 12V and beyond on Vin the on board regulator will start getting hot, such things as Motors will overheat it. The protection circuit will allow you to power it externally while connected to the USB and your computer.


text:
Arduino create Json Array with double values and 2 decimal point
How i can create a Json Array with double values and 2 decimal point using the ArduinoJson Library?
https://arduinojson.org/v6/how-to/configure-the-serialization-of-floats/
In the folowing small example it is possible to write to the Json file a double value with 2 decimal point.
#include <ArduinoJson.h>

double round2(double value) {
  return (int)(value * 100 + 0.5) / 100.0;
}

double round3(double value) {
  return (int)(value * 1000 + 0.5) / 1000.0;
}

double var1 = 1.23456789;
double var2 = 5.05599991;

void setup() {
  Serial.begin(115200);

  StaticJsonDocument<200> doc;
  doc["hello"] = "world";
  doc["var1"] = round2(var1);
  doc["var2"] = round3(var2);

  serializeJsonPretty(doc, Serial);

}

In my sketch right now i am able to create the Json Array with the values read from a Analog input. Only the created Json Array have 9 decimal points. I do not know how to implement in my sketch, folowing the aboth example that the values inside the Json array have only two decimal points.
Follow my sketch.
#include <ArduinoJson.h>

#define ADC_Range_Pin  35  // Pin Range Sensor

unsigned long scale_previousMillis = 0;
const long scale_interval = 100; // Interval
const byte NUM_SAMPLES = 20;
double buffer_range [NUM_SAMPLES];

// Range Sensor Instanzen-----------------------------
double Current_range = 0; //4-20 mA
double rawADCValue_range = 0;
double ADCVoltage_range = 0; //0-3,3 V
double range = 0; //0-50mm
unsigned long range_t;

double mapfloat(double x, double in_min, double in_max, double out_min, double out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

double round_range(double value) {
  return (int)(value * 100 + 0.5) / 100.0;
}

void Read_Scale() {

  StaticJsonDocument<1000> doc;

  static int scale_counter = 0;

  if (millis() - scale_previousMillis >= scale_interval) {
    scale_previousMillis = millis();

    rawADCValue_range = 0;
    for (int i = 0; i < 100; ) {
      if (millis() - range_t  >= 1) {
        rawADCValue_range += analogRead(ADC_Range_Pin);
        i++;
        range_t = millis();
      }
    }

    ADCVoltage_range = (double)(rawADCValue_range / 100.0) * (3.3 / 4095.0);
    Current_range = mapfloat(ADCVoltage_range, 0.8, 3.3, 4, 20);
    range = mapfloat(Current_range, 4, 20, 0, 50);

    buffer_range[scale_counter] = range ;

    scale_counter ++;

    JsonArray rangeValues = doc.createNestedArray("Range");

    if (scale_counter >= NUM_SAMPLES)
    {
      for (int i = 0; i < NUM_SAMPLES; i++) {
        rangeValues.add (buffer_range[i]);
      }

      serializeJson(doc, Serial);
      Serial.println();
      scale_counter = 0;
      Serial.println();

    }
  }
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  Read_Scale();
}

You defined the rounding function round_range(), but never used it.
You want to round the numbers that you are putting into the array within
the JSON document:
rangeValues.add(round_range(buffer_range[i]));


text:
FastLED changing colour at holding state
Basically make a code to guide users through a box breathing exercise (breath in for 4 seconds, hold for 4, release for 4, hold again for 4, repeat) to help relax them.
Right now my code is running APA102's. They're running through 5 "breathing" states; In, ChangingToOut, Out, ChangingToIn, Rest.
My LEDs are just fading in and out in an aqua/green colour.
What I would like to do is to change the colour at every BREATH_HOLD_DELAY. I want the LED display to be easier to follow for people doing the breathing exercise. Right now It's difficult to tell when the "hold breath" part is when the LEDs are at full brightness. I would like the LEDs to fade in green, immediately switch to blue for the 4-second BREATH_HOLD_DELAY, and then immediately switch back to green to fade out and hold at low brightness for 4.
I'm really lost as to how to do this. I've tried doing an "if" statement;

if (BREATH_HOLD_DELAY)

leds[i] = CHSV(HUE2, 255, brightness);

But that just changed the entire LEDs light fade to blue, rather than just the BREATH_HOLD_DELAY parts.
Here's my entire code!
#include <Servo.h>

#define DATA 11                 // Data connected to Digital Pin 11 on the Arduino
#define CLOCK 13                // Clock connected to Digital Pin 13 on the Arduino
#define SERVO_PIN 9              // Pin that the servo is connected to
#define LED_TYPE APA102         // This LED strip uses the APA102 chipset.
#define NUM_LEDS 45             // There are 25 LEDs on this strand
#define HUE 65                  // The colour of the LED's
#define HUE2 10                  // The colour of the LED's
#define LOOP_DELAY 20          // in Milliseconds
#define BREATH_HOLD_DELAY 3000
#define SERVO_INITAL_POSITION 0  // define the initial position value to 0

enum breathingStates { In, ChangingToOut, Out, ChangingToIn, Rest };

//Global Variables
CRGB leds[NUM_LEDS];            // the array of LEDs          assigning one after the other
Servo myservo;  // create servo object to control a servo

/*====================================================================
  setup(): will run only once
=====================================================================*/

void setup() {
  Serial.begin(115200);
  LEDS.addLeds<LED_TYPE, DATA, CLOCK, RGB>(leds, NUM_LEDS);
  FastLED.clear();
  FastLED.show();
  myservo.attach(SERVO_PIN);
  myservo.write(SERVO_INITAL_POSITION); // Initial position of the servo
}

/*====================================================================
  loop(): will run indefinitely
=====================================================================*/

void loop() {
  static int8_t theta = 0;
  static breathingStates breathingState = Rest;

  switch(breathingState)
  {
      case Rest:
        Serial.println("This is the first time the loop has run");
        // Do any further setup not done in setup function here, but this is redundant
        breathingState = In;
        break;

      case In:
        theta++;
        if(theta >= 90){
          breathingState = ChangingToOut;
        }
        break;

      case ChangingToOut:
        delay(BREATH_HOLD_DELAY);
        breathingState = Out;
        theta--;
        break;

      case Out :
        theta--;
        if(theta <= -90){
          breathingState = ChangingToIn;
        }
        break;

      case ChangingToIn:
        delay(BREATH_HOLD_DELAY);
        breathingState = In;
        theta++;
        break;

      default:
        Serial.println("It should never have come to this... :(");
  }

  // Now that theta is set, we do somethign with it in this section of the loop() function

  //Serial.print("The value of theta is: "); Serial.println(theta);

  float thetaInRadians = float(theta) / 57.295;
  double dblBrightness = sin(thetaInRadians);      // LED brightness
  uint8_t brightness = (dblBrightness * 127) + 128;
  Serial.print("The value of brightness is: "); Serial.println(brightness);

  //Set the  hue and brightness of each LED
  for (int i=0; i < NUM_LEDS; i++){
    leds[i] = CHSV(HUE + i, 255, brightness);  // Set the colour and brightness of the LEDs

  }

  //Show the next frame of the LED animation
  FastLED.show();

  myservo.write(theta + 180);

  delay(LOOP_DELAY);

} ```

Would love any help or guidance. I'm very new to coding and Arduino!

Is it intentional that the color of the LEDs is slightly different? Or should they all have the same color at a certain point in time?

All the same colour ideally when the LEDs are holding for 4 seconds at full brightness! I think that's the BREATH_HOLD_DELAY section

Your color scheme seems weird, float thetaInRadians = float(theta) / 57.295; uses an angle (from a HSV color scheme?) and then converts that into a brighness. The brighness however is the second parameter in a HSV, which you apparently want to control separately. I would change the switch statement such that in every step, the desired color/brighness is selected and then, in a separate step, you fade to that. That way, you can control the desired target color/brighness independently of how fast the colors change.

is it possible to put something like if (brightness = >255) and change the colour that way? Tell the code that when it hits full brightness it needs to be blue instead of green?

Sure, it's all software. You can do whatever you like.


text:
Round to first significant digit
I want to round a decimal number (x), but I need to do it differently depending on how it is. If it has integer significant digits, we round to the nearest integer, and if not, we round to the first significant digit. So the following would happen with these example numbers: 11.871->12, 11.177->11, 37.233->37, 37.779->38, 0.578->0.6, 0.544->0.5, 0.0257->0.03, 0.0223->0.02... (The numbers could have more or less decimal places than in the examples).
To implement this, I have created a function (type) in which we check if the most significant digit is of type integer or decimal. This function returns this characteristic of the number in the form of a "string". So if the most significant digit is an integer we just use the "round()" function. However, I don't know how to round a number to the first significant digit (roundto_fsd() function). Does anyone know of any function capable of doing this or any method to do it?
float x;

char type(float number) {
  char type[8];
  if (int(number) != 0) {
    type = "integer";
  } else {
    type = "decimal";
  }
  return type;
}

float roundto_fsd(float number) {}

void setup() {
  Serial.begin(9600);
  if (!type(x).compareTo("integer")) {
    Serial.println(round(x));
  } else if (!type(x).compareTo("decimal")) {
    Serial.println(roundto_fsd(x));
  }
}

void loop() {}

First of all, let me clarify that there is nothing “decimal” in a
float: a float is a binary (not decimal) floating point number.
The Serial.println() function does a binary-to-decimal conversion for
the purpose of representing the number as human-readable text. If you
want a specific number of decimal digits after the radix point, you
should ask Serial.println() to provide them. This is done by passing
this number as a second parameter:
Serial.println(sqrt(2));    // prints "1.41" (2 decimals by default)
Serial.println(sqrt(2), 0); // prints "1"
Serial.println(sqrt(2), 5); // prints "1.41421"

Now the question is: how to compute the number of required digits after
the radix point? This depends on how big the float is. If it is
smaller than 1 but larger or equal to 0.1, you want just one digit. If
it is ten times smaller than that, you want to digits, and so on:
numbers      digits
───────────────────
[1, +∞)        0
[0.1, 1)       1
[0.01, 0.1)    2
[0.001, 0.01)  3

I suggest repeatedly multiplying your float by 10 until it gets ≥ 1,
and count the number of times you had to do so:
/* How many decimal places to print. */
int decimal_places(float x)
{
    int i = 0;
    while (x < 1) {
        x *= 10;
        i++;
    }
    return i;
}

You would use this function like this:
Serial.println(x, decimal_places(x));

Note that there is a small issue with this approach. If you try to print
0.97, decimal_places() will say you need one decimal, and
Serial.println() will print “1.0”. If you would rather have it print
“1”, then change the loop condition within decimal_places() to:
while (x < 0.95)

Caveat: All this assumes that the numbers you want to print are all
strictly larger than zero. Otherwise decimal_places() would have an
infinite loop.

Thank you! Is using the "while(x<0.95)" condition because Serial.print() rounds?

@Libegria: It's because Serial.print() rounds to nearest, meaning 0.97 would be rounded up to 1.0, but 0.93 would be rounded down to 0.9.


text:
Generalize webserver routing
I'm following the examples for ESP32:
  AsyncWebServer _server(80);

  _server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
  {
    request->send(SPIFFS, "/index.html", String(), false);
  });

  _server.on("/css/index.css", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/css/index.css", "text/css");
  });

  _server.onNotFound([](AsyncWebServerRequest *request){
    request->send(404);
  });

_server.begin();

With this approach I have to know in advance each file I store in the SPIFFS and add a handler for each one.
Is there a more elegant way to automatically serve any file that exists in the flash?

You can tell the webserver to serve the static content from a specific folder:
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");

In this case it serves on the root URL the content from the SPIFFS root. So if I place a file called image.jpg in the SPIFFS root it will be served at /image.jpg.
For more information you can look at the corresponding section of the libraries Readme file.

What does static actually mean in this specific context?

In this case it means files that are placed in SPIFFS (aka flash). These files can of course also be written and thus deliver a more dynamic content. But then you should mind the limited write cycles of flash memory. So its mainly meant for the static (not changing) files of your website, but can also be used to serve changing files. In one of my projects I use it to serve a log file of relatively rare events


text:
How often does a mpu6050 gyro sonsor need calibration?
I want to use it in my real car for daily use to measure yaw angle when needed.
Is is ok to only calibrate it once at first then use it every day when driving without any problem? if not, how often should I recalibrate it?

Sorry for asking, but many 1st time posters get accelerometer, gyroscope and magnetometer mixed up. It depends on the manufacture.  But many accelerometers and gyroscopes work with only a small amount of calibration if any.  And I can not think of a good reason to calibrate them a second time.  A magnetometer needs calibration the 1st time and every time afterwards should conditions change.  And magnetometers do not work well near metal objects.  Like cars. (BTW, a MPU6050 has an accelerometer and gyroscope but no magnetometer.)

Most accelerometers and gyroscopes need little if any calibration.  Consult the manufactures specification sheets.  If any calibration is made and correction values found, then it is assumed those values may be used in the future for the same accelerometer / gyroscope.
This analog.com document goes into gyroscope calibration details.
Deriving the angle of the car (the "yaw") at any given moment will likely be problematic.  Errors from integrating the gyroscope's axis which is perpendicular to the ground will accumulate over time.  Which is the main problem when using dead reckoning.
Consider using a magnetometer & accelerometer along with the gyroscope in order to mitigate the accumulated errors from only using the gyroscope.

I just want it to find the 45 angle when parallel park. when car is fixed to adjacent car, reset it to zero then go reverse to reach 45 degree. I reset sensor's current position by a button as zero position.  Is it wrong? what is your idea?

The longer the interval of time over which a maneuver is tracked the more likely errors will creep into your calculations. You will have to be the judge as to how much error your application can tolerate and what is a reasonable amount of time for you to make the maneuver.  My ideas deal with longer car trips and integrating a tilt compass to aid in correcting any accumulated gyroscope errors. I don't think that is necessary for this case.

I don't want to use compass in my car anyway. because it needs calibration every time I want to parallel park. The time for reaching a 45 angle in parallel park is about 10 seconds or less. At that moment the sensor's work is finished. The sensor is going to be used once a day by average.

Excuse me, a micro question! Can I reset the sensor (x, y, z) to (0, 0, 0) logically using code (not calibrate)? because calibration takes much time.

Most gyroscopes are zero at rest and fluctuate when rotated.  It is normally up to the hosting processor to translate that into an angle.  Some gyroscopes can be written to to adjust / calibrate the gyroscope output.  But these values can be kept as part of the hosting processors program so that raw un-calibrated values are read from the gyroscope.


text:
Can't make attachInterrupt() work
I have an accel+gyro sensor connected to an Arduino Zero. It's configured to output an interrupt signal on pin 2 when tapped. I can do a digitalRead() on the pin, and it does go high, so the interrupt from the sensor is triggering as expected.
However, when I try to attachInterrupt() to that pin, so I can update a Boolean variable to use later in the code, it doesn't work; the boolean variable never updates.
Am I doing something wrong in the code, or is it a hardware issue? Thank you for your help.
byte int2 = 2;
int int2_val;
volatile boolean tapcheck = false;

void interrupt_setup() {
  // set up the sensor to fire interrupts
  // ...

  pinMode(int2, INPUT);

  // attach an interrupt on pin 2
  attachInterrupt(digitalPinToInterrupt(int2), tapdummyf, RISING);
}

// double tap ISR function
void tapdummyf () {
  tapcheck = !tapcheck;
}

void interrupt_test() {
  int2_val = digitalRead(int2);
  if (int2_val == 1) {
    SerialUSB.println ("interrupt triggered ");
    int2_val = 0;
  }
}

void loop(void) {
// in loop
  interrupt_test();
    if (tapcheck){
          SerialUSB.println("dt1");
    }
}

Pin 2 has been known to be iffy in the past (see https://forum.arduino.cc/t/zero-attachinterrupt/331384). Try using a different pin

@Majenko that was indeed the issue, wow go figure. Thank you :)

Pin 2 on Arduino M0 is the only pin on headers which doesn't support external interrupt because it is mapped to SAMD21G pin PA08 which is the only pin of SAMD which can't be multiplexed as external interrupt (because it is the only pin which supports NMI).
On Arduino Zero SAMD pin PA08 is mapped to headers pin 4, which is a better choice for a board in Uno format since on Uno only pins 2 and 3 support external interrupt. Maybe there was originally an idea that NMI (non-maskable interrupt) is an even better external interrupt.
Function attachInterrupt requires a pin which support external interrupt.
It looks like you have an Arduino M0 board, not Arduino Zero.

You should use an external pulldown resistor on your input pin, 10K would probably be ideal, tapcheck will only be true on alternate interrupts as you're toggling it.

Thank you. Issue was pin 2 iffy with interrupts.