text:
Keypad - Speaker - Interference
I am trying to build a system, that plays specific audios (.wav files) from a SD-Card, according to the key combination that has been pressed.
I am using:

4x4 Membrane
4 Ohm Speaker
MicroSD Card Adapter Module
TIP120 Transistor (for amplification)
Arduino NANO clone (https://www.amazon.de/gp/product/B0755XYBG4)

So I broke the project down in various steps:

playing .wav file from the SD Card (works fine)
using keypad (works fine)
combinig both (as you may have guessed: does not work)

Here are the codes I used for every step:
1)
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup() {
  tmrpcm.speakerPin = 9;
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD fail");
    return;
  }

  tmrpcm.setVolume(5);
  tmrpcm.play("test.wav");
}

void loop() {}

This plays test.wav one time after uploading or resetting.
2)
#include <Keypad.h>

// Definition für das Keypad von Elegoo
const byte ROWS = 4; // vier Zeilen
const byte COLS = 4; // vier Spalten
// Symbole auf den Tasten
const byte rows[ROWS] = {2, 3, 12, 5};//connect to the row pinouts of the keypad
const byte cols[COLS] = {6, 7, 8, 11};//connect to the column pinouts of the keypad

char keys[ROWS][COLS] = { //create 2D arry for keys
  {'D', 'C', 'B', 'A'},
  {'#', '9', '6', '3'},
  {'0', '8', '5', '2'},
  {'*', '7', '4', '1'},
};

// Instanz von Keypad erzeugen, Keymap und Pins übergeben
Keypad customKeypad = Keypad(makeKeymap(keys), rows, cols, ROWS, COLS);

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

void loop() {
  // Gedrückte Taste abfragen
  char customKey = customKeypad.waitForKey();
  Serial.println(customKey);
}

This code prints out every pressed key.
3)
#include <Keypad.h>
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

// Definition für das Keypad von Elegoo
const byte ROWS = 4; // vier Zeilen
const byte COLS = 4; // vier Spalten
// Symbole auf den Tasten
const byte rows[ROWS] = {2, 3, 12, 5};//connect to the row pinouts of the keypad
const byte cols[COLS] = {6, 7, 8, 11};//connect to the column pinouts of the keypad

char keys[ROWS][COLS] = { //create 2D arry for keys
  {'D', 'C', 'B', 'A'},
  {'#', '9', '6', '3'},
  {'0', '8', '5', '2'},
  {'*', '7', '4', '1'},
};

// Instanz von Keypad erzeugen, Keymap und Pins übergeben
Keypad customKeypad = Keypad(makeKeymap(keys), rows, cols, ROWS, COLS);

void setup() {
    tmrpcm.speakerPin = 9;
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD fail");
    return;
  }
}

void loop() {
  // Gedrückte Taste abfragen
  char customKey = customKeypad.waitForKey();
  Serial.println(customKey);

  if (customKey == 8) {
    tmrpcm.setVolume(5);
    tmrpcm.play("test.wav");
  }
}

This code should play test.wav if key 8 is pressed.
THE PROBLEM
So the problem is not that there is no sound at all, but its just completely distorted. The sound quality never was great but sufficient. Now it sounds like "too much signal" is coming onto the speaker and interferes with the audio. Even if there shouldn't be any audio playing, machine-like sounds are produced by the speaker. By slowly working through the code I managed to find the line that probably causes the problem:
char customKey = customKeypad.waitForKey();
Serial.println(customKey);

If put it in a comment and put
tmrpcm.setVolume(5);
tmrpcm.play("test.wav");

in the setup function the audio is played.
I tried a lot and it doesn't matter where you put the getKey line (or change it to waitForKey()), as long as this line is somewhere in a function the sound is distorted.
Why does this happen? How can i work around it?
Can anybody please help me with this? :)
wiring diagram

Pins 11 and 12 are MISO/MOSI SPI pins, you're using them both for the SD card and the touchpad

Hm ok, so so you have a solution? I am running Out of Pins... Can I use a different wiring? What Others Pins could I use to avoid it?  And what about the Others digital Pins that have an additional SPI purpose? Are they a Problem as well?

You could probably use pins from A0 to A3 (or to A5 if you don't use I2C) https://electronics.stackexchange.com/questions/67103/can-i-use-the-analog-pins-on-the-arduino-for-my-project-as-digital

Thank you! You were right. Pins 11 and 12 interfered with the other SPI pins i used. I switched to A0 and A2 and now everything works perfectly.


text:
Line Following Robot using PID control not working
I'm currently making a line following robot using PID control. My robot uses an Arduino Uno board, a L298N motor, 1 9V battery, 2 motors, 5 TCRT 5000 infrared light sensors to detect a black line on a white surface. I uploaded the code successfully but my robot didn't do anything:

Both of my motors didn't run at all
the sensors couldn't detect the line. The sensors somehow could only detect the distance between it and the ground when i lift the robot above the ground.
The wire connections are fine.
When i used a multimeter to measure the voltage, I found out that there was no voltage from the L298N to both motors. The circuit diagram that i'm using:
[![enter image description here][6]][6]

And this is my code:
float Kp = 1;
float Ki = 1;
float Kd = 1;

//setup speed of the motors
#define ENAspeed 200
#define ENBspeed 200

#define ENB 5 // Enable pin PWM of the Left motor
#define IN4 6 // pin of left motor
#define IN3 7 // pin of left motor
#define IN2 8 // pin of right motor
#define IN1 9 // pin of right motor
#define ENA 10 // Enable pin PWM of the Right motor

int Sensor[] = {A1, A2, A3, A4, A5};
float P = 0;
float I = 0;
float D = 0;
int Error = 0;

int Previous_Error, Previous_I;
int PID_value;
int Left_Speed, Right_Speed;

void setup(){

     pinMode(9, OUTPUT);
     pinMode(8, OUTPUT);
     pinMode(7, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(10, OUTPUT);

     pinMode(A1, INPUT);
     pinMode(A2, INPUT);
     pinMode(A3, INPUT);
     pinMode(A4, INPUT);
     pinMode(A5, INPUT);

     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);

     analogWrite(ENB, Left_Speed);
     analogWrite(ENA, Right_Speed);

     for (int i = 1; i <= 5; i++)
      {Sensor[i];}
     // reading the sensor if HIGH (Black line) or LOW (White line) line
     Sensor[1] = digitalRead(A1);
     Sensor[2] = digitalRead(A2);
     Sensor[3] = digitalRead(A3);
     Sensor[4] = digitalRead(A4);
     Sensor[5] = digitalRead(A5);
}

    void loop() {
    //use analogwrite to run motor at adjusted speed
     CalculateError();
     Calculate_PID();
     motor_control();
}

  void CalculateError(){
  if ((Sensor[1] == 1) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 4;}
  else if ((Sensor[1] == 1) && (Sensor[2] == 1) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 3;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 1) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 2;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 1) && (Sensor[3] == 1) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 1;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 1) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {Error = 0;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 1) && (Sensor[4] == 1) && (Sensor[5] == 0))
  {Error = -1;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 1) && (Sensor[5] == 0))
  {Error = -2;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 1) && (Sensor[5] == 1))
  {Error = -3;}
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 1))
  {Error = -4;}
  //Special case
  else if ((Sensor[1] == 0) && (Sensor[2] == 0) && (Sensor[3] == 0) && (Sensor[4] == 0) && (Sensor[5] == 0))
  {if (Previous_Error = -4) {Error = -5;}
  else if (Previous_Error = 4) {Error = 5;}}
  else if ((Sensor[1] == 1) && (Sensor[2] == 1) && (Sensor[3] == 1) && (Sensor[4] == 1) && (Sensor[5] == 1))
  {Error = 0;}
}

  void Calculate_PID() {
    P = Error;
    I += Error;
    //I = I + Previous_I;
    D = Error - Previous_Error;

    PID_value = (Kp * P) + (Ki * I) + (Kd * D);

    I += Error;
    Previous_I = I;
    Previous_Error = Error;
}

  void motor_control() {

     //define new speed limitation for the engine
     Left_Speed  = constrain (Left_Speed, 0, 255);
     Right_Speed = constrain(Right_Speed, 0, 255);

     //calculating the effective motor speed:
          if ((-5 < Error) and (Error < 0)){
              Left_Speed  = ENBspeed - PID_value;
              Right_Speed = ENAspeed + PID_value;
          }

          if ((0 < Error) and (Error < 5)){
              Left_Speed  = ENBspeed + PID_value;
              Right_Speed = ENAspeed - PID_value;
          }

          if (Error == 0){
              Left_Speed  = ENBspeed;
              Right_Speed = ENAspeed;
          }
     }

Sorry for my bad English if there is any mistake. I'm quite new to Arduino and thanks in advance for your help.

9V battery ... if this is a regular block battery, then it is only good in very low current applications, such as smoke alarms

so should i use a 4 AA battery instead? Thanks for your recommmadation.

Both of my motors didn't run at all ... it is pointless to even look at your code ... first, make sure that you can control one motor ... write a simple sketch to run one motor, in one direction, for one second, pause one second, then repeat .... then run opposite direction .... then run two motors .... each time use a simple sketch that does only one thing ........ then move to sensors .... light up an LED to indicate that the sensor is detecting a line, nothing more ... when all components work, then move to combining the components

what voltage do 4 AA cells produce?

Yes, maybe i should slow down and try to do it step by step. 4AA cells if connected in series then it'll produce a 6V output. Is that the answer you're looking for?

i am not saying that you need to slow down ... i am saying that you need to test the hardware first ... at this point, you do not know if the problem is caused by hardware, or by software ... about the AA cells, i just qanted to make sure that you were aware of the voltage, because you said that you ate using a 9 V battery .... anyway, since you probably have everything connected, try replacing the battery before you start testing motors and sensors ... you may actually have everything already working, only power starved

LOL I guess problem solved. I did like what you'd suggested and turns out, the hardware, software, wire connections are fine. The robot doesn't move due to the 9V battery. The motors did spin but didn't provide enough force to move the robot. Thanks for your help, i'll use 4AA cells instead.

source: Stack Exchange

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

sort: votes


