text:
Why when I try to connect my ESP8266 to my node sever in my localhost it keep getting disconnect and connect?
I think the issue is within the library because I have try to implement this code according to the tutorial that I found in YouTube Youtube. The discussion of this tutorial is the first they implement the node js server for listening to specific event from socket io, second part they build a simple iOS application using swift to control an RGB light on the ESP8266 and the last part they make ESP8266 to listen to the event that have payload as RGB values. However, in my implementation, I use angular web application to control ON-OFF light on the Arduino but the problem when I try to listen to event that on and off, my ESP8266 don't connect to my server and print all of that message on the serial.
Here is the code for my ESP8266 to connect to my node server.

#include <SocketIoClient.h>
#include<ESP8266WiFi.h>
#include<Arduino.h>
#define USER_SERIAL Serial

SocketIoClient socket;
const char* ssid = "bunvath_guest";
const char* pass = "*************";
void setup() {
  USER_SERIAL.begin(115200);
  searchWifi();
  initWiFi();
  socket.on("message", handleMessage);
  socket.on("light_on",handleMessage);
  socket.emit("message","hello from esp");
  socket.begin("192.168.0.102",3000);
}

void loop() {
  socket.loop();
}
void handleMessage(const char* message, size_t length){
  USER_SERIAL.println(message);
}

  void initWiFi(){
      WiFi.mode(WIFI_STA);
      WiFi.hostname("ESP-host");
      WiFi.setPhyMode(WIFI_PHY_MODE_11G);
      WiFi.enableInsecureWEP(true);
      WiFi.begin(ssid,pass);
      while(WiFi.status() != WL_CONNECTED){
        USER_SERIAL.print(".");
        delay(1000);
      }
      USER_SERIAL.print("");
      USER_SERIAL.println("WiFi connected");
      USER_SERIAL.print("IP Address: ");
      USER_SERIAL.println(WiFi.localIP());
      WiFi.setAutoReconnect(true);
      WiFi.persistent(true);

  }
 void searchWifi(){
  int numberOfNetwork = WiFi.scanNetworks();
  USER_SERIAL.println("-----");
  for ( int i = 0; i< numberOfNetwork;i++){
    USER_SERIAL.print("Network name: ");
    USER_SERIAL.println(WiFi.SSID(i));
    USER_SERIAL.print("Signal Strength: ");
    USER_SERIAL.println(WiFi.RSSI(i));
    USER_SERIAL.println("-------------");
  }
}

Here is my node server code for receiving all connection from client and print the client id when new client is connecting. Moreover, this node server will listen to all the event that client emit and broadcast to other client.

var port = process.env.PORT||3000
const http = require('http')
const app = require('./app')

const cors = require('cors');
let message = ''
const server = http.createServer(app)
const io = require('socket.io')(server,{cors:{
    origin:'http://localhost:4200',
    credentials: true
}}
    )

server.listen(port,()=>{
    console.log("server run on ", port)
})

io.on("connection",(socket)=>{
    console.log(socket.id)
    socket.on('message', data =>{
        // console.log(data)
        socket.broadcast.emit('message',data)
    })
    socket.on('open_light',data=>{
        socket.broadcast.emit('open_light',data)
        console.log(data)
    })

})

Here is the message that I got from serial monitor, I feel like my Arduino has already connected to my server but it keep getting reconnect. Moreover, in my sever I did not see any new client connect to server so I am really what going on with this. Plus, I am sure that my node server is working perfectly fine because I have implement angular web application to emit event, and I saw that event printing in server.
12:57:13.083 -> Network name: Meas Nakry
12:57:13.083 -> Signal Strength: -85
12:57:13.083 -> -------------
12:57:13.083 -> Network name: bunvath_guest
12:57:13.083 -> Signal Strength: -57
12:57:13.083 -> -------------
12:57:13.083 -> Network name: BLaNKxD
12:57:13.083 -> Signal Strength: -89
12:57:13.121 -> -------------
12:57:13.121 -> Network name: Tuy vanny1
12:57:13.121 -> Signal Strength: -85
12:57:13.121 -> -------------
12:57:13.121 -> ....WiFi connected
12:57:17.165 -> IP Address: 192.168.0.100
12:57:17.165 -> [SIoC] add packet 42["message",hello from esp]
12:57:17.269 -> [SIoC] Disconnected!
12:57:17.269 -> [SIoC] event disconnected not found. 2 events available
12:57:17.787 -> [SIoC] Disconnected!
12:57:17.787 -> [SIoC] event disconnected not found. 2 events available
12:57:18.376 -> [SIoC] Disconnected!
12:57:18.376 -> [SIoC] event disconnected not found. 2 events available
12:57:18.992 -> [SIoC] Disconnected!
12:57:18.992 -> [SIoC] event disconnected not found. 2 events available
12:57:19.633 -> [SIoC] Disconnected!
12:57:19.633 -> [SIoC] event disconnected not found. 2 events available
12:57:20.217 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:20.217 -> [SIoC] packet "42["message",hello from esp]" emitted
12:57:20.251 -> [SIoC] Disconnected!
12:57:20.251 -> [SIoC] event disconnected not found. 2 events available
12:57:20.771 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:20.771 -> [SIoC] Disconnected!
12:57:20.771 -> [SIoC] event disconnected not found. 2 events available
12:57:21.435 -> [SIoC] Disconnected!
12:57:21.435 -> [SIoC] event disconnected not found. 2 events available
12:57:22.044 -> [SIoC] Disconnected!
12:57:22.044 -> [SIoC] event disconnected not found. 2 events available
12:57:22.596 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:22.596 -> [SIoC] Disconnected!
12:57:22.596 -> [SIoC] event disconnected not found. 2 events available
12:57:23.178 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:23.178 -> [SIoC] Disconnected!
12:57:23.178 -> [SIoC] event disconnected not found. 2 events available
12:57:23.798 -> [SIoC] Disconnected!
12:57:23.798 -> [SIoC] event disconnected not found. 2 events available
12:57:24.403 -> [SIoC] Disconnected!
12:57:24.403 -> [SIoC] event disconnected not found. 2 events available
12:57:24.945 -> [SIoC] Disconnected!
12:57:24.945 -> [SIoC] event disconnected not found. 2 events available
12:57:25.533 -> [SIoC] Disconnected!
12:57:25.533 -> [SIoC] event disconnected not found. 2 events available
12:57:26.201 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:26.201 -> [SIoC] Disconnected!
12:57:26.201 -> [SIoC] event disconnected not found. 2 events available
12:57:26.792 -> [SIoC] Disconnected!
12:57:26.792 -> [SIoC] event disconnected not found. 2 events available
12:57:27.380 -> [SIoC] Disconnected!
12:57:27.380 -> [SIoC] event disconnected not found. 2 events available
12:57:27.894 -> [SIoC] Disconnected!
12:57:27.894 -> [SIoC] event disconnected not found. 2 events available
12:57:28.711 -> [SIoC] Disconnected!
12:57:28.711 -> [SIoC] event disconnected not found. 2 events available
12:57:29.426 -> [SIoC] Disconnected!
12:57:29.426 -> [SIoC] event disconnected not found. 2 events available
12:57:30.131 -> [SIoC] Disconnected!
12:57:30.131 -> [SIoC] event disconnected not found. 2 events available
12:57:30.655 -> [SIoC] Disconnected!
12:57:30.655 -> [SIoC] event disconnected not found. 2 events available
12:57:31.254 -> [SIoC] Disconnected!
12:57:31.254 -> [SIoC] event disconnected not found. 2 events available
12:57:31.787 -> [SIoC] Disconnected!
12:57:31.787 -> [SIoC] event disconnected not found. 2 events available
12:57:32.375 -> [SIoC] Disconnected!
12:57:32.375 -> [SIoC] event disconnected not found. 2 events available
12:57:33.171 -> [SIoC] Disconnected!
12:57:33.171 -> [SIoC] event disconnected not found. 2 events available
12:57:33.731 -> [SIoC] Disconnected!
12:57:33.731 -> [SIoC] event disconnected not found. 2 events available
12:57:34.435 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:34.435 -> [SIoC] Disconnected!
12:57:34.435 -> [SIoC] event disconnected not found. 2 events available
12:57:34.978 -> [SIoC] Connected to url: /socket.io/?transport=websocket
12:57:34.978 -> [SIoC] Disconnected!
12:57:34.978 -> [SIoC] event disconnected not found. 2 events available
12:57:35.581 -> [SIoC] Disconnected!
12:57:35.581 -> [SIoC] event disconnected not found. 2 events available
12:57:36.180 -> [SIoC] Disconnected!
12:57:36.180 -> [SIoC] event disconnected not found. 2 events available

Hope anyone can find what is the issue in these codes, I am really frustrated about this for 3 days already.