text:
Converting c string to integer to unsigned char
I'm grappling with types between two different libraries.
The gist is that I'm using the ArduinoWebsockets library to receive information coming from my API that I then want to render out to an LED matrix. An example message would look like this:
1
2
4
8
16
32
64
128

It's important to point out that the data here is a list of string version of numbers, not integers.
I.e. if you look at the binary version of 1 from the list, it's actually 110001 which is the ASCII code for the character 1.
This is because the message coming back from the websocket server is pulled out as a const char *.
The LED matrix function I'm calling has a signature of:
void Write_Max7219(unsigned char address, unsigned char dat)

So I need to send in the values as unsigned chars.
I want to:

parse this information line by line
convert the ASCII character for the number into its integer equivalent
pass the value to a different function to write the data to an LED matrix

I'm not sure how exactly to do this. I've been grappling with the type const char pointer vs regular char pointer and how to properly parse the return delimited string.
Any help would be greatly appreciated!!
Clarification
Based on some of the comments I don't think I explained the reason I'm trying to do this conversion very well. Here's (hopefully) a better explanation:
The reason I want to convert it is because I'm not displaying the number character as a string, I want to use the binary representation to control the lights in a row of the matrix.
The number 1 or 0b00000001 would light up only the rightmost led on the 8 led row of the matrix.
The idea is that I could send over rows of numbers where each row corresponds to the row on the LED matrix.
e.g.
1   -> 0b00000001
2   -> 0b00000010
4   -> 0b00000100
8   -> 0b00001000
16  -> 0b00010000
32  -> 0b00100000
64  -> 0b01000000
128 -> 0b10000000

But the messages I get from the websocket server are coming through as the string representations of the numbers (ASCII or UTF) vs the numbers themselves, so I can't just pass the numbers into the function for the LED matrix because the underlying binary is different.
The conversion is so that I can use the binary representation of 1 (0b00000001) vs the binary representation of '1' ( 00110001).
UPDATE AND RESOLUTION
So I've been on a big troubleshooting journey. When @ocrdu said:

BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

I thought "yeah, that's the real way of fixing it and understanding what's going on", so I started tracing the issue back. Without going into all of the detail it turns out that the problem I was having was actually starting at the test client.
I use firecamp and websocat as websocket client testing tools. I was trying to send the binary data via both tools, but when I dug in via Wireshark I found that the data in flight coming from the client itself was made up of the hex values for the encoded characters of the 1s and 0s.

After researching and asking a separate stackoverflow question I figured out a way of sending the actual binary data from the client, specifically printf.
e.g.:
 printf "\x01\x02\x03\x04\x05\x06\x07\x08" | websocat -b ws://localhost:3002

Now that this works I can start going back through the rest of my Arduino code and have it parse the binary data directly instead of converting the encoded values to their binary counterpoints.
All of that said, I do appreciate all of the help. I may not have needed to do the conversions for this particular instance, but I want to get better with my C types, conversions, and general understanding so the knowledge gained here is still beneficial. Thanks everyone :bows:

ASCII code is represented by one byte, which is 8 bits, not 6 bits

it is unclear why you need to convert the ascii character to a number before displaying it

point 3 is 'void' unsigned char is one byte and your bit mask values fit into one byte.

(char) strtoul(strData)  http://www.cplusplus.com/reference/cstdlib/strtoul/

Awesome, thanks @dandavis I'll give that a try.

@jsotola re: ascii byte length: I know it's 8 bits, I typed out the ascii without leading zeros. The reason I want to convert it is because I'm not displaying the number character as a string, I want to use the binary representation to control the lights in a row of the matrix, so 1 or 0b00000001 would light up only the rightmost led on the 8 led row of the matrix. The conversion is so that I can use the binary representation of 1 (0b00000001) vs the binary representation of '1' ( 00110001)

Not sure if or why you want to convert char* to int, but if you need to, there are atoi(), atol(), strtol(), strtoul() to consider, or rolling your own function.
Pros and cons are discussed here. Main thing to note is that atoi() and atol() have no error handling, but if the char* you feed them is completely under control and predictable, that need not be a problem.
BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

a nice thing about atoi() is that it stops at non-digits, so your input can be "dirty" as long as starting with numbers, which makes it nice for using with existing string pointers instead of a small chopped-out char arrays.

I think this may be the solution. I have more detail but I have to wait till after work to update the question.

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


text:
Which relay module to buy and what is the difference between 1 channel and 2 channel relay boards
I wanted to d a simple circuit using Arduino to control the lights in my house. But i do not know which relay module to use my house runs on standard 220v ac.
Can anyone tell me weather this relay board will be enough
https://www.roboelements.com/wp-content/uploads/2018/10/1-Channel-5V-Relay-Module-for-Arduino-with-Optocoupler.jpg
Or should I buy a 2 channel one?
And another thing what is the difference between 1 channel and 2 channel relay board.
I'm a complete beginner, so please help me out.

A 1-channel relay board can switch one load, a 2-channel relay board can switch two loads independently. I don't want to sound patronizing but it looks like you have little experience with mains voltage. Please be very, very careful!

Yes, you can use those. You have to watch a few things:

Input voltage: 5V, perfect for Arduino
Output voltage: 220 V, perfect for 220V AC
Output amperage: 10A, what you control should use max 10 A, and I would use max 5A, and also consider switching on current into account. However, 10A is a lot of current.

The difference between 1 and 2 channels relay boards, is just that there are either 1 or 2 of them, meaning you can control 1 or 2 motors independently from each other.

really helpful ;))

Good luck with your project


text:
What are the Arduino hardware options for experimenting with IoT?
Just starting to learn about Arduino and IoT. I'd like to know what the Arduino hardware options are to try the following:

Use FreeRTOS as SO
WiFi and BLE connectivity
Solderless board
Test OTA features
Experiment integration with different IoT Cloud platforms e.g. Azure IoT Hub
Build custom IoT devices

an opinion based question, but ESP32 is the answer

One of the options for closing a question is that it's "opinion-based" and you're asking for what "is best".  Without any criteria on what you mean by "best" it's difficult to say that the question won't get closed for that reason.

Thank you @Juraj and @ timemage for your comments! Both of you are precise on the option-based question. The reason is that as there are so many options available at the Arduino store am not clear which of them would allow me to do all the above.

There are many options; which one is "best" for you I leave up to your own research, that could start here:
There's a list of Arduino's based on the SAMD21 that are supported by the FreeRTOS_SAMD21 library here; pick any one with WiFi and BLE.
There are probably a zillion clones out there that could also do what you want, and there is also a FreeRTOS port for the ESP32 (ESP-IDF FreeRTOS, and maybe other ones as well).

Thank you @ocrdu

You are welcome. Please accept the answer (if you accept the answer) so the question doesn't stay open.


text:
Arduino - ServoMotor Control and SoftwareSerial
My two arduino communicating serially with XBee. The receiver arduino also controls the servo motor. Servo works stably when there is no xBee connection. But when Arduino's serial communication, there is a problem in the operation of the servo motor. Servo motor stuttering while rotate, so stuttering occurs.
Can you help me?
My Coordinator Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
String d1,d2,d3;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  Serial.begin(38400);
  xBeeSerial.begin(38400);
}void loop() {

  deger3 = analogRead(A0);
  deger4 = analogRead(A2);

  String deger5 =  (String)deger3 + ";" + (String)deger4 ;

  xBeeSerial.println(deger5);

  delay(50);
}

My Receiver Code:
#include <SoftwareSerial.h>
#include <Servo.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1,d2,d3;

const int trigPin = 4;
const int echoPin = 3;
long duration;
int distance;
Servo myServo;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  xBeeSerial.begin(38400);
  Serial.begin(38400);
  myServo.attach(11);
}
void loop() {
  for(int i=15;i<=165;i++){
    myServo.write(i);
     delay(10);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, 11200);
    distance= duration*0.034/2;

    if(xBeeSerial.available()>0){
      d1=xBeeSerial.readString();
    }
  }

  for(int i=165;i>15;i--){
    myServo.write(i);
     delay(10);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, 11200);
    distance= duration*0.034/2;

    if(xBeeSerial.available()>0){
      d1=xBeeSerial.readString();
  }
 }
}

What exactly is this "problem in the operation of the servo motor"? Please edit that into your question.

I arranged. Stuttering.

When SoftwareSerial enters an interrupt each time it receives a character and busy-waits (delays) to time in each data sample as the bits in the character come in.  No other interrupt service routines can run while this is happening.  It also turns off interrupts when it sends.
The servo library for the AVR uses timer interrupts to generate the servo position signals.
When characters are being received, SoftwareSerial will interfere with the generation of the servo position signal because only one interrupt service routine can run at a time.
You may be able to mitigate the problem adding significant delay between characters sent, reducing the total number of characters sent.  This would limit the interference and give servo time to get back to its correct position from however far it managed to deviate over the course of an inbound serial character.
There are also alternative libraries that use the AVR's Input Capture feature on an ICP pin to do some of the work of serial in hardware, and that may work for you.  Here's one example library.
@ocrdu has rightly prompted me to add that there are servo libraries that will do the servo signal generation in hardware.

I removed some material regarding I2C/Wire because this was probably completely useless advice with XBee being involved.

Maybe a servo library that doesn't use interrupts can be found also?

Yeah, I had a thought to add that, but don't off-hand know of one. If you have a recommendation I'll put it in, or if you put one in a separate answer I'll up-vote it.

Perhaps I'll add in https://www.arduino.cc/reference/en/libraries/servo-hardware-pwm/   if you add an answer, I'll remove it and specifically call out your answer.


text:
Recognize peak in specific frequency area
I am wondering if it is possible to attach a microphone to an Arduino board and make the Arduino recognize a volume peak in a specific range of frequencies.
I want it to detect a specific peak (for example 0,1 dB) in the range of 1000 hz to 5000 hz.