I think you need to allow all origins, at least to begin with. At the moment, only connections coming from the machine running node can access the sever.
Removing credentials as a next step, which I can't see being used, may also move your testing along.
const io = require('socket.io')(server,{cors:{
    origin:'*:*',
    credentials: true
}}


text:
Arduino Nano skips statements after Interrupt
I am using an Arduino to control an AC Phase Control Circuit to control some lamps.
The problem is that the interrupts seem to break the code inside the loop().
This Code should just blink one lamp. But it doesnt!
What I found out so far:
The Led always has dim_level[22] so it seems like (at least the first) delay in the loop is skipped.
The strange thing:
When i add a statement that takes some time between the delays everything is working
For example
void loop() {
  CH[0] = dim_level[0];
  Serial.println("---------------------------------------------------------");
  delay(500);
  CH[0] = dim_level[22];
  Serial.println("---------------------------------------------------------");
  delay(500);
}

The not working code:
#include <TimerOne.h>

unsigned char channel_1 = 7;    // Output to Opto Triac pin, channel 1
unsigned char channel_2 = 6;    // Output to Opto Triac pin, channel 2
unsigned char channel_3 = 5;    // Output to Opto Triac pin, channel 3
unsigned char channel_4 = 4;    // Output to Opto Triac pin, channel 4
unsigned char CH1, CH2, CH3, CH4;
unsigned char i = 0;
unsigned char delay_time = 1;   // delay ms or flashing SPEED
unsigned char clock_tick;        // variable for Timer1
unsigned char CHANNEL_SELECT;    // variable for channel select

unsigned char CH[] = {CH1, CH2, CH3, CH4};

unsigned char dim_level[] = {5, 8, 10, 12, 15, 18, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75, 80, 82, 85, 88, 92, 95}; // don't use this massive for 60Hz
// create new massive for 60Hz
void setup() {
  Serial.begin(2000000);
  pinMode(channel_1, OUTPUT);// Set AC Load pin as output
  pinMode(channel_2, OUTPUT);// Set AC Load pin as output
  pinMode(channel_3, OUTPUT);// Set AC Load pin as output
  pinMode(channel_4, OUTPUT);// Set AC Load pin as output
  attachInterrupt(1, zero_crosss_int, RISING);
  Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz;
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here

}

void timerIsr()
{
  clock_tick++;
  if (CH[0] == clock_tick)
  {

    digitalWrite(channel_1, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_1, LOW);    // triac Off
  }

  if (CH[1] == clock_tick)
  {
    digitalWrite(channel_2, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_2, LOW);    // triac Off
  }

  if (CH[2] == clock_tick)
  {
    digitalWrite(channel_3, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_3, LOW);    // triac Off
  }

  if (CH[3] == clock_tick)
  {
    digitalWrite(channel_4, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_4, LOW);    // triac Off
  }
}

void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  clock_tick = 0;
}

void loop() {
  CH[0] = dim_level[0];

  delay(500);
  CH[0] = dim_level[22];

  delay(500);
}

Im new to arduino maybeIi miss some concepts but I read that interupts should not break delays outside interrupt

volatile qualify CH.

I don't know whether or not it's appropriate to mark as as duplicate for this, but have a look at this question and the answer given there.  If that makes things work, then maybe it makes sense.

@timemage yes thats is - thank you. you want to post an answer?

Like timemage mentioned i had to qualify ch as volatile.
so:
volatile unsigned char CH[] = {CH1, CH2, CH3, CH4};

is the fix

source: Stack Exchange

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

sort: votes


text:
Arduino parsing of a string using sscanf
Hello I am new to Arduino and C programming.
I wanted to parse string using sscanf fuction
This is my Program
String hith;
int field1,field2;
float field3;
int F1=0,F2=0;
float F3=0;
int h1,h3;
float h2;

void setup() {

  Serial.begin(9600);

}

void loop() {
  field1=5;
  field2=6;
  field3=56.67;
  F1=field1;
  F2=field2;
  F3=field3;

  hith =hith+F1+","+F3+","+F2;
  Serial.println(hith);

sscanf(hith.c_str(),"%d,%f,%d",&h1,&h2,&h3);

Serial.println(h1);
Serial.println(h2);
Serial.println(h3);
  hith="";

  delay(1000);
}

I am only able to Parse Integer values but not Floating points.

%f is not implemented in the Arduino world.

On 8-bit Arduinos support for %f from printf and scanf (and related functions) has been removed to save space.
Instead you should look at parsing the string into chunks with strtok() and use atof() to convert relevant chunks to floating point.

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


text:
How to reduce AnalogRead noise?
Currently trying to read off values from a photodiode through analogread. It's constantly so noisy and I thought it might be something wrong with my low-pass filter, but I decided to just connect a 1.5V battery to an analog pin and had just as much noise (upwards of 10mV oscillations). Is there a way around all of this noise? Because this makes the collected data unusable for my project.

Code to read off analog values:
int diodePin = A0;
int sensorValue = 0;
int sensorVoltage = 0;

void setup() {

  Serial.begin(57600);

}

void loop() {

sensorValue = analogRead(diodePin);
sensorVoltage = sensorValue*(5000/1024);
Serial.println(sensorVoltage);
delay(10);

}

Without a schematic it'll be impossible to help, although it may be more relevant on the electronics SE. 0.01V out of 3.3V/5V doesn't sound that bad, but it depends on context and hardware.

are the readings noisy if the sensor is exposed to sunlight only?

no. noisy readings at all times. as i said, even if I literally just try to read the voltage of a AA battery off of an analog input, it doesn't give me a smooth reading at all.

sure: take 3 readings, sort, keep only the middle one.

I need continuous good readings so that I can perform a Fourier transform on the collected data

Please post the schematic, not a frizzy thing. Your question is a tough one and without being there the next best thing is the schematic you drew as you wired it. Links to technical information on the hardware devices makes it easier for all of us. At this point all we can do is guess.

Just to make sure I understand: you're putting 1.5V into an analog pin (5V reads 1024, so 1.5V would be ~307), it's a 10-bit ADC so ~5mV with the default analog reference. You're seeing values from 306-308. What are you using to power the Arduino? Have you tried using a different reference or a stable AREF input? Have you checked things like [this] (https://forum.arduino.cc/t/help-with-weird-analog-input-problem-unstable-analog-reference/82011)? Without a solid reference voltage this still doesn't seem that unusual. Analog had a lot of moving parts.

Per your frizzy thing you should get zero as the Arduino does not have any power and the A+ and Ground are connected together on the + terminal. Posting a schematic would help a lot, Dave Newton suggested that a few days ago.

I always do two things for when "reading" analog data with an Arduino.

Measuring the voltage supply of the arduino board through its internal reference and calibrating with another 'good" voltmeter ("4 1/2" digits-20000 points or "3 3/4" digits-6000 points). ( Usefull link  https://www.instructables.com/Secret-Arduino-Voltmeter/ )

Sampling more analog datas to calculate a "mean" ... This can remove some "noise" and add "some bits". 16 samples would add "4" bits at your "readings". Of course, the global sample rate will be lower.

Don't forget, ground star of wires !!!

Keep in mind that averaging samples will increase the resolution but might not improve accuracy. Only random noise can be "averaged out"...systemic inaccuracy will remain.

Right. Only in the case if "linearity" is better than 1/16 LSB min ... which is very "rare". Some cases of 1/4 LSB of very good converters.


text:
Custom library for Arduino to encode and decode JSON Web Tokens
So I have been recently been trying to create a library for Arduino to encode and decode JSON Web tokens(JWT) using HMAC-SHA256.
For those unfamiliar, JWT has 3 parts - The header, body and signature. The header and body are in JSON format.
The header contains the hashing algorithm and token type while The body contains the data to be transmitted.
The header and body are converted to base64 format and arranged as "[header].[body]". The signature is created by running the hashing algorithm (HMAC-SHA256 in my case) on the "[header].[body]" and converting the result to base64 format.
Finally, the token is arranged as "[header].[body].[signature]"
More information can be found on - https://jwt.io/introduction
So far, I successfully managed to create the encoding part. I wanted to test the code for consistency, so I tried to run the code on an Arduino UNO and kept on calling the encoding function in void loop. Initially, the results were as expected -

The long line of text is the expected output. But suddenly, it does this -

Then there is a period where the output is blank and finally, this comes-

For some reason, only the signature part gets printed. Also, I have no idea what the last 2 outputs are. Finally, it goes blank for a second and then repeats the entire process
Can anyone please help me in figuring out what is going on and how do I solve it?
This is my code in the library-
custom_jwt.h
#ifndef _CUSTOM_JWT_H_
#define _CUSTOM_JWT_H_

#include <Arduino.h>

class CustomJWT{
private:
    char* secretKey;

public:
    char* header;
    char* payload;
    char* signature;
    String out;

    CustomJWT(char* secret);

    char* getSecret();

    void changeSecret(char* secret);

    void encodeJWT(char* string);

    void decodeJWT(char* string);

};

#endif //_CUSTOM_JWT_H_

custom_jwt.cpp
#include "custom_jwt.h"
#include "sha256.h"
#include <Arduino.h>

const char b64[]  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const char head[] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";

void decodeblock(unsigned char in[], char *clrstr) {
    unsigned char out[4];
    out[0] = in[0] << 2 | in[1] >> 4;
    out[1] = in[1] << 4 | in[2] >> 2;
    out[2] = in[2] << 6 | in[3] >> 0;
    out[3] = '\0';
    strncat(clrstr, reinterpret_cast<const char *>(out), sizeof(out));
}

void b64_decode(char *b64src, char *clrdst)
{
    int c, phase, i;
    unsigned char in[4];
    char *p;

    clrdst[0] = '\0';
    phase = 0; i=0;
    while(b64src[i]) {
        c = (int) b64src[i];
        if(c == '=') {
            decodeblock(in, clrdst);
            break;
        }
        p = strchr(b64, c);
        if(p) {
            in[phase] = p - b64;
            phase = (phase + 1) % 4;
            if(phase == 0) {
                decodeblock(in, clrdst);
                in[0]=in[1]=in[2]=in[3]=0;
            }
        }
        i++;
    }
}

void encodeblock( unsigned char in[], char b64str[], int len ) {
    unsigned char out[5];
    out[0] = b64[ in[0] >> 2 ];
    out[1] = b64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
    out[2] = (unsigned char) (len > 1 ? b64[ ((in[1] & 0x0f) << 2) |
                                             ((in[2] & 0xc0) >> 6) ] : '=');
    out[3] = (unsigned char) (len > 2 ? b64[ in[2] & 0x3f ] : '=');
    out[4] = '\0';
    strncat(b64str, reinterpret_cast<const char *>(out), sizeof(out));
}

void b64_encode(char *clrstr, char *b64dst) {
    unsigned char in[3];
    int i, len = 0;
    int j = 0;

    b64dst[0] = '\0';
    while(clrstr[j]) {
        len = 0;
        for(i=0; i<3; i++) {
            in[i] = (unsigned char) clrstr[j];
            if(clrstr[j]) {
                len++; j++;
            }
            else in[i] = 0;
        }
        if( len ) {
            encodeblock( in, b64dst, len );
        }
    }
}

void b64_encode(unsigned char *clrstr, char *b64dst)
{
    unsigned char in[3];
    int i, len = 0;
    int j = 0;

    b64dst[0] = '\0';
    while(j < 32) {
        len = 0;
        for(i=0; i<3; i++) {
            in[i] = clrstr[j];

            if(clrstr[j] && j < 32) {
                len++; j++;
            }
            else in[i] = 0;
        }
        if( len ) {
            encodeblock( in, b64dst, len );
        }
    }
}