You can filter the signal and look at the power that lies within the
frequency range you are interested about. You could use an FFT for that,
but it is quite computationally expensive. If you go for the FFT, you
would probably end up sampling the mic in small bursts (a few
milliseconds sampled every few tens of milliseconds), as the Arduino
would spend most of its time processing the data.
A better option is probably to work in the time domain, rather than the
frequency domain. If you do not need to know exactly how much power lies
in each frequency bin, and are only interested in the total power within
the window of interest, then the FFT is computing too much stuff you do
not need. A less computationally expensive option would be to run the
samples through a digital band pass filter tailored to the band you
want. You can then compute the power from the output of the filter and
low-pass it:
raw_sample = sample_the_microphone_somehow();
filtered_signal = bandpass_filter(raw_sample);
instantaneous_power = filtered_signal * filtered_signal:
smoothed_power = low_pass_filter(instantaneous_power);

But you would still need a beefy Arduino if you want to be able to
acquire and process the samples at a reasonable rate: at least twice the
highest frequency that comes out of the microphone.
A still better option could be to do the filtering in the analog domain,
before the signal reaches the Arduino. If you can at least remove the
frequency components above 5 kHz, then the Arduino would only need
to sample at 10 kS/s, and run a digital high pass filter to remove
the part of the signal below 1 kHz. This should be easy enough even
for an AVR-based Arduino.
For the implementation of the filters, you may want to try this online
filter builder

An alternative to the FFT is the Goertzel algorithm. It is intended to only detect a single frequency, so may not suit your purpose of working with a range.
But it may be more practical and require less intensive processing. Although intended to only detect a single frequency, it will of course give results near a given frequency, depending on the sampling rates and detection thresholds.
I have previously used an Arduino Goertzel algorithm library, but there doesn't appear to be anything available through the Library Manager at the moment; a web search shows some hits though.
The beauty of the Goertzel algorithm is that it only needs to keep a small amount of data in memory, so may have some benefit on smaller processors over more data intensive techniques like FFT.
I would try implementing one or more Goertzel detectors across your range (eg one at 3kHz or two at 2kHz and 4kHz) to see if they are sensitive enough.

You could sample the sound from the microphone and then apply a Fast Fourier Transformation (FFT).
An FFT lets you decompose a sequence of samples into components of different frequencies, usually into "buckets" that each have a small frequency band. You can then have a look at these buckets to see if there is a peak in a specific frequency range.
There are several examples and libraries for this on Arduinos, like EasyFFT and arduinoFFT.
PS. Edgar Bonet's answer is better; I may have become a bit lazy at coming up with computationally efficient ways of doing things because of my using "beefy" Arduinos exclusively.


text:
LCD 16x2 shows one line cut and the 7th column also cut
My 16x2 LCD shows one line cut and the 7th column also cut:

Applying pressure:

What happens if you gently push down around the outside of the LCD display?

Push down means

Quite literally apply some pressure with your fingers to the black part, pushing it toward the PCB board while displaying your message.

Yes I apply some press on screen but not completely show all character

It's not conclusive, but it is a strong indication if it causes some of the segments to show that were otherwise not showing.

Ok i will try tell what happen

Thanks you very much

It's Work!!!! Thanku Sir

My LCD module looks so similar to yours I decided risk to taking it apart for the purposes of taking pictures for to go along with the description.  It went back to together fine.
The black part I suggested pushing down on I'm going to call a "bezel", even though I'm not sure that's technically the correct term for it.
The pink color showing between the PCB and bezel is probably a "zebra strip" or elastomeric connector.  They conduct signals from LCD controller mounted on the PCB up to the LCD glass itself.  Sometimes they don't make good contact and so some segments of the LCD don't respond or respond poorly.  They may make better contact when you apply pressure to them.  If some or all of the segments start responding when you do that, it's a fairly good indication that this is a problem, though not an Arduino problem as such, it's a problem encountered with some frequency by Arduino users.
If you may need to replace the strips, or clean them, or adjust the bezel to apply more pressure to them.  Or just get another LCD module.
Back of one of my LCD modules that looks a lot like yours:

If you look at the back side of the board you may find that you can unclip the bezel; though it could also be soldered or glued etc.  If/when you do unclip it, the zebra strips and LCD glass will probably come free, perhaps with polarization filters as well.  You'll want to pay attention to the orientation of the everything so you know what you're doing when you put it back together.
I unclipped my the bezel on mine and the zebra strips (pink; they're not always pink) stayed with it. It is no so easy to see the "zebra" pattern on these particular strips.  Often they more alternating gray/white pattern.

Here's the PCB showing the contacts that the zebra strips mate to an the LED backlight spreader. Apologies for the dust.

The strip pattern is a little easier to see in this image.  You can also see the pattern of the conductors on the LCD glass.

You can try cleaning the strips and the glass and PCB where the make contact.  I would be careful what you clean with; look for trustworthy recommendations. In any case, keep your finger grease off of everything, either by using gloves or just washing and drying your hands before working on it.


text:
WiFi101 vs WiFININA - reliability issues
I've got the same code running on 2 different boards:

MKR1010
Adafruit Feather M0

I'm using WiFiNINA on the former, and WiFi101 on the latter.
Other than that, the code that's exactly the same: every 10 seconds connects to WiFi, sends an HTTPS Request, and then sends a response back to the server (response is a bunch of metrics: memory, counter, time & day).
I am also using a WDT to reset the board if it hangs.
After a lot of refinement and experiments, the Adafruit board is able to run for days with no hangs (indicated by no WDT triggers), and no visible degradation (e.g. memory stays stable over time).
The MKR1010 board, on the other hand, resets several times per day.
What I've done?
I've been able to narrow down issues to the network stack (I think). I've randomly injected a bogus hostname to the WiFikSSLClient::connect method (e.g every n calls, where n is random,  I will switch the real hostname with something that will not resolve, simulating a longer latency).
In reviewing the WiFi101 codebase I've found a long, hardcoded, non-customizable timeout here.
...
while (_info[sock].state == SOCKET_STATE_CONNECTING && millis() - start < 20000) {
        m2m_wifi_handle_events(NULL);
    }
...

20 seconds is greater than the max WDT timeout (16 seconds). You can argue that for network operations, 20 seconds would be reasonable, but I'm expecting connections in my network to happen much faster, so I tweaked the library (WiFi101) to 10 seconds and the reliability increased significantly. Every once in a while I get a connection error, but that is fine. The system recovers nicely on the next attempt.
I have not been able to find similar timeouts in WiFiNINA (looks like a much more complex codebase too, but that is my first impression. I'm not an expert)
If I disable the WDT around the connect method, then the MKR1010 will hang after some time. If I leave it, it will recover through a WDT reset.
I'm making sure the firmware on both boards is up to date.
While the WDT solves the issue of ensuring the board recovers, I'd love to fix it properly.
Questions

Is this consistent with anyone's experience?
Are there alternatives to WiFiNINA for the MKR1010?
Is there something obvious I'm missing when configuring the WiFI stack (e.g. a timeout someplace else)?

I'm a bit lost here: you say you have a problem with the MKR1010/WiFiNINA combination, and changing a time-out in the WiFi1010 library helps?

Thanks @Juraj for the edits, good catches! ocrdu, sorry I wasn't clear enough. In a nutshell:

MKR1010 + WiFiNINA  -> not reliable
Adafruit Feather M0 + WiFi101 -> reliable (once I changed the library timeout to 10s)

Could this be the same problem as described here? https://github.com/arduino-libraries/WiFiNINA/issues/103


text:
How can I control blinking of LED while in timer function?
When I am in the 30-second standby function, I want to turn the LED on and off at 5-second intervals.
How can I do what I want using the read_counter() function?
The problem here is that I am already in the timer function with the read_counter() function.
void wait_function() {
  timer_init();
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
  }
}

Note: The read_counter() function increases every 1 millisecond with ISR COMPA vector. I tried many times and couldn't find a stable solution. Example:
if (read_counter() % 1000) PORTB^=(1<<LED);
Update: My new code :
while((TIFR1 & (1 << OCF1A))==0) //4secondIf I do this cycle 8 times, it
                                 //makes 32 seconds.
            {
                if(TCNT1%15624==0) //per 15624=1 second,
                PORTA^=(1<<0);
                 //led_blink_1s
            }

But,it doesn't work.Should I use util delay function?

count six 5 second intervals .... this does not fully describe how the LED is to flash turn the LED on and off at 5-second intervals

this is not a question about arduino software or hardware so off-topic

if (read_counter() / 5000 % 2) PINB^=(1<<LED);

i updated my code but it doesn't work right.

Your waiting loop runs much faster than once per millisecond, and even faster per second. So to get just one "event" per second, you need to detect the change of the second.
void wait_function() {
  timer_init();
  for (int second = 0; second < 30; ++second) { // 30 second wait
    // Wait for the next second
    int old_second = read_counter() / 1000;
    int new_second;
    do {
      new_second = read_counter() / 1000;
    } while (new_second == old_second);

    // A LED blinking at 1 second intervals
    PORTB ^= 1 << LED;
  }
}

However, you may think about refactoring your timer. You can put the division in the ISR, and then set a flag if a second has past. In your waiting loop you could wait for the flag, reset it, and toggle the LED.
EDIT:
If you have your (pseudo) code like this:
while (!timed_out) {
    if (timer % ticks_per_second == 0) {
        do_something();
    }
}

you will have the following erroneous behavior, presumed that the loop runs 1 million times per second and the timer increments 20000 times per second.

The timer starts at 1000, for example, and has just incremented.
The loop runs for 50 times until the timer increments to 1001.
This happens repeatedly until the timer gets 20000, which will be after (20000 - 1001) * 50 = 949950 loops.
Now the loop will run for 50 times, while the timer is still at 20000.
The condition is true on each repetition, so do_something() will be executed 50 times in a row.
Next, the timer increments to 20001, and the condition becomes false.

This is exactly what you observe: If the condition of the if becomes true, its statement will be executed repeatedly.
Because the relation between the loop's repetition frequency and the timer's frequency is not the presumed value (but similar) and even depends on the instructions executed, the state of the output is subjectively random. If the XOR instruction is executed an even number, the LED does not change, and if it is executed an odd number, the LED changes.

i updated my code but it doesn't work right.

You still have the same error: While the while loop is running, the condition of the if will be true many times each second.  Just as a guessed number, let's say the loop runs 1 million times a second. The condition TCNT1%15624==0 will be true for about 60 times in sequence each second. Additionally, TCNT1 will overflow on 65535 to 0.

My solution:
uint16_t st_led=0;
  uint16_t et_led=0;

    while((TIFR1 & (1 << OCF1A))==0) //30 second
    {

      st_led=TCNT1;
      et_led=st_led;
      while((et_led-st_led)<=15624) //1 second
      {
        et_led=TCNT1;
      }
      PORTA ^= (1<<ledno);
    }
    TIFR1=(1<<OCF1A);
    TCCR1B=0;

If read-counter is already incremented once a millisecond, use that to time your LED flashes:
void wait_function() {
  timer_init();
  bool LED_State = LOW
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
    if (read_counter % 1000 == 0) { //Switch 1000 to 500 here if it flashes too slowly
       LED_State = !LED_State;
       digitalWrite(LEDPin, LED_State ? HIGH : LOW);
    }
  }
}