CustomJWT::CustomJWT(char *secret)
{
    CustomJWT::secretKey = secret;
}

char * CustomJWT::getSecret()
{
    return CustomJWT::secretKey;
}

void CustomJWT::changeSecret(char *secret)
{
    CustomJWT::secretKey = secret;
}

void CustomJWT::encodeJWT(char *string)
{
    //Create header and body
    int len = (strlen(string) + 2)/3*4;
    char str[len];
    b64_encode(string, str);
    while(str[strlen(str) - 1] == '=')
        str[strlen(str) - 1] = '\0';
    String temp = head;
    temp = temp + ".";
    temp = temp + str;
    //Convert passkey to unsigned int
    char* msg1 = CustomJWT::secretKey;
    size_t length = strlen(msg1 + 1);
    char* beg = msg1;
    char* end = msg1 + length + 1;
    uint8_t* key = new uint8_t[length + 1];
    size_t i = 0;
    for (; beg != end; ++beg, ++i)
    {
        key[i] = (uint8_t)(*beg);
    }
    //Initialise HMAC
    Sha256.initHmac(key, length + 1);
    //Convert string to char array
    char temp1[temp.length() + 10];
    temp.toCharArray(temp1, temp.length() + 10);
    //Obtain result
    Sha256.print(temp1);
    uint8_t* hash = Sha256.resultHmac();
    //Encode to b64
    len = ((32 + 2)/3)*4;
    char str1[len];
    b64_encode(hash, str1);
    while(str1[strlen(str1) - 1] == '=')
        str1[strlen(str1) - 1] = '\0';
    temp = temp + ".";
    temp = temp + str1;
    CustomJWT::out = temp;
}

This is the code on the Arduino:
#include <custom_jwt.h>

int i;
char key[] = "tester";
char string[] = "{\"temp\":22.5,\"speed\":25.1}";
CustomJWT jwt(key);

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

void loop()
{
  jwt.encodeJWT(string);
  Serial.println(jwt.out);
}

I have used the SHA256 library that I found in this link with some minor modifications as mentioned here HMAC SHA256 in Arduino use case? so that it can compile:
https://github.com/Cathedrow/Cryptosuite
Any help will be appreciated.

Is the Serial tx buffer overrunning? Try if (Serial.availableForWrite() >= sizeof(jwt.out)) Serial.println(jwt.out);

Nope. Didn't work.

Could it be a memory related issue? Cause the behavior is consistent irrespective the delay() used.

It could be your temp variable causing your heap to turn into swiss cheese. You should re-factor that to use a static buffer.

Yeah, that is possible. I was just writing the JWT decoding script. It worked fine until I got strings involved after which it started showing similar problems. I think I need to rewrite the code to not use strings.

Unrelated, but "JWT" stands for JSON Web Tokens.

Noted. I'll just fix that. Thanks.

As @Majenko had pointed out in the comments, it was temp variable causing the problem. Or rather, strings in general seem to have a bad effect on the memory of the Arduino UNO. After I rewrote the code without using any strings at all, the problem was fixed and the program gave a consistent output.


text:
Serial monitor can't display float and double values with absolute greater than 4294967040=2^32-2^8
I have the following sketch:
void setup() {}

void loop() {
  float af = 4294967040.0;
  float bf = 4294967240.0;
  double ad = 4294967040.0;
  double bd = 4294967040.00001;
  Serial.println(af);
  Serial.println(bf);
  Serial.println(ad);
  Serial.println(bd);
}

The values of af, bf, ad and bd are way smaller than 3.402823466e38 which is the maximum for float values. The values can still be correctly operated with, but the result on the serial monitor however is ovf for bf and bd.
Why is that?

Also note that on Unos etc there's no difference between doubles and floats: https://www.arduino.cc/reference/en/language/variables/data-types/double/

Related: Answer on StackOverflow.

It's not the data type, it's the printing routine that sets that limit.  In Print.cpp:
227   if (isnan(number)) return print("nan");
228   if (isinf(number)) return print("inf");
229   if (number > 4294967040.0) return print ("ovf");  // constant determined empirically
230   if (number <-4294967040.0) return print ("ovf");  // constant determined empirically

Don't ask why...

That's bizarre, it's not even the (quite) max unsigned int value. Might try a version w/o that and see what happens.

@DaveNewton I know. It was a surprise to me too...

print does not produce an exponent format, so there must be a reasonable limit somewhere. Maybe they took the mantissa size ? surprise, yes indeed. Thanks for bringing this to our attention,

4294967040.0 (float)  is 0x4f7fffff  => (Sign) 0  (Exponent) 10011110 (Mantissa) 11111111111111111111111

Looks like it's a guard for unsigned long int_part = (unsigned long)number;.  Since number can be larger than an unsigned long can hold, the explicit-cast, (unsigned long)number, probably threw an error or something, around that value.  Since the value was "determined empirically", it may've been a bit stricter than necessary.  Guessing it could've been as high as 2^32-1 (whereas it's actually just 2^32-256).


text:
Audrino mkr1500 keeps going offline
I am using a MKR1500 with an Arduino SIM. I am able to upload the code on the device using the web editor. But when once I am done uploading the code, the device shows status offline and I am unable to check if the data is changing in the dashboard. I am running the below code to test. Also if i check when was the last time it was active, it generally shows before flashing. Also found that when I detach the device from the web UI and select it again, it shows up the last active timing as when it was detached. But during that time I saw it was inactive. Is there something that i am missing?
Can someone please help me with it.
Thanks!
int readSensor;
void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);
  Serial.println("Hello world");
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
}
void loop() {
  ArduinoCloud.update();
  // Your code here
  int sensor1 = analogRead(A1);
  int carbonMonoxide = analogRead(A2);
  int methaneSensor = analogRead(A3);
  Serial.println(sensor1);
  Serial.println(carbonMonoxide);
  Serial.println(methaneSensor);
  delay(1000);
 }
void onADCvalueChange() {
  // Do something
}

The mkr1500 is not compatible with the sim right only the mkr1400 is working with the sim SORRY!
Check The Page store.arduino.cc/digital/sim

So can I use any other sim to make it work. Seems to be that my other SIM(T mobile, AT & T) also doesnt seem to work. The arduino sim seems to have some activation issue it seems, just heard back from the arduino team

I was able to get the MKR1500 online using a Soracom sim card. Seems to be that the T-mobile nbiot sim are a pian to get them talking to the cloud.. Thanks for all the help!

sorry for the late reply. I think 1500 is not built for GSM capibilitys please check what the mkr board is for


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

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

int buttonState = 0;

// Define motor interface type
#define motorInterfaceType 1

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

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

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

  if(buttonState = 0){

  }

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

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

}

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

direction = ! direction;

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


text:
How to get the value of a measurement transmitted by a BLE device?
I would like to use a BLE temperature sensor (such as the Inkbird IBS-TH1 Mini BLE Sensor), however, I want to be able to display the temperature measurements in my own website. To do this I am planning to have an ESP32, which would intercept the temperatures sensor's BLE messages (and then send them to Firebase Realtime Database via WiFi). I know how to use the ESP32 to find advertising devices, however, I am not sure how to receive the measurements the sensor is transmitting. I have seen libraries such as the ESPHome or ESP32-mqtt-room, but I was wondering whether there is a way to bypass them? Is it neccesary to use mqtt or mosquito? Or is it possible to achieve this using solely the Arduino BLE library?
Any help would be appreciated!


text:
How to properly send bytes between RPI and Arduino over I2C while using ISR without IOerrors?
I have a I2C connection between an RPI 3B+ and Arduino Nano. I want to send a key and a corresponding value byte, and the arduino does something with that inside a timed ISR. Which works. But I get IOerrors at the RPI side, probably because the ISR is busy. So I did a little test. Every 10000 messages send:

245 IOerrors at 51,281 Hz ISR
104 IOerrors at 25,600 Hz ISR
28 IOerrors at 6,400 Hz ISR

Is there any way to have less or no IOerrors? I need about 25,600 kHz for my ISR.
RPI side:
bus.write_i2c_block_data(0x60, 0x00, [key, val])