That code will turn the LED on for one second, then off for one second, etc. (For a total cycle time of 2 seconds.) If you want the full on-off cycle to last 1 second, lower the if statement's value from 1000 to 500.


text:
ATtiny85-DHT11-TM1637
I have tried many combinations and I can get the Attiny85 to display on the TM1637 just fine, but I cannot get ant readings from the DTH11, tried different pins, libraries. I upload code via UNO as isp and that works fine. Tried same code on UNO and it works.
This is my first question on here, I usually figure things, but also first ATtiny85 adventure.

#include <TM1637Display.h>
#include "DHT.h"
#define CLK 4
#define DIO 3
#define DHTPIN 2  //
#define DHTTYPE DHT11
int MTD (2000);
TM1637Display display = TM1637Display(CLK, DIO);
DHT dht(DHTPIN, DHTTYPE);

const uint8_t celsius[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_D | SEG_E | SEG_F
}; // oC
const uint8_t Fahrenheit[] = {
  SEG_A | SEG_B | SEG_F | SEG_G, SEG_A | SEG_E | SEG_F | SEG_G
}; // oF
const uint8_t Humidityh[] = {
  SEG_B | SEG_C | SEG_E | SEG_F | SEG_G, SEG_C | SEG_D | SEG_E | SEG_F | SEG_B
}; // HU

void setup() {
  dht.begin();
  display.setBrightness(7);
}

void loop() {
  delay(1000);
  float Humidity = dht.readHumidity();
  float TemperatureC = dht.readTemperature();
  float TemperatureF = dht.readTemperature(true);

  display.showNumberDecEx(TemperatureF, 0b10000000, false, 2, 0);
  display.setSegments(Fahrenheit, 2, 2); delay(MTD);
  display.showNumberDecEx(Humidity, 0b10000000, false, 2, 0);
  display.setSegments(Humidityh, 2, 2); delay(MTD);
  display.showNumberDecEx(TemperatureC, 0b10000000, false, 2, 0);
  display.setSegments(celsius, 2, 2); delay(MTD-1000);
}

Found <TinyDHT.h> and all works ok, just what I wanted.


text:
Rasberry Pi Controlling Arduino - Reads "Ghost" Input - Doesn't Complete Logic Loop
I am using an Arduino Atmega2560 clone, I have used it many times before with satisfactory results - although I haven't used it with my Rpi before.
My Raspberry Pi is model 4 (B I think?).
#define knap 49
#define motorOutput 8

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(knap, INPUT);
  pinMode(motorOutput, OUTPUT);
  digitalWrite(motorOutput, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  int knapSensor = digitalRead(knap);
  Serial.print(knapSensor);
  if (knapSensor == 1) {
    int knapSensor = digitalRead(knap);
    Serial.print("aktiveret");
    digitalWrite(motorOutput, HIGH);
    delay(500);
    digitalWrite(motorOutput, LOW);
  }
}

Now I have double checked, the motor and the button is wired correctly. There is no hardware issue, aside from the cables being sh- quality.
Problem is, whenever I run this program two things will happen;
Either it starts fine by displaying "0000..." on the serial monitor.
Then when I press the button it goes to
"AktiveretAktiveretAktiveret..." even when I depress the button.
Or, it will just display "AktiveretAktiveretAktiveret...".
In either case the motor won't work.
Once again, I have done tests where I have removed the power from the breadboard and replaced the voltage pin for the motor with the voltage pin leading from the button.
First thing didn't change the input (i.e still "AktiveretAktiveret,") the latter started the motor.
I.e this isn't about bad wiring.
EDIT:
Added schematics and changed the code

checked, the motor and the button is wired correctly ... how do you know?

I strongly suspect a hardware issue. How are you providing power to the Mega2560 and the motor? How are you controlling the motor and how is the button wired (pulldown)? You are aware that, with the code you've shown, once you activate the motor output, it will never turn off?

Please show your wiring. You say the wiring is not bad, but we'll be the judge of that, not you.

Alright, I have added the schematics now.

@StarCat4 Wouldn't it change once the button reads nothing?

You set the motorOutput to HIGH when you detect that the button is pressed, bu you do not set it to LOW again when it is released. So it stays HIGH.

There's also nothing to pull the button output to LOW when the button is released so it is very vulnerable to noise. You should put a pulldown resistor of around 10K Ohms between pin 49 and ground to make the button more reliable.

@StarCat If I connect the button to ground won't it create a short circuit? How do you mean connect 10K ohms between pin 49 and ground?

See here The resistor needs to be between the button input pin and ground to give it a defined value when the button is released. The resistor to ground will make sure the pin reads "low" when no button is pressed. When the button is pressed, it will be connected directly to +5V and will read high. Only a small current (0.5mA) will flow from +5V to ground through the 10K Ohm resistor in that case. It will not create a short circuit.

@StarCat Thanks! It works great now! If you want to, you can post your comment as an answer and I will accept it.

I've made my comment into an answer. Good luck with your project!

Your button needs a pulldown resistor to work reliably.
See the discussion and solution here
The resistor, with a value of around 10K (but any value between 3K and 20K will probably do), needs to be between the input pin or your Arduino and ground to give it a defined value when the button is released.
Putting a resistor between the Arduino pin and ground will make sure the pin reads "low" when no button is pressed. When the button is pressed, it will be connected directly to +5V and will read high. Only a small current (0.5mA) will flow from +5V to ground through the 10K Ohm resistor in that case. It will not create a short circuit.

What motor are you using? If it works straight from the 5v but not from a GPIO, it could be an issue of insufficient power.
As @StarCat4 mentioned, you also need to add a digitalRead inside your while loop if you want the motor to ever turn off.

Well, the problem here is, that it doesn't even read the inputs correctly. So regardless of the motor, it still won't function.

It reads when you press the button in, correct? You'll never see a state change after pressing in the button because you haven't instructed the Arduino to look for it. Even if you release the button, the Arduino does not know to check state. Your while loop should read while (knapSensor == 1){  Serial.print("aktiveret");  digitalWrite(motorOutput,HIGH);  delay(500);  knapSensor = digitalRead(knap); }

Oops, forgot to edit the code.
It will occasionally print out "Aktiveret" and then go "0000...." i.e "000001Aktiveret " is the default pattern, when I am not pressing the button.
When I press the button it will go complete "00000".


text:
Can't stop SG90 spinning
I have a SG90. I just want it to spin 360° and stop, that's about it. This seems impossible.
I have tried the sweep example:
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

This works fine.
I read somewhere that for 360 motors the variable in myservo.write() is actually just the speed. So I tried:
void loop() {
    myservo.write(0);              // tell servo to go to position in variable 'pos'
    delay(2000);                       // waits 15ms for the servo to reach the position
    myservo.write(180);              // tell servo to go to position in variable 'pos'
    delay(2000);
    myservo.write(0);              // tell servo to go to position in variable 'pos'
}

The motor rotates several times then spins the other direction and repeats doing this.
What do I need to do to make it complete 1 rotation and stop?

TL;DR: Can't be done.
On a servo modified for continuous rotation, the signal you send sets direction and speed, not rotation angle. You can stop it, but you can't set an angle.
The sweep example will turn a continuous rotation servo in both directions, but I doubt it hits the angles you send it; it will just adjust speed and direction.
Without external hardware and feedback, like a limit switch, or a rotary encoder, there is no way of knowing what angle the servo is at, and no way to rotate to exactly 360° other than experimenting and "guessing" based on time and rotation speed.
You can then stop it by setting it to the PWM value for 90° or center position, which should set the rotation speed to 0.
On a servo, you can't have both continuous rotation with a set speed, and a set angle of rotation, without extra hardware.
Maybe a stepper motor would be a better choice for your application, or a "normal" servo with a gear that gives you the required rotation range.

A dc motor might be better. I just need to turn an auger once. I can add a limit switch, not sure how I would implement this to stop the servo?

You would need a pin on the axle that hits a switch. Could be awkward. You could also use a regular servo (non continuous, 0°-180°) with a gear on it to get 360°, or look into sail winch servos. Don't forget to accept the answer (if you accept it).

A value near 90 will make your rotating servo stop. Try 89, 91 etc. until you find it.
If you are running an auger, use a microswitch that pulses once per revolution. Starting at the point where the switch makes contact, run the servo until the switch opens and closes again then stop. You have made one revolution.


text:
rfm69 on M0 Express... init() doesn't work
I have already connected succesfully the rfm69 on my Feather M0 Express... but I cannot do it again.
The connections are (in the order of the rfm69):

Vin -> 3V
Gnd -> Gnd
En  -> (nothing)
G0  -> 9
SCK -> SCK
MISO -> MI
MOSI -> MO
CS  -> 10
RST -> 6

The code of the setup is
#include <SPI.h>
#include <RH_RF69.h>

#define RFM69_CS      10
#define RFM69_INT     9
#define RFM69_RST     6
#define LED           13

// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);

void setup()
{
  Serial.begin(9600);
  while (!Serial);

  Serial.println("Feather RFM69 RX Test!");
  Serial.println();

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if (!rf69.init())
    //***********************************
    Serial.println("init failed");
  else
    Serial.println("init ok");

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
  // No encryption
  if (!rf69.setFrequency(434.0))
    Serial.println("setFrequency failed");
  else
    Serial.println("setFrequency ok");

  // If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
  // ishighpowermodule flag set like this:
  //rf69.setTxPower(14, true);

  // The encryption key has to be the same as the one in the client
  uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
  rf69.setEncryptionKey(key);

#if 0
  // For compat with RFM69 Struct_send
  rf69.setModemConfig(RH_RF69::GFSK_Rb250Fd250);
  rf69.setPreambleLength(3);
  uint8_t syncwords[] = { 0x2d, 0x64 };
  rf69.setSyncWords(syncwords, sizeof(syncwords));
  rf69.setEncryptionKey((uint8_t*)"thisIsEncryptKey");
#endif
  Serial.println("Fin du Setup");
}

But during the execution, the program stops at //**************************
I do not understand.
Can somebody help me?
Thanks a lot and merry Xmas

To be clear, you are seeing "init failed" printing and then no further output on the Serial Monitor, is that correct?

The "init failed" do not appear. Everything stops at "//******".
I have compared to another RFM69 program.
I have added a line " digitalWrite(RFM69_RST, LOW);" at the begining of the "//manual reset" and it works now.
the sequence
digitalWrite(RFM69_RST, LOW);
digitalWrite(RFM69_RST, HIGH);
delay(10);
digitalWrite(RFM69_RST, LOW);
seems to be more efficient.
... it remains a few mysteriuos for me.
Thank you

You should be able to mark your answer as accepted.

Sorry, I do not understand what you mean... it seems thus I am not able to do it. I almost never use forums.


text:
Problems in calculating and printing long unsigned integers
I have this code which provides an erroneous unsigned long number.
CODE:
char buff[100];

int unsigned long bytes;

bytes = 48 * 70 * 144;

sprintf(buff,"%lu bytes\n", bytes);

BTPort.print(buff);

OUTPUT:
20088 bytes
BUT: The correct value is 483840

This is because the default numeric type is int, which on Arduino is just 16 bits (and signed).
So 48 * 70 * 144 is 0x76200 in hex, which truncated to 16 bits is 0x6200, or 25088. This calculation is done by the preprocessor, not the compiler, so doesn't know (or care) about the destination variable type.
You need to force the values to be calculated as unsigned long by appending UL to them:
bytes = 48UL * 70UL * 144UL;

Thank you for your time, this was extremely useful.

It's even sufficient to force one of the values to be unsigned long. bytes = 48UL*20*144;


text:
seeeduino can-bus shield v2: can't read can bus and write on SD card
I'm using a seeeduino V4.0 and a CAN-BUS shield v2.0 with industrial grade SD card.
I'm using the default library given by the wiki of seeed.
I've simulate a can bus with two mcp2515. I can read it without trouble and everything is fine.
I can write/read on the SD card with the exemple given in the SD library.
But when I use this example, the can bus and SD card start without error. The can bus read normally and show the can bus data. But when I read the SD card, the file is created but completly empty.
I've tried to modify to write on a .txt instead of .csv and when I try a
myFile = SD.open("test.txt", FILE_WRITE);
if (myFile)
{
  ...
}
else
{
  Serial.println("error: file not reachable");
}

The "myFile" return false.
ps: I don't ask a lot of question here. Sorry for bad formating my question.

I don't have any good ideas, so here's one bad idea: print something showing that it made it to myFile.close();  You may not have any writes until you close(), flush(), or fill a sector.  Given what you've shown and what I've read about the shield etc, it seems like this shoudn't be a problem though.  Which Arduino are you using?  You did not change the CS selection on the board right?

I got the same "bad idea" but even with the close() (and withouthe the if(myFile)) The SD card don't write anything. If I process to write before using MCP2515, it works fine.
It look like a problem with the ISP to determinate the slave to talk to.
My board is a seeeduino V4.0

That is more or less what I think, but I didn't find anything confirming that when I went looking through the code of the two libraries.  At some point I may try setting up an UNO with an SD card and some SPI device as a stand-in for your MCP2515 (I don't have one of these).  Though, by then someone else may already have answered.

I did more digging, but I'm not turning up anything clear.  In their example flagRecv should be volatile qualified, as volatile unsigned char flagRecv = 0;  But I have little confidence that this is actually the problem.  I kind of expect that as a bug it would manifest differently if at all in this usage.  It should be fixed though in any case.  If it actually solves it though, let me know and I'll stick it as an answer.

Thank you for your help.
The volatile don't help. Still the same issue.
I tried to force the SPI to use the slave 4 (SD) and not the 9 (CANbus)
digitalWrite(4,LOW);             digitalWrite(9,HIGH);              if (!SD.begin(4)) {               print error             }             print success             myFile = SD.open("can.txt", FILE_WRITE);
and put ss 9 to low right after that. It show a success
It read as usual but still nothing on the SD.
Look like the spi is saturated by the mcp2515. If I remove the sd card, I got an error.

Despite the "the library example must be correct, It's work for other people before you", I'm not sure a lot of people make it works.
I've seen that even when the mcp2551 don't receive anything on can bus, the SPI bus is saturated by the mcp2551.
The solution was to use a simplest library make for 8MHz cristal chip. Modify it to works with standard 16MHz and use the interrupt pin (pin 2 on board) as interrupt.
If anybody got the same issue, just post a comment here and I'll do a better and more complete response.
Thank you very much @Timemage for your help


text:
ESP8266 print garbage output
I am working on a project at school that need using ESP8266, but when i compile and run, the code run sucessful but print nothing, when i push the reset button on the ESP8266, it print some garbage output, i tried to reset it many times but it's still the same. I had success in running the code at the first time, but when i build it again, it's just showing garbage output
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <Ticker.h> //for LED status
#include <WiFiManager.h>
#include <String.h>
#include "ThingSpeak.h"
#include <PubSubClient.h>
#include <SoftwareSerial.h>
Ticker ticker;

//MQTT - mosquitto

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

const char* mqtt_server = "broker.mqtt-dashboard.com";

unsigned long myChannelNumber = 1260973;
const char * myWriteAPIKey = "ML0AX95ICWN71XKC";
const char * myReadAPIKey = "MT8FRNAUN4GJL8F5";

//Ultra Sonic Sensor
const int trig_pin = 5;
const int echo_pin = 4;

//Light Sensor
const int light_sensor = 0;

//LED for tree
const int led_tree = 2;

//LED for remaining water
const int led_red = 14;
const int led_yellow = 12;
const int led_green = 13;

//Soil Moisture Sensor
const int soil_moisture = A0;
int Soil_Value;
int limit = 300;

//Relay
int relay_pin = 15;

float getDistance(){
  float duration, distanceCm;

  digitalWrite(trig_pin, LOW);
  delayMicroseconds(2);
  digitalWrite(trig_pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig_pin, LOW);

  duration = pulseIn(echo_pin, HIGH);

  distanceCm = duration * 0.034 / 2;

  return distanceCm;
}

//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("LED_tree");
      client.subscribe("Pump_water");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  if (topic == "LED_tree"){
    if (digitalRead(led_tree) == HIGH)
      digitalWrite(led_tree, LOW);
    else
      digitalWrite(led_tree, HIGH);
    }
  else if (topic == "Pump_water") {
      Serial.println("pump_water");
    }
  }

void setup() {
  // put your setup code here, to run once:
//  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  // Ultra Sonic Sensor
  pinMode(trig_pin, OUTPUT);
  pinMode(echo_pin, INPUT);
  // Led for tree
  pinMode(led_tree, OUTPUT);
  // Light Sensor
  pinMode(light_sensor, INPUT);
  // Relay
  pinMode(relay_pin, OUTPUT);
  //led for showing remain water
  pinMode(led_red, OUTPUT);
  pinMode(led_yellow, OUTPUT);
  pinMode(led_green, OUTPUT);
  ThingSpeak.begin(espClient);
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  // put your setup code here, to run once:

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;
  //reset settings - for testing
  wm.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wm.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wm.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
}

float waterRemaining(int distance) {
  float r = 2;
  float h = 5;
  float V = 3.14*r*r*(h - distance);
  return V;
}

void loop() {
  // put your main code here, to run repeatedly:
  float distance = getDistance();
  float light = digitalRead(light_sensor);
  String light_value;
  if (light == 1){
    light_value = "The light is enough for tree";
  }
  else {
    light_value = "The light is not enough for tree, suggesting turn on the LED";
  }
  float led_status = digitalRead(led_tree);
  float soil = analogRead(soil_moisture);
  float soil_percent = map(soil, 0, 1023, 0, 100);
  float water_remain = waterRemaining(distance);

  //Write data to field
  ThingSpeak.setField(1, distance);
  ThingSpeak.setField(2, light);

  int returncode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  // Check return Code
  if (returncode == 200) {
    Serial.println("Channel update sucessful.");
  }
  else {
    Serial.println("Problem updating channel. HTTP error code " + String(returncode));
  }

  //Read data from ThingSpeak
  float Distance2 = ThingSpeak.readIntField(myChannelNumber, 1, myReadAPIKey);
  float Light2 = ThingSpeak.readIntField(myChannelNumber, 2, myReadAPIKey);
  // LED for showing remaining water

  float h_box = 20;
  float res = h_box - distance;

  if (res < 5)
  {
    digitalWrite(led_red, HIGH);
    digitalWrite(led_yellow, LOW);
    digitalWrite(led_green, LOW);
  }
  else if (5 <= res <= 10)
  {
    digitalWrite(led_yellow, HIGH);
    digitalWrite(led_green, LOW);
    digitalWrite(led_red, LOW);
  }
  else if (res > 10)
  {
    digitalWrite(led_green, HIGH);
    digitalWrite(led_red, LOW);
    digitalWrite(led_yellow, LOW);
  }
  // Relay pump water
  if (soil_percent < 60)
  {
    digitalWrite(relay_pin, HIGH);
    delay(3000);
    digitalWrite(relay_pin, LOW);
  }

  Serial.print("Distance: ");
  Serial.println(res);
  if (digitalRead(light_sensor) == 1)
  {
    digitalWrite(led_tree, HIGH);
    Serial.println("Light Sensor: HIGH");
    Serial.println(digitalRead(light_sensor));
  }
  else if (digitalRead(light_sensor) == 0)
  {
    digitalWrite(led_tree, LOW);
    Serial.println("Light Sensor: LOW");
    Serial.println(digitalRead(light_sensor));
  }

   if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("soil_moisture", String(soil_percent).c_str());
  client.publish("water_remain", String(water_remain).c_str());
  client.publish("light_sensor", String(light_value).c_str());
  delay(2000);
}