Arduino side message handler called as Wire.onReceive(msg_handler);:
void msg_handler(int bitstream) {
     Wire.read();
     int pin = Wire.read();
     int val = Wire.read();
     Serial.println(pin);
     Wire.begin(0x60);

I do the wire begin every time because otherwise once it had a IOerror it stops printing on the serial.
My wiring is 18 AWG and about 20cm. The error:
[Errno 121] Remote I/O error

What i2c clock speed are you using?
Even at the faster "fairly standard" speed of 400kHz, that's 2.5us per bit. For a two byte transfer, that's 4us for the data alone, which is 25000 transfers per second. Add on the start and stop bits, plus processing time and you can see that your target data rate isn't possible.
i2c just isn't that fast as standard, though there are much faster "non standard" modes.


text:
ESP 32 unable to connect to https website and return the data using GET
I have created a ThingHTTP below:
https://api.thingspeak.com/apps/thinghttp/send_request?api_key=BVLJ7A6KNK9VVAYK

In my browser I could see the reply. But I am unable to make this work in my ESP32. I understand that this is a https so I would have to declare the root cert details. I have tried to modify based on this tutorial:
https://github.com/witnessmenow/arduino-sample-api-request/blob/master/ESP8266/HTTP_GET/HTTP_GET.ino

My code as follows:
#include <WiFi.h>
#include <WiFiClientSecure.h>

//------- Replace the following! ------
char ssid[] = "SSID";       // your network SSID (name)
char password[] = "pass";  // your network key

// For Non-HTTPS requests
// WiFiClient client;

// For HTTPS requests
WiFiClientSecure client;

// Just the base of the URL you want to connect to
#define TEST_HOST "https://api.thingspeak.com/apps/thinghttp/send_request?api_key=BVLJ7A6KNK9VVAYK"

const char *server_cert = "-----BEGIN CERTIFICATE-----\n"
                                  "MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\n"
                                  "RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\n"
                                  "VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\n"
                                  "DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\n"
                                  "ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\n"
                                  "VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\n"
                                  "mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\n"
                                  "IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\n"
                                  "mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\n"
                                  "XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\n"
                                  "dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\n"
                                  "jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\n"
                                  "BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\n"
                                  "DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n"
                                  "9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\n"
                                  "jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\n"
                                  "Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\n"
                                  "ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\n"
                                  "R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n"
                                  "-----END CERTIFICATE-----\n";

void setup() {

  Serial.begin(115200);

  // Connect to the WiFI
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

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

  //--------

  // Checking the cert is the best way on an ESP32
  // This will verify the server is trusted.
  client.setCACert(server_cert);

  // If you don't want to verify the server
  // Unlike the fingerprint method of the ESP8266 which expires frequently
  // the cert lasts years, so I don't see much reason to ever
  // use this on the ESP32
  // client.setInsecure();

  makeHTTPRequest();
}

void makeHTTPRequest() {
  delay(5000);
  // Opening connection to server (Use 80 as port if HTTP)
  if (!client.connect(TEST_HOST, 443))
  {
    Serial.println(F("Connection failed"));
    return;
  }

  // give the esp a breather
  yield();
  client.connect(TEST_HOST, 443);
  // Send HTTP request
  client.print(F("GET "));
  // This is the second half of a request (everything that comes after the base URL)
  client.print(""); // %2C == ,
  client.println(F(" HTTP/1.1"));

  //Headers
  client.print(F("Host: "));
  client.println(TEST_HOST);

  client.println(F("Cache-Control: no-cache"));

  if (client.println() == 0)
  {
    Serial.println(F("Failed to send request"));
    return;
  }
  //delay(100);
  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  if (strcmp(status, "HTTP/1.1 200 OK") != 0)
  {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders))
  {
    Serial.println(F("Invalid response"));
    return;
  }

  // This is probably not needed for most, but I had issues
  // with the Tindie api where sometimes there were random
  // characters coming back before the body of the response.
  // This will cause no hard to leave it in
  // peek() will look at the character, but not take it off the queue
  while (client.available() && client.peek() != '{')
  {
    char c = 0;
    client.readBytes(&c, 1);
    Serial.print(c);
    Serial.println("BAD");
  }

  // While the client is still availble read each
  // byte and print to the serial monitor
  while (client.available()) {
    char c = 0;
    client.readBytes(&c, 1);
    Serial.print(c);
  }
}

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

}

the program was able to compile, and was able to run until it shows it connect to the network. But then it returned "Connection failed!" I believe it stuck at this line :
if (!client.connect(TEST_HOST, 443))

I am not sure what is the problem here. Comments appreciated.

Try creating a properly formatted HTTP request. Try also connecting to a server not a web page. There are so many things wrong with your GET request I don't know where to start...

Things wrong with your GET request (which are nothing to do with Arduino - just learn the basics of the protocol you are trying to use before you use it):

You are trying to open a socket to a URL not to a server. That can never work. Connect to the server instead (hint: the server, or "FQDN", is the bit between the https:// and the next /).
You aren't providing any path in your GET request, only a comment that says what you should provide.  Hint: the path is everything that comes after (and including) the / following the FQDN.
Your Host: header should contain just the FQDN, not the whole URL. By now you should know what the FQDN is.
You should also include Connection: close in your headers to inform the server you won't be keeping the socket open.

Correct those problems and you might begin to see something useful happening.

Thanks for the pointers. Been new to this. Guess I have started at the wrong place. Anyhow after implementing what you have said, and other minor mistakes, it seems to be working. I found out that I have to change the certificates for the website, there are a few types. Anyway thanks again.

The piece of code below is from a firmware code I've been programming lately to use on Tensilica's Xtensa LX6/7 compatible MCUs (ESP32). The code below makes an HTTPS request using WIFIClientsecure library.
String GetInfoFromDataverse(String url) {
  //Check WiFi connection status

  if(WiFi.status() != WL_CONNECTED){
    mserial.printStrln("WiFi Disconnected");
    if (connect2WIFInetowrk()){
      GetInfoFromDataverse(url);
    }
  }

  int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator)
  char SERVER_URL_char [str_len];    // Prepare the character array (the buffer)
  SERVER_URL.toCharArray(SERVER_URL_char, str_len);    // Copy it over

  client.stop();
  client.setCACert(HARVARD_ROOT_CA_RSA_SHA1);

  if (!client.connect(SERVER_URL_char, SERVER_PORT)) {
      mserial.printStrln("Cloud server URL connection FAILED!");
      mserial.printStrln(SERVER_URL_char);
      int server_status = client.connected();
      mserial.printStrln("Server status code: " + String(server_status));
      return "";
  }

  mserial.printStrln("Connected to the dataverse of Harvard University");
  mserial.printStrln("");

  // We now create a URI for the request
  mserial.printStr("Requesting URL: ");
  mserial.printStrln(url);

  // Make a HTTP request and add HTTP headers
  // post header
  String postHeader = "GET https://" + SERVER_URL + url + " HTTP/1.1\r\n";
  postHeader += "Host: " + SERVER_URL + ":" + String(SERVER_PORT) + "\r\n";
  //postHeader += "X-Dataverse-key: " + API_TOKEN + "\r\n";
  postHeader += "Content-Type: text/json\r\n";
  postHeader += "Accept: text/html,application/xhtml+xml,application/xml,application/json,text/json;q=0.9,*/*;q=0.8\r\n";
  postHeader += "Accept-Encoding: gzip,deflate\r\n";
  postHeader += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
  postHeader += "User-Agent: AeonLabs LDAD Smart DAQ device\r\n";
  postHeader += "Keep-Alive: 300\r\n";
  postHeader += "Connection: keep-alive\r\n";
  postHeader += "Accept-Language: en-us\r\n";

  // request tail
  String tail = "\r\n--" + boundary + "--\r\n\r\n";

  // content length
  int contentLength = tail.length();
  postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";

  // send post header
  int postHeader_len=postHeader.length() + 1;
  char charBuf0[postHeader_len];
  postHeader.toCharArray(charBuf0, postHeader_len);
  client.print(charBuf0);

  mserial.printStrln("======= Headers =======");
  mserial.printStrln(charBuf0);
  mserial.printStrln("======= End of Headers =======");

  // Read all the lines of the reply from server and print them to mserial
  String responseHeaders = "";

  mserial.printStr("Waiting for server response...");
  long timeout= millis();
  long ttl=millis()-timeout;
  while (client.connected() && abs(ttl) < 30000) { // 30 sec.
    ttl=millis()-timeout;
    responseHeaders = client.readStringUntil('\n');
    if (responseHeaders == "\r") {
      break;
    }
  }
  if (abs(ttl) < 30000){
    mserial.printStrln("OK");
  }else{
    mserial.printStrln("timed out.");
  }

  String responseContent = client.readStringUntil('\n');
  client.stop();

  return responseContent;
  }


text:
I am in need of a usable communication library on 1-4 pins of ATTiny84 instead of I2C
I messed up when designing my PCB and just assumed that I could use software slave I2C with ATTiny84.
The reason I did so is - I needed to use all of the analog inputs.

The pins I have on my connector are:
PB0 (pin 2), PB1 (pin 3), PB2 (pin 5) and PA0 (pin 13)
Is there an alternative to I2C or a different communication protocol I could use to connect multiple of these slave boards to a master (ATMEGA328 etc.)?
Thanks a lot, I can provide any further information.

SPI without MOSI (one-way comms) only needs two pins CLK & MISO. That saves you one pin.

You can write a bit-banging implementation of I2C. -- As well as any other serial protocol. -- You could even invent your own protocol, but this is not wise. -- There are many serial protocols, starting with 1 wire.

That is a lot of pins, so this really boils down to your application and what you want to optimize for.
You could do a bit-banged software I2C slave on these pins. "Bit-bang" means you just write a program to flip the bits on the pins rather than handing the bytes off to the hardware which would do the same thing (although sometimes faster or without using up CPU cycles). This would require either finding some existing code to implement the protocol, or sitting down with the documentation for the protocol and writing it yourself. Depending on your goals, the second option might be a great learning experience and take away some of the magic from this stuff. It is all just 1s and 0s and once you really internalize that, you realize that you can do almost anything with these little chips regardless of hardware or library support.


text:
consecutive analogRead()
Has anyone noticed that if calling analogRead() in a consecutive way that the value drops by a bit as opposed to just doing a single read?
And is this to be expected?
I am using a Seeeduino XIAO.

You need a short delay between analog reads, more about it here: https://www.quora.com/Why-is-a-little-delay-needed-after-analogRead-in-Arduino

@Nino Thank you. That would explain it! (Add it as answer and I mark it as solution.)

You need a short delay between analog reads due to the time it takes to complete a reliable ADC reading. In depth technical explanations can be found here, note that it refers to AVR architecture.


text:
Replace CH340 With FTDI
I have built a arduino midi octapad with a Clone of arduino nano that contain a ch340 chip but hairless midi says FTDI driver doesn't installed i installed that driver but it still show that error so can i replace the ch340 chip with a FTDI chip to resolve this Problem... ?

yes ... install an FTDI  chip to resolve the "no FTDI chip installed" error

You can't just take one chip off and put another on. The two are very different things. Like taking a boot off and trying to put a glove on your foot instead. You could remove (or disable) the CH340 and connect an FTDI cable or dongle to the TX/RX pins though. Would that solve the "problem"? Maybe - who knows? What's "hairless midi"?

Personally I wouldn't bother messing with it. I'd just choose a microcontroller with a native USB connection that is capable of being programmed to appear as a USB MIDI device.