maybe it is the bootlog at 74880 baud. what baud rate do you have set in Serial Monitor?


text:
Sending 4 analog values from one arduino to another with I2C
I have modded a cheap drone controller to output its joystick values to an Arduino Nano.
I made it to output its 4 pot values using I2C to another Arduino don't ask why. So my problem is that I need to send 4 values but I can send only 1. Help me please.
I don't have a time limit or something so I don't need this quick or now!
I am also using a 16x2 LCD without I2C to show the live values and sometime I want to make a menu there or stuff like that.
I would like if you wrote the code for me but its ok if you cant. Also I'm kind of a noob at arduino programming.
Master(a.k.a the nano in the controller):
int pot1 = A0;
int pot2 = A1;
int pot3 = A2;
int pot4 = A3;

int potValue1 = 0;
int potValue2 = 0;
int potValue3 = 0;
int potValue4 = 0;

int led = 10;
int button = 8;

int lastButtonState;    // the previous state of button
int currentButtonState; // the current state of button

int output1 = A4;
int output2 = A5;
int output3 = A6;
int output4 = A7;

#include <Wire.h>
#include <LiquidCrystal.h> // includes the LiquidCrystal Library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)

#define SLAVE_ADDR 9

void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);

  // Open serial communications and wait for port to open:
  Wire.begin();

  lcd.begin(16, 2);
  lcd.print("   ArduinoTX");
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  delay(3000);
  lcd.clear();
}

void loop() {
  currentButtonState = digitalRead(button);
  potValue1 = analogRead(pot1);
  potValue2 = analogRead(pot2);
  potValue3 = analogRead(pot3);
  potValue4 = analogRead(pot4);

  int sendValue = map(potValue4, 1, 1023, 1, 255);  //converting to values 255 max
  int sendValue2 = map(potValue3, 1, 1023, 1, 255);
  int sendValue3 = map(potValue2, 1, 1023, 1, 255);
  int sendValue4 = map(potValue1, 1, 1023, 1, 255);

  Wire.beginTransmission(SLAVE_ADDR); //sending only one pot value
  Wire.write(sendValue);
  Wire.endTransmission();

  lastButtonState  = currentButtonState;      // save the last state
  currentButtonState = digitalRead(button); // read new state

  if (lastButtonState == LOW && currentButtonState == LOW) { //dont worry about this
    lcd.print(potValue4);
    lcd.print("        ");
    lcd.print(potValue2);
    delay(delayTime);
    lcd.clear();
    lcd.setCursor(0, 2);
    lcd.print(potValue3);
    lcd.print("        ");
    lcd.print(potValue1);
    delay(delayTime);
    lcd.clear();
  }
}

Slave(or an uno who receives the values):
int rd;
int br;

#include <Wire.h>

#define SLAVE_ADDR 9

void setup() {
  // put your setup code here, to run once:
  Wire.begin(SLAVE_ADDR);

  // Function to run when data received from master
  Wire.onReceive(receiveEvent);

  // Setup Serial Monitor
  Serial.begin(9600);
}

void receiveEvent() {
  // read one character from the I2C
  rd = Wire.read();
  Serial.println(rd);
}

void loop() {
  delay(50);
}

Thanks!

"I would like if you wrote the code for me but its ok if you can't." That's very considerate of you.

"I need to send 4 values but I can send only 1" why can you only send 1?