When you search for "FTDI" in one of the hairless-midiserial repos on github (I looked at this and this one), you find what looks like your error message (though you didn't actually put it in your question:
./src/PortLatency_win32.cpp:        emit debugMessage("FTDI drivers don't seem to be installed. Not attempting any FTDI latency tricks.");

Also the repos have a class in PortLatency.h with the description:
A simple class to manage latency reduction of FTDI-based serial ports.

This gives us some information:

The message above is not an error message, but a debug message. It might work despite not having an FTDI
The class description suggests, that the program wants to use some tricks to reduce the latency in the communication. These tricks seem to be FTDI specific. When the above debug message appears, these tricks are not used. Thus your performance may be significantly worse than with an FTDI chip. Also one of the repos has an open issue about problems with the CH340, which states, that it just doesn't work correctly. It was updated in May and still has no solution. I would not bet on getting help there. (Also the ground repo, that the other was forked off, wasn't updated since 5 years.)
You cannot fix that debug message by installing the FTDI drivers, because you don't use an FTDI chip.

As we are on Arduino SE here, we cannot really help you with that program running on your PC.
Of course you can use an extra FTDI chip/board and connect it to the RX and TX lines of the Arduino (not using the CH340 USB serial chip on the Arduino itself). But I support Majenkos comment about just migrating to an Arduino with native USB connection (means the USB communication is done by the Arduinos microcontroller directly, not by an extra chip) (for example the Micro, but there are a lot more Arduinos with native USB). That enables you to manipulate the type of USB connection, thus you can let the Arduino directly appear and work as an USB midi device. Then you don't need the hairless-midiserial program anymore.


text:
RaspberryPi Pico SPI and nrf24l01
I am programming a RaspberryPi Pico with the Arduino IDE. Works pretty well, but now I try to control an nrf24l01 module.
My code compiles but I do not know on which pins the SPI bus has to be hocked up. I tried to connect to different pins according the pinout
https://datasheets.raspberrypi.org/pico/Pico-R3-A4-Pinout.pdf
(for example 2 sck, 3 miso, 4 mosi), but nothing worked so far.
Does anybody know what the default pins are or how to control them? I also would like to control other SPI hardware, for example a display.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const uint64_t address = 0x1;
byte sendData[1];

#define CSN_PIN  5
#define CE_PIN   6
RF24 radio(CE_PIN, CSN_PIN);

byte counter = 0;

void setup()
{
  Serial.begin(115200);
  Serial.println(“radio starting");

  if (!radio.begin())
  {
    Serial.println("radio hardware is not responding!!");
    while (1) {}
  }
  radio.openWritingPipe(address);
}

void loop()
{
  Serial.print("Counter: ");
  Serial.println(counter);

  sendData[0] = counter;

  radio.write( sendData, sizeof(sendData));

  counter++;
}

Did you successfully run it both transmission and receiving? Any capacitor you use? My experience is that when using Raspberry Pi Pico + NRF24L01 and on Micropython, it works BUT fails when programmed on Arduino

For Arduino-pico core
** MISO - pin GP16
** MOSI - pin GP19
** CS   - pin GP17
** SCK  - pin GP18

Arduino-mbed core
** MISO - pin GP4
** MOSI - pin GP3
** CS   - pin GP5
** SCK  - pin GP2

Fantastic, it works!

Source, and other pins hard-coded on the pico: https://github.com/arduino/ArduinoCore-mbed/blob/8e0a044330e88bde781eb4c509875ce94980659f/variants/RASPBERRY_PI_PICO/pins_arduino.h


text:
Arduino MKR NB 1500 websockets
I am trying to implement websockets for MKR1500 and I am having trouble finding a perfect example to implement it. Can someone guide me to an example that works with MKR1500?

I would try ArduinoHttpClient library with MKRNB library


text:
How do I make another action repeat inside a loop?
So, I've just started programming Arduino (and also in general), so I'm doing basic things, like switching on and off LED's.
I've made them light in a sequence and then turning them off (in the same sequence), and now I wanted to use 2 buttons, one to make them do the same thing as before (light and turning LED's off in sequence) repeatedly, and the other to turn them off.
The problem is that curently they only light up once, and not repeatedly, I think I would've needed another loop, but i found out that you can't use 2 of them.
Can anyone help me? here's the code
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int buttonON = 7;
int buttonOFF = 8;

void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(buttonON, INPUT_PULLUP);
  pinMode(buttonOFF, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(buttonON)== LOW)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
 if (digitalRead(buttonOFF)== LOW)
 {
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);
  digitalWrite(LED4, LOW);
  digitalWrite(LED5, LOW);
 }
}

P.S. if anyone has other general tips I would really apreciate them

insert a layer of separation between the button press and the LED lighting ... use a flag variable .... if (digitalRead(buttonON)== LOW)  ledsON = true; .... then further down in the code if (ledsON) { / led lighting code } ... you can set/clear ledsON flag any number of times, so you could check the button after every led is lit ... that way you don't have to hold the button until the sequence is finished

good way of asking question ;) Nicely written, formatted +1

I take it you are new to programming?

yes, like i said, I've just started, and decided to start programming with Arduino

You have written your question beautifully.
In your case, according to your logic, the button has to be kept pressed, so that the LEDs are lit in the order you desire. The single loop() function is part of the Arduino sketch but it is never a limitation.
One way to solve your problem is to make the LED drive logic independent of the button press state.

Once you detect the button press, store the event in one variable.
Let us call it ButtonStatus.
So, soon after the keypress is detected, update the ButtonStatus variable to TRUE.
Your LED drive logic can check this variable value to decide whether to drive the LEDs or not
Soon after you detect another press of the second button, you can update the variable value to FALSE.
Here is the Arduino simulation output for your code and the code suggested by @cat

below is after adapting the solution from cat

The simulation links are here:
Original problem
solution 1
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int buttonON = 7;
int buttonOFF = 8;
int ledEffectON;
void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(buttonON, INPUT_PULLUP);
  pinMode(buttonOFF, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(buttonON)== LOW)
      ledEffectON = true;

  if (digitalRead(buttonOFF)== LOW)
      ledEffectON = false;

  if(ledEffectON)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
}

Link to docs on Pushbuttons. Wokwi Arduino simulator simulates debounce by default - just like real-world switched. Debounce is a very important technique that you should consider adding to the code. To disable the "bounce" option, use the below trick!
{ "bounce": "0" }

Thanks, really apreciate the time you spent on explaining it

Very nice diagrams!

@Juraj brought in resistors. I have also updated the links referred to. Now you should see the current limiting resistors as well!

By using delay() it blocks the rest of the code. The programme needs to keep track of two buttons and update the lightshow at appropriate times, therefore a non-blocking style of coding is needed similar to the Blink Without Delay example where the delay() is replaced with a timer using millis() that is checked periodically. This allows other things to be checked periodically as well, e.g. the buttons.
Also the button contacts tend to bounce several times for several milliseconds when they change state sending a train of on/off pulses to the MCU, so they need to be debounced. You can find many debouncing algorithms online, but here's a simple debouncer that I put on GitHub.
void loop ()
{
  static bool doLightshow = false;

  static Debouncer buttonOn(buttonON);
  static Debouncer buttonOff(buttonOFF);

  buttonOn.Update();
  buttonOff.Update();

  if (buttonOn.Fall())
  {
    Serial.println("buttonOn falling edge.");
    doLightshow = true;
  }
  else if (buttonOff.Fall())
  {
    Serial.println("buttonOff falling edge.");
    doLightshow = false;
  }

  if (doLightshow)
  {
    // Do lightshow.
    . . .
  }
  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, LOW);
    digitalWrite(LED4, LOW);
    digitalWrite(LED5, LOW);
  }
}

Due to the way you've neatly written your code, you can probably pick out a pattern in the lightshow.

State
Delay time
LED pin
LED state

0
300
LED1
HIGH

1
50
LED2
HIGH

2
50
LED3
HIGH

3
50
LED4
HIGH

4
50
LED5
HIGH

5
300
LED1
LOW

6
100
LED2
LOW

7
100
LED3
LOW

8
100
LED4
LOW

9
100
LED5
LOW

This lends itself well to creating a Finite State Machine that can be stored in an array of structures:
typedef struct LightshowData
{
  unsigned int delayTime;
  byte ledPin;
  bool ledState;
};

const byte numStates = 10;

const LightshowData lightshowData[numStates] =
{
  { 300, LED1, HIGH },
  {  50, LED2, HIGH },
  {  50, LED3, HIGH },
  {  50, LED4, HIGH },
  {  50, LED5, HIGH },
  { 300, LED1, LOW },
  { 100, LED2, LOW },
  { 100, LED3, LOW },
  { 100, LED4, LOW },
  { 100, LED5, LOW }
};

The state machine can now cycle through the array in a non-blocking manner:
    // Do lightshow.
    static byte state = 0;
    unsigned long currentTimestamp = millis();
    static unsigned long previousTimestamp = currentTimestamp;

    if (currentTimestamp - previousTimestamp >= lightshowData[state].delayTime)
    {
      previousTimestamp += lightshowData[state].delayTime;
      digitalWrite(lightshowData[state].ledPin, lightshowData[state].ledState);
      state = ++state % numStates;
      Serial.print("state = ");
      Serial.println(state);
    }

You may want to reset state to 0 after a negative edge on buttonOff, otherwise the lightshow will continue where it left off after being stopped and restarted.
Here's the Wokwi simulation of the lightshow with 250 Ω protection resistors for the LEDs.

Wokwi simulates button bounce by default to more accurately model the real world, so it's advisable to have some form of button debouncing.

thanks man, looks a bit difficult, but I'll certanly check it out

When the loop() function does not need any time ( avoid delay and nested time consuming loops ) your program logic is completely different from before, but more flexible and easier, once you got used to it.

You simply need to save the state of the LEDs in a new variable ...
void loop ()
{
  if (digitalRead(buttonON)== LOW)
      ledEffectON = true;

  if (digitalRead(buttonOFF)== LOW)
      ledEffectON = false;

  if(ledEffectON)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
}

https://wokwi.com/arduino/projects/304626706673566272 Wonderful solution!

Thanks for the short and simple answer

It's very seldom that  buttonOFF is checked. It needs to be pressed when LED5 goes LOW

is this not the same code as in ArduinoFan's answer?


text:
Can bool variable be NULL
I want to know if bool variable can be null, or it must have to be true or false:
Base on Arduino description:
A bool holds one of two values, true or false. (Each bool variable occupies one byte of memory.)