Why are you limited to sending one value? You can have multiple Wire.write() calls in one transmission.
The slave side just needs to know to expect multiple values in order to accommodate. The best way to do this would be to read in values as long as the master is sending them (check out https://www.arduino.cc/en/Reference/WireRead).
Then your master changes from
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.endTransmission();

to
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.write(sendValue2);
Wire.write(sendValue3);
Wire.write(sendValue4);
Wire.endTransmission();

And the slave receiveEvent() becomes
int receiveValue;
int receiveValue2;
int receiveValue3;
int receiveValue4;
int index = 0;
while(Wire.available()){
    if(index == 0){ receiveValue = Wire.read(); }
    else if(index == 1) {receiveValue2 = Wire.read(); }
    else if(index == 2) {receiveValue3 = Wire.read(); }
    else if(index == 3) {receiveValue4 = Wire.read(); }
    index++;
}

I would also consider using arrays as a way to clean up some of your variables, but making the above changes should accomplish what you want if not as cleanly.

Happy New Year! But it still does not work :(  And also how do I Serial print these values maybe that's my problem because I put Serial.print(receiveValue); in void loop because i thought that's how it's meant to be. Say if I need to post updated code

If you want to print receiveValue, doing it in void receiveEvent() is the way to go. Unless you made receiveValue a global variable printing it in your loop will not work and could provide misleading results anyway. I'm not sure exactly what issue you are seeing at this point. Can you provide more info please? If it's just that its not printing 4 values, see my previous answer and add Serial.println() for all receiveValues.


text:
Updating SPI transfer16 to create Transfer24
It might be a bit out there, but for a project that I am working on, my word size default is 24bits (3x8-bit), of which the first 8-bits are data and the next 16-bits are data. I would like to transfer it out of the system as fast as possible with minimal calls to the sub-routines. For this I am trying to reduce the number of calls, I have managed to reduce it from 3 to 2, Can I possibly make it 1 call.

My first attempt was to use 3x SPI.transfer() Second was to use 1x

SPI.transfer() and 1x SPI.transfer16()

I would like to know what would be the ideal way to write a SPI.transfer24 function.

What teensy are you using?

teensy 4.0 is the one i am using

And how much difference do you think making 1 function call as opposed to 2 will make at 600MHz? Will you even be able to tell?

@Majenko that is a fair point, but if you try to look at a digital logic level analyzer each word seems to to have a small impact, but when you write ~4M words a second it adds up unfortunately.

You can't.  The teensy 4.0 has hardware support for 8-bit, 16-bit and 32-bit transfers. Not 24-bit transfers.
But at 600MHz the overhead of making a function call is negligible anyway - certainly compared to the speed of SPI which is at best about 30x slower than the CPU operates at.
If you want high throughput you won't be wanting to use the SPI library anyway, instead you'd be using DMA to transfer your data with minimal CPU intervention.


text:
Conflicting pins between the PCM library and speaker and the NRF24L01
The PCM library uses pin 11 and the NRF24L01 also uses pin 11. I am using an Arduino nano, and don't know if there is any way to change the pins of either the speaker or the transceiver.
https://github.com/damellis/PCM

No, you can't just change pins. Both systems use hardware that is specific to pin 11.
The best you could achieve would be to use a software SPI implementation on other pins to drive the nRF24L01, but that would mean changes to the library you are using to remove the SPI library usage and replace it with your own software SPI implementation.

So does that mean it's basically impossible?

Not impossible, just a lot of work, and the results won't be as fast as with hardware SPI.

Oh :(. Is there no way to edit the PCM library to use another pin? What makes pin 11 so special?

It's hard-wired to a specific timer to generate the PWM signal. You could re-write the PCM library to use different timers and their associated pins, but that would be more work and much harder to understand.

I might be wrong, but didn't pin 11 in the PCM library have also been pin 3? So could it be changed to that?

I don't know enough about AVR PWM. It may be possible if you can work out the register settings, for which you'll have to refer to the datasheet for the AVR chip. Personally I wouldn't even begin to consider doing audio on a little 8-bit Arduino. Choose a 32-bit MCU with I2S if you must do anything more than a beep.

I'm just playing a short 2-second audio file.

@Epicmania, you could try to replace OCR1A with OCR1B in PCM.cpp (and OCIE1A with OCIE1B) to use pin 3. do not change other 1A/1B

thank you, I have been trying to change it but I changed much more than that(TCCR2A to TCCR2B), I'll try it with just those changes.

It didn't work :(


text:
MKR Wifi 1010 Project Design
I am newer to microcontrollers and have my first project I would like to try. I have started to sketch out a basic design and would like feedback on things that I may be missed or over looked. I understand I am new and things are probably not correct or I might miss use terminology, please feel free to correct me in any aspect.
Project Scope- I would like to integrate the MKR Wifi 1010 into Alexa using IoT to have an Alexa command sent to the MKR Wifi 1010 that then pulls in a relay that actuates a 12v solenoid.
Hardware
Power supply 1- FQCMOGU AL-1250, Input 100-240v 1.6a, Output 12v 5a
Power supply 2- Drok 15w DC/DC, Output 5v 3a
Microcontroller- Arduino MKR Wifi 1010
Relay- Songle SRD-05VDC-SL-C
Solenoid Valve- Beduan 12v
Here is a sketch of my original plan. Let me know any safeties/ protections I may have missed, calculations that do not make sense or if there is an easier/ better way. I have not order the hardware yet and want some people better at this than me to check it over before I do.

a common project with Arduino IoT Cloud and MKR 1010. https://create.arduino.cc/projecthub/303628/arduino-iot-cloud-amazon-alexa-integration-4e6078

@Juraj Thank you for the response. I did read that article and it is the reason I chose the MKR 1010 for this project.
What I was looking for out of this question was a second opinion on my design to make sure I am not setting my self up for any early failures or better methods of achieving this project.
I will re-read the article to make sure I did not miss anything.


text:
How to put together an HKT30 optical rotary encoder?
I'm working on a project involving stepper motors. It is important for this project to track the position of these motors, so I decided to buy an optical rotary encoder, specifically an HKT30(HKT3005-C03G-1000B-5E) pictured here. I've found it difficult to find resources on how to put this together. I've found datasheets, like this one, but it does not seem to be made up of the same components I have. I think I've basically gotten the gist of how one puts this together from google images, but I would like to be pointed in the way of an explicit resource in case I damage my parts.
Additionally, I was hoping for an explanation on the 5 wires (red, green, black, white, and gray), their purpose and how to set one up on a board.
If any clarification or images are needed, I would be happy to provide.
Thank you!

It's not hard...

The sensor screws into the screw holes.
The disc slots into the gap in the sensor
The case clips on the outside

As to what the wires are, only the datasheet / manual / manufacturer can tell you that. Maybe if you trace them on the sensor board you can work out what is what.

About that, the disc isn't a tight fit into the sensor. Is that supposed to be the case?

Of course. It has to be able to spin, doesn't it...


text:
How do I control the onboard LEDs of my Arduino Nano 33 BLE Sense?
I picked up my Arduino Nano 33 BLE Sense for the first time in a while and ran the classic "Blink" sketch to make sure it was alright. After slight usage, I wanted to play with the onboard LEDs. When I run the following code, the onboard LED does not turn on:
#define RED 22

void setup() {
    pinMode(RED, OUTPUT);
}

void loop() {
    digitalWrite(RED, HIGH);
}

However, when I run the following code, the onboard LED does turn on and stays on - it doesn't blink:
#define RED 22

void setup() {
    pinMode(RED, OUTPUT);
}

void loop() {
    digitalWrite(RED, LOW);
    delay(1000);
    digitalWrite(RED, HIGH);
}

What's happening? Is my Nano busted?

The LED is probably active-LOW, that is,it will only light when you send a LOW signal to the appropriate LED pin. The fact that it doesn't blink in the second sketch is because you turn the LED on (LOW), wait one second, turn it off again (HIGH) but it will immediately (within a few microseconds) turn on again in the next loop() iteration. If you want it to stay on for longer, you should place a delay() after it's turned off (digitalWrite(RED,HIGH);).

There are 3 LEDS on the Nano 33 BLE:

A power LED on pin 25 (yes, you can turn off the power LED programmatically);
A built-in LED on pin 13;
An RGB LED with red on pin 22, green on pin 23, and blue on pin 24.

In the variant file, they are given names:
#define PIN_LED     (13u)
#define LED_BUILTIN PIN_LED
#define LEDR        (22u)
#define LEDG        (23u)
#define LEDB        (24u)
#define LED_PWR     (25u)

The power LED and the built-in LED are active-high, i.e. you need to set their pin to HIGH to turn these LEDs on. The three LEDs in the RGB LED, however, are active-low.
This isn't well-documented as far as I know, and some example code snippets have it wrong too. A quick look at the schematic helps.
Also, as StarCat mentioned, you need two delay()s to make an LED blink.


text:
Arduino LED lamp circuit
I am working on a RGB LED lamp project and this is the schematic for the circuit I managed to come up with.

I am planning to integrate a 27V power supply that powers both the Arduino and a Bluetooth HC-05 module, so I calculated the required resistor values as seen on the schematic. Would this design work? Is 27V too much for the Arduino or does the LED setup balance everything out?
EDIT:
I made an attempt to fix my mistakes based on the answers I received here and this is the new schematic:

This new model would use a 5V power supply instead. Would this fix all issues?

I suggest you to read the usermanual or datasheet of microcontroller. 27V is way to high for the board to handle. You have to reduce it down to suitable voltage level using any voltage regulators. And about the LEDs, the board might not seem to provide enough power to run all LEDs together.

the Arduino pins are 5 V. it will work with one LED, but not with 6 in series. every LED drops around 2 V so after 2 LEDs there is not enough voltage and nothing will light up.

No, this will not work. An Arduino works at 5V and 27V will destroy it. You cannot control the LEDs directly from the Arduino's pins. You need a transistor or MOSFET based circuit to be able to control the LEDs from a lower voltage digital output pin. What current do these LEDs run at?

This is not a software question, it's an electrical one.  Read the datasheet.  And then learn Ohm's Law.

in the updated schematics every LED must have its own resistor usually at least 100 Ohm. it is better to have the transistor after the LEDs

No. You will destroy the Arduino and the bluetooth module.
Firstly the Arduino needs no more than 20V absolute maximum - recommended no more than 16V.
Secondly a resistor is not a voltage regulator. It can only drop a fixed voltage when you have a fixed current. It only works with LEDs because they are themselves a fixed voltage.
Thirdly an Arduino output cannot power 6 LEDs in series. You get 5V out, but the combined forward voltage of 6 LEDs is between 12 and 18 volts depending on the colour.


text:
How to connect D1 mini and ATTINY85 over data wire
I’m trying to connect my D1 mini module and attiny85 USB module together over a data wire, but I don’t know how to do it.
Basically, what I want to do is have the D1 broadcast a hotspot with a web page that when a button is pressed, it sends a signal to the attiny85. The D1 is connected via power wires to the attiny85.
I have the sending signal and web server setup on the D1 but I don’t know how to let the attiny85 receive it.
If it helps, I’m using the wire.h library on the D1
(edit: sorry for inactivity, just haven’t been able to test it)

why do you need to use the ATtiny? what does it do what the D1 can't?

I’m using the attiny85 USB module to send keystrokes to a computer, but if I was using it as a microcontroller I wouldn’t use it at all.

ATTinyCore seems to come with a Wire library implementation presenting the same interface as you find in other Arduino board packages.  The damellis package doesn't, so if you've been trying to use that one, I'd suggest switching to ATTinyCore.
To get started you should be able to use the ESP8266-Arduino Wire library's Master Writer example with ATTinyCore Wire library's Slave Receiver example.  To be clear, you don't need to get them from github, they should be available in the File/Examples menu.  Because the interface is the same, you may find that it doesn't matter which board from which you take the example.
I don't know that I've ever used this Wire library in ATTinyCore; my only memory of using I2C slave no an ATTiny85 was coding it directly myself, but I expect it works fine.  I may try myself to confirm though.
On the ATTiny85 you'll be using DIP/SOIC pin 7 (PB2) for the SCL signal.  And DIP/SOIC pin 5 (PB0) for the SDA signal.
If I try it myself later I'll update this with more details.
More details
I don't have a D1 mini.  I do have this NodeMCU clone though.  According to the pin maps, the D1 mini's D1 and D2 pins are same as on the NodeMCU, that is GPIO5 an GPIO4 respectively.  I wired it together as shown here:

I've drawn some lines on the lower part of the image where the camera angle is bad.  The smaller inset images are just for showing a better angle there.  The yellow and white leads carrying I2C "Wire" data are doctored simply because they went out of frame.
Don't take the "5V" on the ISP cable breakout too literally, that line is at 3.3V (from the NodeMCU 3.3V pin).
ATTiny85 had the following code loaded onto it.  It is just the ATTinyCore slave receiver example with unnecessary comments removed and code to set the LED based on whether it receives a non-zero byte in the I2C ("Wire") transaction:
#include <Wire.h>

static const int LED_PIN = 4;
static const int SLAVE_ADDRESS = 0x08;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(wire_receive);
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {}

void wire_receive(int howMany) {
  if (Wire.available()) {
    digitalWrite(LED_PIN, Wire.read());
  }
}

The following was loaded onto the NodeMCU board.  Likewise derived from the ESP8266 Arduino Wire master-writer example.  Set the local ESP8266 led when it sends the state over to the ATTiny85.  The result is that the ATTiny85 and ESP8266 change their LEDs every 1 second together.  The NodeMCU module is wired to light the LED on a LOW, the ATTiny85 to light on a HIGH, so when one is lit the other is not.
#include <Wire.h>
#include <PolledTimeout.h>

#define SDA_PIN 4
#define SCL_PIN 5
const int16_t I2C_SLAVE_ADDRESS  = 0x08;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin(SDA_PIN, SCL_PIN);
}

void toggle_led() {
    static bool led_state;

    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Wire.write(led_state);
    Wire.endTransmission();
}

void loop() {
  using periodic = esp8266::polledTimeout::periodicMs;
  static periodic nextPing(1000);

  if (nextPing) {
    toggle_led();
  }
}


text:
Getting Trouble in multiple ST7789 SPI LCDs (without CS) with ESP32
I am developing a product in which i have to use 5 LCDs. The LCD i am using does not contain CS pin. SO i had to use MUX for muxing of complete SPI bus from one LCD to other.
But the issue i am facing is, LCD turn off display when i change the select lines of MUX to switch the SPI bus to other LCD. sometimes it just show white screen. basically switching the MUX put the LCD in trouble.
what i am thinking is that when i switch the BUS from one LCD to other then MUX may generate some random data during switching or something like that.
so there is any way the before switching, i should put lcd in a mode that it should not update display until i send any special command again ?
All pins except RST are going through mux, i used separate GPIO for RST of every LCD so that RST should not have issues during switching.
Library i am using is TFT_eSPI.h
Basically library do not support mulitple LCDs, so i customized it by just making global variable for reset pin, when i switch the mux to specific LCD then i change the values of RST to corresponding LCD.
My LCD link is
https://megaeshop.pk/1-3-inch-ips-hd-tft-st7789-ic-unit-240-240-spi-communication-3-3v-voltage-spi-interface-full-color-lcd-oled-display.html
Controller is ESP32
MUX 74HC4051
purpose of using LCD without CS is related to pricing issues. LCDs with CS are too expensive.
I am sorry if my Question formating is not correct or i missed any information. pleas feel free to ask.
I think on all the forums and articles, this is first time i am using multiple LCDs without CS :)

yes it without CS. that's why i used mulitplexer. when i have to write data on let's say LCD 2 then i simply change the address lines of multiplexer

i am sorry, i have updated the link.

Just guessing but try using some simple logic and keep the clock line in the  non asserted state (depends on SPI mode), all the data bouncing around will have no effect, it has to be clocked in. I assume you are not actually reading data from the display.

thanks for your comment,  should i make clock pin as input of controller before switching the addresslines ?
for now i am not reading anything from display.

Thanks for the update. I was just thinking later when reading you probably will have to mux the data out of the display and again it will only be valid with a clock. The reason for the mux is all of them will probably turn on at the same time causing bus contention.


text:
To reduce the Attiny85 current consumption
I am using Attiny85 to control 4 LEDs parallelly with a programmable switch. But even though when the LEDs are in OFF state, current consumption is around 7-8mA.
I am using a 200mAh battery in my project and it is draining up the whole battery in 24hrs (when the LEDs are in OFF state)
Below is the schematic image of my attiny85 circuit:

Code:
//Absolute maximum current of each pin of Attiny85 is 40mA
//So each LED has been given to seperate pins

const int buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin1 = 0;      // the pin that the White LED1 is attached to
const int ledPin2 = 1;      // the pin that the Blue LED1 is attached to
const int ledPin3 = 3;      // the pin that the White LED2 is attached to
const int ledPin4 = 4;      // the pin that the Blue LED2 is attached to

// Variables will change:
int counter = 1;             // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  //Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(buttonPin);    // read the pushbutton input pin

  if (buttonState != lastButtonState) {    // compare the buttonState to its previous state
    if (buttonState == HIGH) {             // if the state has changed, increment the counter
      counter++;                           // if the current state is HIGH then the button went from off to on:
    }
    delay(50);                    // Delay a little bit to avoid bouncing
  }

  lastButtonState = buttonState;  // save the current state as the last state for next time through the loop

  if (counter == 2) {
    digitalWrite(ledPin1, HIGH);  //turns on White LED1
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
  else if (counter == 3) {        //turns on White LED2
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }
  else if (counter == 4) {        //turns on both White LEDs
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }
    else if (counter == 5) {        //turns on Blue LED1
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
    else if (counter == 6) {       //turns on Blue LED2
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, HIGH);
  }
  else if (counter >= 7) {         //turns on both Blue LEDs
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, HIGH);
    counter = 0;
  }
  else if (counter == 1){         // turns off all the LEDs after one button push
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
}

For each time push button is pressed, respective LEDs get ON and there are 6 such cases. In 7th case, it goes back to case 1.
So, is there a way to reduce the current consumption?
Is there any commands where we can,

Reduce the clock frequency
Disable all the interrupts
Disable all modules etcc.....when not in use

If the current consumption goes less than 1mA that would be great.

The key word you want to search for is “sleep”.

https://electronics.stackexchange.com/questions/349496/how-to-achieve-low-power-consumption-with-attiny85 . You can have the MCU in power-down mode most of the time, and only wake it up (via an interrupt) when the button is pressed. It's probably easier to move the button pin to the INT0 pin for that. After that you should get sub 1mA currents (when all leds are also off). After that, you can disable the ADC to save a few tens of µA's.

The VCC line of your ATTiny85 is connected to something called VBOOST; I just wanted to point out that the power you save by putting your ATTiny85 to sleep will probably be peanuts compared to what you'll save by shutting down the boost regulator when it's not used.  If you're unable to do that, it may not matter so much whether you put the ATTiny85 to sleep.

Yes. I have placed a SPDT switch in between so that there wont be any drain @timemage


text:
Properly escaping very large strings
On an ESP8266 I want to create a little webserver that shows me a dashboard with charts and stuff. For this I want to include the echarts-library as it works offline. To access it the only way I can see this working is that I write:
const char libData[784674] PROGMEM = "the entire 700 KB library goes here";

And then deliver it on request with server.on('./echarts.min.js', handleLibRequest) or something like that.
Now my problem is that in this 700KB of text there are ' and " characters all scattered arround. The C++11 way of R("hard escapable '"'''" string") isn't working in my environment. How would one go about this to include this file in my code?
Is there mybe some way utilize the preprocessor for this? Or maybe an online tool that converts "str" to ['s','t','r']?

serve static files from file system

How would I add these static files into the filesystem? Without having to use any c++ code where I would face the same issues mentioned in my question?

with the IDE plugin for esp8266 FS upload. https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html

Its simple, paste all you page between "()" on the below line
const char live_html[] PROGMEM = R"rawliteral(your date here)rawliteral";

You could write a program that escapes all the offending characters and use the output of that in your const char libData[]; see here for a list of escape sequences;
You could serve the library directly from a (pseudo) file system on the ESP8266, without having to copy it "manually" into a variable; you just copy the file to the filesystem;
You could Base64-encode the library and manually copy the result into const char libData[], then Base64-decode before sending;
What I like to do, if there is no file system but enough memory:

Gzip the library;
Base64-encode the .gz file;
Copy the Base-64 encoded result by hand into your const char libData[].

The Base64 encoding allows you to copy/paste without problems.
Despite the Base64 encoding, the gzipping makes the end result smaller than the original, which helps with memory usage and transfer speed, and it will have no "quote problems".
When the libData needs to be served, Base64-decode it, and send the resulting (gzipped) data to the client; all browsers I know will accept that if you add the Content-Encoding: gzip header.
Example code on a raw client without a webserver library: unsigned int sendBase64Page() (mind the content type).

That's like copying it into a variable but unecessarily complicated in my opinion. But thanks for the idea.

You can use "objcopy" to produce an object file from the file's contents, if you declare it as binary.
objcopy -I binary echarts.min.js -O <your-bfd-format> echarts.min.js.o

To find out which BFD format you need, run objdump -t <any object file> and look at its output.
The resulting object file contains an object named after the input file in the .data section. There are 3 symbols in the symbol table:

_binary_echarts_min_js_start
_binary_echarts_min_js_end
_binary_echarts_min_js_size

The "start" symbol marks the beginning of the file's content, and the "end" symbol marks the address after the last byte. The "size" symbol is hard to use in C or C++, because it is an absolute value.
Commonly I just use "start" and "end" like this:
extern const char _binary_x_bin_start[];
extern const char _binary_x_bin_end[];

Instead of objcopy, you can use ld -r -b binary echarts.min.js -o echarts.min.js.o This way you do not need to know the BFD format, provided you use the ld binary appropriate for the target architecture.

I've just written myself now a python-script that creates a char-array with the numbers representing the characters. Maybe it helps someone else:
import sys

def arrayify(sourceFile, targetFile):
    with open(sourceFile, 'rb') as sf:
        contents = sf.read()

        charArray = ""

        for char in contents:
            charArray += str(char) + ","

        # end array

        with open(targetFile, 'w') as tf:
            tf.write(charArray)

if __name__ == "__main__":
    sourceFile = sys.argv[1]
    targetFile = sys.argv[2]

    arrayify(sourceFile, targetFile)


text:
CNC Y-axis stepper moving forward but not in opposite direction
I'm building an CNC mill with an Arduino UNO with a CNC Shield V3. But I have a problem with the Y motor direction. It only moves in one way while the X motor is moving both ways. When I just installed everything it worked, but after a view tries it doesn't anymore. I viewed multiple topics on this problem but nothing is working.

I tried to switch the stepper drives but that didn't make a difference.

Switched the stepper motors and then the x motor moved in one way so it isn't the stepper motor.

Tried cloning the Y controller to the 4th connection. Also didn't work.

Tried multiple GRBL HEX files, all the same.

I also tried multiple gcode senders but is just doesn't make a difference.

Is there anything else that I can try to help this problem? Or shall I order an new shield to test if this shield is broken.

So, what code is running on the Uno? How exactly is it conected to a motor? Link to the attached CNC shield and it's pinout? Pictures of the setup maybe?

Have you blown one of your drivers? Try swapping them around.

if one of the motor windings was not driven,  then the motor would fail to turn in either direction ... either the motor driver has a bad direction pin (if there is one), or the problem is caused by software

The code is running on the Uno is GRBL and the driver board is A4988, on the cnc shield 3 and i was even trying to interchange the driver and the motor no improvement

Check the DIR signal to the Y controller.


text:
Variable Fan Controller - Properly Sized Transistor
I would like to a build a temperature sensing variable speed fan controller for my truck. Currently using a purchased 2 speed on/off relay based controller, but my fans are overloading the whole circuit when the controller is powered on during a high speed temperature scenario. On low speed, I have the fans wired in series to spin both slower - works great. Each fan initially draws 100 amps at full 12v. On the low speed (6v/series), they cruise about 20a together. On high speed, they settle in around 25a each.
I am somewhat experienced with arduino and using a few references to build in specific features I want, but here is the main example I am going by.
https://circuitdigest.com/microcontroller-projects/automatic-temperature-controlled-fan-project
My question is around the type and size of transistor that I would need to handle the amount of current these fans draw. Some examples have MOSFET while others have FET or even standard PNP. I am pretty new to working with transistors and can't find any references that make sense. Would love to get a reference to learn this calculation and appropriate type.
Edit: removed picture with incorrect wiring diagram.

You would typically have a bank of parallel power MOSFETs with a big heatsink.

the arduino cannot induce current flow into the base of Q1 because the arduino ground is not connected to the emitter of Q1 ... therefore Q1 will not turn on

@jsotola I didn't catch that before linking to that picture. Thanks for pointing out, though it's not my question. Removed the picture.

The easiest might be to use a solid state relay. There are devices for DC and they often can be controlled directly with 3.3V or 5V. In any case, thermal management will play an important role

Doing a quick search for high-current MOSFET transistors, I ran across the following:
https://www.digikey.com/en/products/detail/ixys/IXFK170N20T/2126313
The important spec here is the Rds ON (max) of 11mOhm @ 60A, 10V
At your peak current of 100A, you would drop 1.1V across the transistor, for a power dissipation of 110W.
The advertised P(max) is 1150W, so assuming the junction temp can be held to under 175C (and with an entire metal truck to use for a heat sink, this shouldn't be a problem) you should be OK with this device.  In the 'cruise' configuration with 25A motor current, you should have no problem controlling the fans.
YMMV ;-)

Your answer is fine, but as the OP mentioned to have little experience with transistors, I want to add that this mosfet can't be controlled with qn arduino's logic level and needs an additional drive circuit

Good point - thanks for the addition!


text:
Can i connect in pin of relay module to Analog pins of arduino instead of digital pin?
Im a complete beginner
Im making a project using relay modules and arduino. but all the digital pins of my arduino are filled.
I wanted to ask if i can use the analog pins to connect my relay module to my arduino? If yes can anyone give me the statements to write high and low using analog.

pins that have analog functionality are multi purpose ... they can also be used for digital outputs ... the command is the same for all digital output pins

Yes, you can  use the analog pins as digital pins.
Quoting this Arduino tutorial:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);

EDIT:
Here is the code snippet for digital input:
pinMode(A0, INPUT);
digitalRead(A0);

Your answer is certainly correct, but it would be better to show an example of using an analog pin as a digital INPUT, since that's what the OP is asking about.

worked for me thanks