A bool value must be either 0 or 1, or false and true respectively. It is undefined behavior for it to be any other value. When assigning a value to a bool, the compiler will automatically force it to be 0 if it is already 0, or 1 if it is not.
However, as it is a full byte, it is possible to store another value. As mentioned before, however, this is undefined behavior. This means that if it ever happens, or will absolutely happen, the program can do anything: for example, crash the program, output random data, or act like it's truthy, falsy, or both! In fact, that can (again, no guarantees) happen if you store the value 2:
#include <cstdio>

int main() {
    union b_c {
        unsigned char c;
        bool b;
    };
    b_c c;
    c.c = 2;

    if(c.b) puts("true!");
    if(!c.b) puts("false!");
}

(this is designed to run on a computer, but the same thing could happen on an Arduino). Check out what happens when you run it: it outputs both true! and false!! This obviously doesn't make sense, but because we violate the rules by making a bool 2, we loose all guarantees.

So, how is this relevant to your question? There's no valid value a bool can store other than true and false. In C++, null is defined as "an integer literal with value zero". So, if you were to assign null to a bool, it would be stored as false. If you want a separate null value, you're better off using another type that takes up a single byte (e.g. unsigned char or uint8_t, same thing) and storing e.g. 0 for false, 1 for true, and 2 for null.

just want to know if i am correct or not that bool is single bit can only hold 0 or 1

@Shahreza yes, you can only store a 0 or 1 in a bool, i.e. a single bit. However, because you can't address single bits, each bool takes up a full byte, even though you can't use the other 7 buts.

Depending on the compiler's implementation, a bool can also be as wide as an int. There is no guarantee that it takes just 8 bits (chapter 8.3.3 in the C++17 standard). However, some systems support bit accesses (8051 microcontroller, for example), and some compilers for these support 1-bit bools.

A boolean test doesn't look only at bit 0 in most implementations; rather, it may look at the entire variable and test it's "zero-ness. Zero == false; non-zero == true. That still doesn't leave any values for a third distinct meaning (such as NULL). If you need that, an enum would be a better choice.

A bool is literally that - a boolean value. So either 1 or 0 - true or false.
In C only pointers can be NULL. Every other primitive type is a value, and NULL is not a value.


text:
Driver configuration not showing the right numbers on the Graphics Test example's serial monitor for Adafruit IlI9341 library
I have a 2.8" Color TFT Touchscreen from Adafruit, and I'm currently trying to set it up. I've been following this guide to set up the screen. The screen powers on when connected to power, but it's not displaying what the example says it should. I can't tell if it's the code of our the hardware that's the issue, but since the hardware setup is pretty straightforward on the site, my guess is it's the code.
The guide says to check the serial console, and that the configuration bytes should be similar. Here's the example's configuration bytes:

Versus what my serial console is displaying

I should note that I am using a Nano every instead of an Uno, but looking up the SPI pins for the Nano Every, I found that they should be the same as for the Uno. But if anyone can confirm that, much appreciated. That could definitely be the problem if I'm wrong.
Finally, I'm including the code that I am currently using below. There are no issues with uploading, and I've triple checked that I have the right libraries downloaded, and am using the correct board and port. I'm thinking the everything before the setup is what might be causing the issue, but I've included the entirety of the setup as well.
  This is our GFX example for the Adafruit ILI9341 Breakout and Shield
  ----> http://www.adafruit.com/products/1651

  Check out the links above for our tutorials and wiring diagrams
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional)
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

// For the Adafruit shield, these are the default.
#define TFT_DC 9
#define TFT_CS 10
#define TFT_CLK 13
#define TFT_MISO 12
#define TFT_MOSI 11

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
// Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_CLK, TFT_MISO, TFT_MOSI);

void setup() {
  Serial.begin(9600);
  Serial.println("ILI9341 Test!");

  tft.begin();

  // read diagnostics (optional but can help debug problems)
  uint8_t x = tft.readcommand8(ILI9341_RDMODE);
  Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDMADCTL);
  Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDPIXFMT);
  Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDIMGFMT);
  Serial.print("Image Format: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDSELFDIAG);
  Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);

  Serial.println(F("Benchmark                Time (microseconds)"));
  delay(10);
  Serial.print(F("Screen fill              "));
  Serial.println(testFillScreen());
  delay(500);

  Serial.print(F("Text                     "));
  Serial.println(testText());
  delay(3000);

  Serial.print(F("Lines                    "));
  Serial.println(testLines(ILI9341_CYAN));
  delay(500);

  Serial.print(F("Horiz/Vert Lines         "));
  Serial.println(testFastLines(ILI9341_RED, ILI9341_BLUE));
  delay(500);

  Serial.print(F("Rectangles (outline)     "));
  Serial.println(testRects(ILI9341_GREEN));
  delay(500);

  Serial.print(F("Rectangles (filled)      "));
  Serial.println(testFilledRects(ILI9341_YELLOW, ILI9341_MAGENTA));
  delay(500);

  Serial.print(F("Circles (filled)         "));
  Serial.println(testFilledCircles(10, ILI9341_MAGENTA));

  Serial.print(F("Circles (outline)        "));
  Serial.println(testCircles(10, ILI9341_WHITE));
  delay(500);

  Serial.print(F("Triangles (outline)      "));
  Serial.println(testTriangles());
  delay(500);

  Serial.print(F("Triangles (filled)       "));
  Serial.println(testFilledTriangles());
  delay(500);

  Serial.print(F("Rounded rects (outline)  "));
  Serial.println(testRoundRects());
  delay(500);

  Serial.print(F("Rounded rects (filled)   "));
  Serial.println(testFilledRoundRects());
  delay(500);

  Serial.println(F("Done!"));

}```

One difference between Uno and Nano Every is that the SPI on Nano Every could operate at higher SPI data rate. Do you use a level shifter between the display and the Nano Every? Some of the level shifter couldn't handle the higher SPI well. One thing you could try is to change the tft.begin() to tft.begin(3000000);, this set the hardware SPI to 3MHz, and should be able to be handed by the library and whatever level shifter you are using.


text:
PZEM-004T can't read current
I'm trying to measure the current, voltage, and power of AC load using Peacefair PZEM-004Tv3.0 module. For the serial communication of this module, I'm using SoftwareSerial Pins 2 and 3 on Arduino Uno.
But this module seems doesn't work well, it just read the voltage and the rest is zero. The datasheet said:

current test value is from the beginning of 0.02A
power test value is from the beginning of 0.4W

I have assumed the load that I'm trying to measure hasn't enough minimum current or power. But I have tried to measure a bigger load also, and the result of current and power measurement is still zero.
I don't think it is caused by the program because I just run the example of the library. I'm using this library.
Here I attached how do I wire my pieces stuff:

Any suggestions?

SoftwareSerial doesn't work well at 115200 baud on the 8 bit Arduinos. They can't keep up with the flow of data.

Have you tried placing the sensor over the other AC load wire?

Uhh, are you running the line and return through the same CT and going in opposite directions?

I created an answer thinking that it was.  For anyone that doesn't see it, if you zoom in your can just barely tell that the black wire is in fact outside the CT.

It should always be on one lead, not both, and I could see the black is outside. What I suggested is placing the sensor on the "other" lead, meaning remove the red and try the black. Also, have you tried reducing the speed to 9600 as Majenko suggested?

@Nino, to be clear, none of what I wrote was addressing your suggestion.

I have tried all of your suggestions but it still doesn't work guys :(

just changed the CT with the new one and now everything works fine, thank you :D

It would probably be best to delete the question.


text:
how to write a program in Arduino that pairs a single Rx to multiple Tx modules? i want to learn implementing this protocol
I have two Attiny85 communicating over 433mhz radio (Rx & Tx on either ends) using virtual wire library, how will the programming be to pair them by the press of a button on either module ?
i have so far been able to pair them both through the program (exclude any external devices by giving a node ID to listen to in my Rx) or think of adding DIP switches (but i run out of pins & combinations sooner). I am expecting  something similar to a commercial product where i can connect/pair multiple Tx modules to a single Rx base station in a press of a button on the Tx side. so i am seeking some technical expertise on the idea to understand such programming technique/methods.
Regardless of using 433mhz or a NRF24L01 module or anything else, i want to know how this feature of pairing module together is made.
------
Edit 22 July 2021:
This is added here in response from Crisl's comment
you have correctly understood my question, yes i want to learn how such a pairing protocol is implemented, i am not too concerned about the device for the communication gateway.
this question is regarding the protocol, and not about a specific circuit
------
I am a mechanical engineer by profession, with a hobby towards programming & electronics, so kindly spare some patience/detail in explaining this concept/technique.

please add a diagram of the system that you are trying to build

If you are talking about these simple 433MHz modules, which are also used for example in garage openers, then there is normally no pairing. The sender just sends some data (a static code, rolling code or other security measurement) and the receiver receives that data and acts accordingly. They normally don't have a sense of which device send the data. That would be an overlying protocol. Can you please describe, what you want to achieve? Current it is rather broad, so that we cannot really give advice on what would be the best option.

@chrisl.....yes i want to learn the protocol implementation, i am clueless on how to learn such a protocol, maybe give me some reference to learn that will also help

If it is sufficient to distinguish between the two (or several) transmitters and you don't need to exclude intrusions, accidental or otherwise, a "protocol" can be as simple as:
XMTRID BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]
, where each of the above represents a single byte. Does the library include message integrity checking, such as a checksum? If not, and the physical conditions warrant, you might add that to your protocol as well, and include an expectation by the transmitter that it receives an acknowledgement or rejection of correct reception (ACK or NAK) within a short time and will re-transmits the same message if it hasn't received an ACK. Then you'll want a message ID byte that increments for each new message (but not for retramsmission), so the receiver can reject a retransmission (if, say, its attempt to acknowledge had been lost).
Then your protocol could look something like this:
XMTRID MSGID CHKSUM BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]
. and it just keeps getting better from there as you add features for robustness, security, and whatever else you might need it to accomplish. But I'm guessing this is already sufficient.
Update:
To clarify:
XMTRID    - ID of sending 433MHz radio (any value you like, as long as each device has its own).
MSGID     - An incrementing number (rollover allowed), a new one for each *new* message
            (enables the receiver to distinguish new messages from resent ones).
CHKSUM    - A sum of bytes in the message to let the receiver check the message integrity.
BYTECOUNT - The number of message bytes to follow.
BYTE[0] ... BYTE[BYTECOUNT-1] - The actual message data.

Thanks, i understand your logic. this has sparked some new thinking for new topics to learn and experiment on. and i suppose you mean the Tx ID as "XMTRID" ?, and what is the difference between CHKSUM BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]


text:
SD Card Initialization Failed, cannot add inactive module
Just to preface I am not that great at coding or anything and I am currently building sensors off of Oregon State University's Smart Rock sensor code, so the code I am being used is not mine. I am currently operating off their 2.5 and 2.5.1 Firmware as the code and every piece of the device works properly except for initializing an SD card, which continuously gives me the error of:
[Factory] Creating: SD
[SD] Initialize failed
[Device] Cannot add inactive module

I have attempted this in many different boards with different SD cards and the issue remains the same, so I am inclined to think the issue is within the firmware. Is there anyone who could potentially guide me in the right direction on this or determine where the issue is coming from. I will respond quickly. I am using a Feather m0 Adafruit board and a Hypnos V3.1 board. Here is the serial monitor report when running this code, just to add, I am only seeking to fix the SD card issues:
Initialized Serial!

= = = = = Parse Config = = = = =

Config Pretty Version:
{
  "general": {
    "name": "Device",
    "instance": 1
  },
  "components": [
    {
      "name": "Analog",
      "params": [
        8,
        12,
        true,
        false,
        true,
        false,
        false,
        false,
        5,
        0,
        4,
        0,
        0,
        0
      ]
    },
    {
      "name": "SD",
      "params": [
        true,
        1000,
        10,
        "data",
        true
      ]
    },
    {
      "name": "DS3231",
      "params": [
        11,
        true,
        true
      ]
    },
    {
      "name": "Interrupt_Manager",
      "params": "default"
    },
    {
      "name": "Sleep_Manager",
      "params": [
        true,
        false,
        1
      ]
    },
    {
      "name": "MS5803",
      "params": [
        119
      ]
    }
  ]
}
SIZE: 949
= = = = = Generate Objects = = = = =

[Factory] Creating: Analog
[Device] Adding Module: Analog
[Factory] Creating: SD
[SD] Initialize failed
[Device] Cannot add inactive module
[Factory] Creating: DS3231
[DS3231] Current Time (before possible reset)
[DS3231] Time: 2021/7/21 23:42:44
[DS3231] Time: 2021/7/21 23:42:44
[DS3231] Clearing DS3231 alarms
[Device] Adding Module: DS3231
[Device] Adding Module: InterruptManager
[Factory] Creating: Sleep_Manager
[Device] Adding Module: SleepManager
[Factory] Creating: MS5803
Oversampling setting: 512
C0 = 0
C1 = 0
C2 = 0
C3 = 0
C4 = 0
C5 = 0
C6 = 0
C7 = 0
p_crc: 0
n_crc: 0
[MS5803_0] Initialize failed
[Device] Adding Module: MS5803_0
= = = = = = = = = = = = = = = = =

[Device] Config:
    Device Name         : Device
    Instance Number     : 1
    Device Type         : Node
    Interval            : 1000
[Device] Modules:
    Others
        [+] InterruptManager
        [+] SleepManager
    Sensors
        [+] Analog
        [+] MS5803_0
    RTCs
        [+] DS3231
[InterruptManager] Registering ISR on pin 12 to be triggered on 0 and is immediate

 ** Setup Complete **
[Device] Json:
{
  "type": "data",
  "id": {
    "name": "Device",
    "instance": 1
  },
  "contents": [
    {
      "module": "Packet",
      "data": {
        "Number": 1
      }
    },
    {
      "module": "Analog",
      "data": {
        "Vbat": 0.012891,
        "EC[0]": 357.7055,
        "turbidity[2]": 2471
      }
    },
    {
      "module": "MS5803_0",
      "data": {
        "pressure": 0,
        "temp": 20
      }
    },
    {
      "module": "LocalTime",
      "data": {
        "Date": "2021/7/21",
        "Time": "15:42:44",
        "TimeZone": "PST"
      }
    }
  ],
  "timestamp": {
    "date": "2021/7/21",
    "time": "23:42:44"
  }
}

Any help would be appreciated! I'm sorry if the formatting is wonky I'm very new to this.

Guessing, by any chance, are you using SDCards formatted by a Microsoft machine?  Try a new from the factory SDCard which is likely formatted traditionally with partition tables.  For what ever reason, Microsoft may have left that off their list of important things to do.

Also you might look here where several people with different problems are discussing SDCard Arduino issues.

This "Cannot add inactive module" has me stumped.  Make sure all you software is up to date including any supporting software like Arduino libraries and board support.

Adding on to the first comment, Make sure that your SD card is not a high capacity version or one that is formatted(use as comes from factory) these factors may be causing you trouble. If you did format it, format it again with a different file allocation table


text:
Using Arduino LMIC library with EnableInterrupt
I am using the EnableInterrupt library, infact the only library that I can find that allows me to use six interrupts to wake the Arduino. However when I use it with the LMIC library (Matthijs Kooijman ) the "Forward uplink data message" is not sent during initial registration, only if
#include <EnableInterrupt.h> is commented out does it work. I am using a RFM95 with the following LMIC pin assignments:
const lmic_pinmap lmic_pins = {
.nss = 10,
.rxtx = LMIC_UNUSED_PIN,
.rst = 9,
.dio = {3, 8, LMIC_UNUSED_PIN},
};
This must be something to do with the library sharing ISRs.  Could somebody point to which parts of the LMIC library so as not to have this conflict?
I have tried swapping 8 for A5 and it again only works when the line is commented. Any help would be greatly appreciated.

I have managed to get it to work by specifying
#define EI_NOTPORTD however it does not work with  #define EI_ARDUINO_INTERRUPTED_PIN which is needed for my project to function.

This is the best I can get to work with 6 available pin change interrupts - just enough!
#define EI_ARDUINO_INTERRUPTED_PIN
#define EI_NOTPORTB  // DISABLE FOR LMIC
#define EI_NOTPORTD  // DISABLE FOR LMIC


text:
How to control Shift registers output individually bitwise
so i am working on a project which needs a lots of bit manipulation and shifting out the bits to control the pins of shift registers individually.
So i am using 2 shift registers daisy chained with 16 LEDS. Now, what i want is that, i want to control the LEDs individually just by shifting out the bits
here is what i tried
first Attempt
int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

byte leds=0b1000000000000001; // byte has 16 bits

void setup()
{

  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{

  updateShiftRegister();

}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);

   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

Does not work! the 2nd shift register seems to be copying the first shift register which i don't want
In second attempt, i tried the masking method with HEX data type.
Here is it.
int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

byte leds=0xFFFF & 0x8001; // used hex masking method

// 0xFFFF = 1111111111111111
// 0x8001 = 1000000000000001
// After & it should be 1000000000000001

void setup()
{

  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{

  updateShiftRegister();

}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);

   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

This too makes same effect like the attempt 1 above.
Now here is what i want and need...
byte leds = 0b1000000000000001

/* As you can see the index 0 and index 15 of the byte led
  is set 1 or high which should produce +ve to the 15th pin of first register and 8th pin of second register.

but whenever i try this, it seems that one of the register is copying another one.
So, is there any way to shift out bits to control the shift register outputs individually?
if yes then please give a clear example code with a clear explanation.
if no then, please suggest me some alternative ways which can be used in the same way i want , of course with example code and explanation.
Schematic: arduino.cc/en/Tutorial/Foundations/ShiftOut
Thank You so much for your precious time.
Looking forward to your replies .
:)

Please show how you connected the shift registers. If you really have two of them daisy-chained they can’t be copying each other. Also, you seem to shift out just 1 byte (8 bits). For 16 LEDs connected to two 8-bit shift registers, you need to shift out 2 bytes.

https://www.arduino.cc/en/Tutorial/Foundations/ShiftOut/ here you may find the schematic

Could you add that link to the question?

Ok added the link to the question through my mobile.

You have two problems with your code:

byte is equal to unsigned char and can only hold exactly one byte, aka 8 bits (not 16 bits like your comment says). But you are trying to assign a 16bit number to it. The upper 8 bits are cut out in that process. They are lost. If you want to hold a 16bit number, you need to use a data type, that is at least 16 bits in its size, for example uint16_t (or you can use unsigned int, though in such situations it is often better to use a type, which has the same size on all platforms).
  uint16_t leds = 0b1000000000000001;

The shiftOut() function has this declaration in wiring_shift.c:
  void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)

You can see, that val (which is the data, that should be shifted out) is of type uint8_t, the same as byte, which also can only hold 8 bits. The upper 8 bits of a 16bit value would be cut off and the function also just transmits 8 bits, nothing more (When you look at its implemention in the mentioned file, you will see a for loop with 8 as limit).
Instead you should call that function for every byte, that you want to transmit in a single transmission; 2 times in your case  because you have 2 shift registers.

So the resulting program would look something like this:
int latchPin = 4;   // Latch pin of 74HC595 is connected to Digital pin 5
int clockPin = 5;   // Clock pin of 74HC595 is connected to Digital pin 6
int dataPin = 3;    // Data pin of 74HC595 is connected to Digital pin 4

uint16_t leds=0b1000000000000001; // uint16_t has 16 bits

void setup()
{

  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{

  updateShiftRegister();

}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);

   // Shiftout lower byte by masking the other byte with bitwise AND (&)
   shiftOut(dataPin, clockPin, LSBFIRST, leds & 0xFF);
   // Shiftout higher byte by shifting the bit pattern 8 bits to the right
   // resulting in the high byte getting to the position of the low byte
   // and then masking away anything else than the new position of the high
   // byte data
   shiftOut(dataPin, clockPin, LSBFIRST, (leds >> 8) & 0xFF);
   digitalWrite(latchPin, HIGH);
}

Note, that the masking with the bitwise AND operator is not really necessary here, but I like to do such things explicitly to make it more clear.

So I need to store almost 50 bits in the variable to control the columns so can 'uint' method be useful in this case ?

In that case I would use a byte array to hold the data. With 50 bits you are at 6.25 or 7 bytes (since you cannot have sub bytes). The declaration would be something like this:
byte leds[] = {0b00011001, ... }; // list the byte data here

And then you can shift that out with a for loop:
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   for(int i=0;i<sizeof(leds)/sizeof(leds[0]);i++){
       shiftOut(dataPin, clockPin, LSBFIRST, leds[i]);
   }
   digitalWrite(latchPin, HIGH);
}

Note that sizeof(leds) will return the size of the leds array in bytes. I also divided through the size of a single element of the array to get the number of elements in the array instead of bytes. In this case this is the same, but since datatypes might change while the code progresses it is better to be save than sorry.

i tried the masking method with HEX data type.

The data, that comes out is the same. The Arduino only knows of binary data. It doesn't know of different representions (like binary, HEX or decimal). The compiler will already convert that to the target value. So for the Arduino both ways are equivalent.

Actually, i am working on a 50x8 dot matrix project and writing up the library on my own instead of copying anyone's code. So I need to store almost 50 bits in the variable to control the columns so can 'uint' method be useful in this case ?

Those 16 bits in the datatype byte is just a small example that I used to explain my problem

@SubhaJeetSikdar I added a paragraph about that at the end of the answer.

The function shiftOut() only works for 8-bit values, as its documentation says.
Additionally, a byte can only store 8 bits. It doesn't matter how many bits you try to assign. (The compiler should have given you a warning, but the IDE likes to hide this.)
You need to write your own output function to shift out 16 bits, AFAIK.


text:
Arduino and fingerprint scanner - can I get the fingerprint scanner data?
I am currently planning a thesis that involve scanning fingerprints and storing the data in a database. The problem is that I do not know if it is possible for me/us to get the fingerprint data or variables scanned by the fingerprint scanner.
I tried searching on google, of course, but I don't see any information on how to display the data in a form such as binary.  I'm not sure if I can extract the data from the Arduino then store it in a website/database (---which to be fair, since fingerprints can be confidential, I understand if some articles don't provide a sample.)
Is it possible to get and extract the fingerprint scan data? For example, converting the scanned data in to a binary representation (011010101 etc.)

What is the fingerprint scanner you are using? Of course it is possible to get fingerprint data since that's what the scanner is doing. It just might not give you the data if it's designed to be used as a pass/fail kind of device. Fingerprints are hardly confidential, you can record one with a camera or just a drop of wet ink.

I have 3 Products in my choices: AS608, R307  and this one
(https://shopee.ph/Fingerprint-Scanner-Reader-Sensor-i.18252381.1243862326?position=4&hybrid_pc=1&stm_referrer=https%3A%2F%2Fshopee.ph%2Fsearch%3Fkeyword%3Dfingerprint%2520arduino) sorry this one didnt write the product type.
i wonder what are suitable for the thing im looking for?

I'm a software engineer that works with biometric sensors. The answer is, it will vary greatly depending on the scanner you've chosen. Some hardware solutions have built-in subject enrollment and database matching; some simply collect an image and return it in an appropriate format- sometimes an image file (e.g. PNG), or a template file (a binary representation of a subject and/or their fingerprint(s)).
For you, I highly recommend avoiding the pain of interfacing with an Arduino at such a low level, and use a Raspberry Pi or other full computer to write a collection program with your vendor's SDK. Linux is supported by all the major players I've worked with, and that will drastically ease integration with whatever database or website you have in mind. Many vendors have built-in enrollment, storage, and matching examples as part of their SDKs that will help you get up and going in short order
EDIT: As this is an Arduino SE, I realize I should give a microcontroller-friendly answer as well. There are indeed scanners like this. It does templating and matching on board if I understand correctly, and the provided library does indeed allow you to transfer those templates over serial. Granted, you still have to get that data from your Arduino to a computer of some sort, so I still think a Pi is the shorter putt ;)

highly appreciated!
regarding to "some simply collect an image and return it in an appropriate format- sometimes an image file (e.g. PNG), or a template file (a binary representation of a subject and/or their fingerprint(s))." does the "template file" is literally different to each other. like my thumb left will have different template to right thumb? sorry i dont have Fingerprint scanner yet(but just like the sample, im planning to buy one like that). im curious a bit

If I understand what you are asking, yes, those two template files will be unique. As a matter of fact, even if you scan the same finger twice, the two resulting templates will be unique, like taking a picture of the same thing twice will make two slightly different pictures- it's up to the matcher to tell you if the two prints are "close enough" to be considered a match. How close is "close enough" will vary based on your desired false-positive and false-negative rates

It is also worth noting that "template" is a general term that means "a data representation of a fingerprint," and not a standardized file/data format. Each vendor has its own proprietary template format. If you don't mind me asking, what is your thesis trying to show, exactly?

in my thesis im planning to make. simply taking the template of the fingerprint. basically it is like a "registration system" similar to School Attendance System but unlike the regular thing you can see in youtube tutorial for beginners, what we are planning is to take the scanned fingerprint then convert it a template then store it online/database.
so for example, when a person is suspected for a crime. we can re-enter the fingerprint then determine it by matching the fingerprint.

but actually, the first pharagraph is the main objective. making a Matching System is not part of our scope but we would consider it since our Panelist/professor may question the quality of our way of getting fingerprint.

Sounds cool! Best of luck!

@DreacLeoson If this has helped you, can you mark it as the Accepted Answer? Much appreciated :)

There is a discussion thread on Quora discussing finger print scanners that provide raw output. The Quora author recommends a  Futronic device which comes with an API for raw image collection. They also discussed NeuroTechnology which apparently also has a downloadable image database. Looking at the neurotechnology website they also have some interesting SDK options. These of course all give you an image not the binary output you described.
It strikes me that a binary encoded output would likely be the result of a recognition algorithm, or a resultant / generated security key. Not sure that is what you intended by your question?
There are a mass of academic papers on open finger print scanning algorithms.
I did a bit of google searching for people capturing raw data from Arduino compatible devices. Didn’t find anyone saying it was easy. Please post back here if you make progress.
Hope this helps get you started.

Those information were so useful. thank you so much!

the "binary" thing is simple example of how can i convert it to a data since im not sure of how the data will be converted aside from .bmp. im not entirely hoping if i can convert it to Binary(but if it is possible, ill gladly to know/try)

You’re welcome @DreacLeoson. Remember to please  upvote the responses you find useful, and mark if a response answers your question ( I could use the reputation points :-)

will do. alhough i need more 15 reputation or higher. still, im going back here to report my progress. this is a good information actually!

So I upvoted your question, not only for the reputation, I
also find the subject interesting and thanks to Rowap for excellent research.

Echoing my comment on SO with more information:
Commercial fingerprint sensors like this one do local store and compare and do not expose the actual image or binary signature. What they transmit to the microcontroller are ID's and match success.
If you need the binary data of the image itself you may be able to write your own image processing algorithm, perhaps using machine learning, and use a simple video camera connected to a microcontroller that in turn will send the captured image to your web server for processing.
Arduino can be programmed to capture still images and transfer a bitmap file to a server, such devices (microcontroller and cameras) are widely available.

ahhh. thank you so much for your service. my bad this is just a copy paste from SO but still, thank you for directing me here. i thought Arduino Forum is the only existing QandA website for this. thank you so much!


text:
As a novice, how do I program my Atmega328p?
I bought a board which the above MCU is the atmega328p. Since I haven't used atmel MCU before, now it's a bit confusing. Are the ATMEGA and STM32 programmers not universal? What programming methods can this chip support? Is there serial programming or SWD programming? Need help. Many thanks!

"Are the ATMEGA and STM32 programmers not universal?" No, one is via ISP and the other one is SWD / JTAG, they are different. Most of the times the ATMega chip on maker boards comes preprogrammed with a bootloader that allows it to be flashed via serial (Optiboot). Using the Arduino IDE with the board "Uno" selected will work then. Otherwise, you need to construct a ISP programmer if you do not have one. See https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoISP.

I bought a board - which board? Link to it?

Are the ATMEGA and STM32 programmers not universal?

They are not the same. As far as I know their programming arrangements are completely distinct.

What programming methods can this chip support?

Traditional AVR In-Circuit-Serial-Programming (ICSP) using a 2x3 header pin connector and one of a variety of programmers such as the STK500 which has low-cost clones like the Pololu AVR programmer (less than $10). These programmers typically connect to a PC's USB port and can be used either with the software development tools from Atmel (now Microchip) or using the Arduino integrated development environment (IDE) which uses a program named avrdude to communicate with the ATMega328P (or other AVR family MCUs). ICSP is sometimes called In System Programming (ISP). It uses the MCU's SPI interface and you have to be careful what other circuitry is attached to those pins when you program the device.

Serial-port programming by communicating with a pre-loaded "bootloader" program installed in the ATMega328P. This is the normal way to use the Arduino IDE but it depends on having that bootloader installed. Most bare ATMega328Ps are sold without this bootloader installed. All "Arduino" boards will have a bootloader installed in their MCU and many will have a serial-to-USB interface on-board so that the board can be plugged in to a PC directly. Otherwise you would need a USB-to-Serial interface like the Adafruit FTDI friend or many others.

There is also a high-voltage programming method but that isn't something a novice would need to use. I believe it is most often needed when you have configured the MCU in such a way that the above methods cannot be used. For example after having disabled the reset pin so it can be used as an IO pin that can be pulled to GND without resetting the MCU.
You can use an Arduino to emulate a programmer and use that to program boards that lack a USB serial interface. This is called Arduino as ISP
Microchip's newer generation of AVR MCUs use a different programming method than ICSP called UPDI.

What programming methods can this chip support? Is there serial programming or SWD programming?

The Arduino IDE (a free download) supports programming in C++. The IDE pre-processes your code (which they call a "sketch") slightly but it is still C++.
You can drop into assembler if you absolutely must, but the C++ compiler does a good job of producing efficient code, almost always.
With the assistance of a serial interface (many Arduinos, like the Uno, have one built-in connected to a USB interface) you can quickly and easily upload your code. The wherewithal to do that is built into the IDE.