text:
L1 is not declared in this scope error
I have a project where I have to control a DC motor.
In this code the purpose is that every time you press a button the direction of the motor changes.
I only get the error that L1 (and L2,R1 and R2) are not declared in this scope. the place in the loop.
How do I define the variables so that the code works?
int Motorforward = 10;   // MotorDirectionPin set to pin10
int Motorbackward = 11;   // MotorDirectionPin set to pin11
const int button1Pin = 2; //button control set to pin 2

int state = L1;
int state = L2;
int state = R1;
int state = R2;

int button1State;  // current reading from the input pin
int previous = LOW; //the previous reading from the input pin

char input;

void setup(){
pinMode(button1Pin, INPUT); //set pin as input
Serial.begin(9600);

pinMode(Motorforward, OUTPUT); // sets the pin as output
pinMode(Motorbackward, OUTPUT);
 }

  void loop(){
button1State = digitalRead(button1Pin);
input = button1State;

switch(state){
  case L1:
    if (state == L1){
    if (button1State == HIGH){
        state == L2;
    }
  }
  break;

case L2:
  if (state == L2){
    if (button1State == LOW){
      state == R1;
    }
  }
  break;

case R1:
  if (state == R1){
    if (button1State == HIGH){
      state == R2;
    }
   }
  break;

case R2:
  if (state == R2){
    if (button1State == LOW){
      state == L1;
    }
  }
  break;
}

How many state variables do you want?!  And it is quite correct. At no point do you ever declare those symbols.

Do you mean the different states the motor can be in?
in that case 4 states in which case 1 and 2 and case 3 and 4 give the same result.

No, I mean how many state variables do you want? You define the same variable 4 times, each time with a different assignment, and an assignment to a variable or macro that you haven't defined at that.

I have the feeling you need only one state which can have 4 values: L1, L2, R1 or R2.
For this, use an enum:
enum EState { L1, L2, R1, R2 };

Now create one state variable of that type and give it an initial value.
EState state = L1;

Some other problems I see at first sight:
case L1:
  if (state == L1){
  if (button1State == HIGH){
      state == L2;
  }
}
break;

In this statement, when there is case L1, it means the code following ( until the break) is only handled when the state (because of switch(state) is L1, so you can remove the check if (state == L1). What is left is:
case L1:
  if (button1State == HIGH)
  {
    state == L2;
  }
  break;

Than you use state == L2 to set a new state. However, the == only compares two values, if you want to assign it, you have to use a single =, thus the code should be:
case L1:
  if (button1State == HIGH)
  {
    state = L2;
  }
  break;

Of course you have to do this also for the other case statements.
Tip: align your code (make the { and } aligned under each other; this will make your code readability much better.

You have not defined L1, L2, R1, or R2.  You're also redefining the int variable 'state' four times.
Try replacing:
int state = L1;
int state = L2;
int state = R1;
int state = R2;

With something like:
#define L1  1
#define L2  2
#define R1  3
#define R2  4
int state = R2;


text:
NeoICSerial and SPI on the Uno - pin 10
The NeoICSerial documentation contains a table that states for the Uno:

Transmit: 9
Receive: 8
PWM Unusable: 10

Pin 8 and 9 are used for the serial connection. Pin 10 is part of the pins for the SPI on the Uno. Does this mean SPI connections can't be used together with NeoICSerial or is this specific for using pin 10 for PWM?

The "Unusable 10" is explained in AltSoftSerial library

The "Unusable PWM" pins can be used normally, with digitalRead() or
  digitalWrite(), but their PWM function controlled by analogWrite()
  will not work properly, because AltSoftSerial uses the timer which
  controls that pin's PWM feature.

Pin 10 on Uno is SPI slave select if the Uno is SPI slave (then it is an INPUT).
If the Uno is SPI master, this pin must be set as OUTPUT. For this reason it is usual to use pin 10 as slave select for the (first) SPI slave. SPI shields have this pin hardwired as slave select for the (first) SPI device on the shield.

NeoICSerial is interrupt driven - does this create a limitation between using pins 8, 9 and 10? I'm a bit puzzled by the table in the documentation and don't see where the limitation is coming from. The documentation states: "This class can only use one predefined Input Capture pin. Each MCU and board has a pre-determined pin"

source: Stack Exchange

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

sort: votes


text:
please explain the sketch attached
Sorry about a newbie.
1. what mening of:
    if(Xstr[XstrLength-1] != '|'){
      Xstr[XstrLength] = '|';
      Xstr[XstrLength+1] = '\0';

the setup: char Xstr[60]; what means? and then: itoa(Yint,Ystr,10);

Code:
#include <VirtualWire.h>

//gamepad setup
int up_button = 2;
int down_button = 4;
int left_button = 5;
int right_button = 3;
int start_button = 6;
int select_button = 7;
int joystick_button = 8;
int joystick_axis_x = A0;
int joystick_axis_y = A1;
int buttons[] = {up_button, down_button, left_button, right_button, start_button, select_button, joystick_button};

void setup()
{

    //gamepad setup
    for (int i; i < 7; i++)
    {
        pinMode(buttons[i], INPUT);
        digitalWrite(buttons[i], HIGH);
    }

    Serial.begin( 9600 );

    //transmitter setup
    vw_set_tx_pin(12);          // Sets pin D12 as the TX pin
    vw_set_ptt_inverted(true);  // Required for DR3100
    vw_setup(2000);             // Bits per sec
}

int counter = 0;

int Xint;
int Yint;

char Xstr[60];
char Ystr[60];

void loop()
{
    // Read and store Sensor  data
    Xint = analogRead(joystick_axis_x);
    Yint = analogRead(joystick_axis_y);

    // Convert integer data to Char array directly
    itoa(Yint,Ystr,10);
    itoa(Xint,Xstr,10);

    int XstrLength = String(Xstr).length();

    if(Xstr[XstrLength-1] != '|'){
        Xstr[XstrLength] = '|';
        Xstr[XstrLength+1] = '\0';
    }

    char combinedArray[String(Xstr).length() + String(Ystr).length() + 1];
    sprintf(combinedArray, "%s%s", Xstr, Ystr);

    vw_send((uint8_t *)combinedArray, strlen(combinedArray));
    vw_wait_tx(); // Wait until the whole message is gone

    Serial.println(combinedArray);

}

This adds some end of string characters.
if(Xstr[XstrLength-1] != '|'){
    Xstr[XstrLength] = '|';
    Xstr[XstrLength+1] = '\0'

First it checks if Xstr last character is a '|', if not:
   Place a | directly after the last character
   And append a '\0', which is a symbol to 'end' a string
A string in C/C++ is normally build up like this, e.g. "Hello" contains of the bytes:
'H', 'e', 'l', 'l', 'o', \0

Where each of the above are ASCII characters/values and the last \0 a 0 byte.

char Xstr[60]; defines a character array (string) that can contain 60 characters. Note however, that the ending \0 also needs to be in this string, so you can actually only put 59 characters inside.
itoa(Yint,Ystr,10); converts Yint which is an integer value to a string (where each digit has each own byte), and 10 is the length.

Thank you Michel Keijzers.  I confused with char Xstr[60] and  itoa(Yint,Ystr,10), actually they not same thing.

Gladly done, If the answer helps you, please consider upvote and accept my answer.

HI, when used a MCP4261, there is function "digitalPotWrite" , can I use "digitalWrite" replace it? Thanks.

Because the "digitalPotWrite" need be void definition， can't be used inside setup.

digitalPotWrite is a function to communicate with the MCP4261 over SPI. digitalWrite is a function to set an IO pin HIGH or LOW. The two have nothing at all to do with each other.

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


text:
How to put the inputs in array?
I face a problem and I really need help.
For my Arduino project, I'm using RFID reader with tags.
The story is, I have a desired arrangement for the cards and I defined it as an array called desired[]= {.... , .... ,....}
Then, I want my RFID reader to read the real sequence of the cards and Arduino will tell me if the sequence is right or wrong.
My real problem is, how to put the input which will come from the reader in my empty array real[2];
My code is:
#include <SPI.h> //// Library
#include <MFRC522.h> // Library
constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout above
 constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout above
 MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance
String Desired[]={ "f01ca379" ,"60d7a1a5" , "64d7a3a6"};
String Real[2];

void setup() {
Serial.begin(9600);                                           // Initialize
serial communications with the PC
SPI.begin();                                                  // Init SPI bus
mfrc522.PCD_Init();                                              // Init MFRC522 card
 }

   String readUID() {
  String readUID = "";
  for (byte i = 0; i < mfrc522.uid.size; i++) {
     readUID = readUID + (mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
    readUID = readUID + String(mfrc522.uid.uidByte[i], HEX);
          }
            mfrc522.PICC_HaltA();
       return readUID;
      }

void loop() {
 if ( ! mfrc522.PICC_IsNewCardPresent()) {
return; }
 if ( ! mfrc522.PICC_ReadCardSerial()) {
return; }
String UID = readUID();
if (UID == "f778f19"){
******************************************
******************************************
     }
 }

I used f01ca379 card as a master card only to start the loop.
in the {*************} I need to complete the code in order to save the input in my Real Array, then to compare it with the desired array and decide if the real arrangement matched with the desired one.with tags

why do you need to put the scanned card number into an array? .....  why don't you simply compare the card numbers as you scan them?

The first problem is, how to decide the number of card scanned without using an array?  Because I want the reader to stop after scanning 3 cards, and do the process again.  Also, what command I have to use in order to compare without an array? Because when RFID reader scan the first item, i want to compare it with first number in array, second time of scanning, comparing with second number in desired array.... Etc.  Please help me how it comes?

there is no number of card scanned ..... there is  number of card being checked ...... why would you continue to check all three cards if the first one does not match?  ........ do this with playing cards first (or with pieces of paper)

For my project, I need to check all three cards ... even if the first one doesn't match, I need to check the rest of them, and that's the problem. Also, in the real case it's not only 3, I just chose 3 to start writing the logic.


text:
Arduino UNO and ESP8266-01 Wi-Fi cutting out after few seconds
I followed this tutorial: https://www.youtube.com/watch?v=2cjufbgOBYo
My serial output in Arduino editor is this:
AT
AT
AT
AT
AT
AT
AT
AT+RST
ATE0
AT+CWMODE=2
AT+CWDHCP=0,1
AT+CWSAP="RemoteXY","12345678",10,4
AT+CIPMODE=0
AT+CIPMUX=1
AT+CIPSERVER=1,6377
AT+CIPSTO=7
AT
AT
AT

The problem is the Wi-Fi is cutting out after a few seconds. I see the network pop up on my phone/on the RemoteXY app and then it disappears after a few seconds.
I have a suspicion it's something to do with the RX needing a voltage divider? But I am just following the tutorial and am new to electronics.
I also haven't wired up an LED yet (I am planning on using a mains relay instead)
All help appreciated,
Thanks.

I'll bet one of the small chips on the Uno is getting very very hot, yes?

I'm not sure, why would that be? Do you know why it's not working?

It would be getting hot because you're trying to run an ESP8266 from the 3.3V pin of the Arduino. The Arduino cannot supply enough current without the 3.3V regulator overheating. When it overheats it shuts down.

So do you know how I can rewire it? Any diagrams ?? I guess that tutorial was bad :(

Get a proper 3.3V voltage regulator that can provide at least 500mA. Run the whole thing off an external 1A (or greater) 5V power supply (phone charger).

Can I use the 5V pin from the Arduino?

You can feed your 5V supply into the 5V pin, but you shouldn't try and pull more than a few hundred mA out of it, no.

no power supply to Uno will allow more current over 3.3 V pin of Uno. the esp8266 resets if it doesn't get the current for peek draw so the regulator doesn't get hot


text:
What is the best way to connect multiple Arduinos?
In my situation, I have a map divided into multiple parts, each part could have about 20 to 100 Arduinos that they should send information from time to time to the master. How could I do this?
Second problem. How could I use the other Arduinos to send the info from Arduino that are so far from the Master?
Example in part 1: Arduino X is 500 meters far away from the master. How could use the other to send the information?
Can I do this with NodeMcu or such equipment with built-in WiFi?

esp8266 arduino boards package supports WiFi mesh

I think you should start with using Wifi modules and you use an esp-01 too instead of NodeMCU. Once you are familiar with esp-01's, you will find them as good as NodeMCU. Esp-01's only lack multiple pins when compared to NodeMCU.
And for communication between arduino and esp-01, use serial ports- 0 and 1.
Here is example code-
For Master Arduino
int temp;
int hum;

void setup(){
 Serial.begin(115200);
 delay(2000);
}
void loop() {

 temp = random(0,100);
 hum = random(100,200);
 Serial.print(temp);
 Serial.println('t');
 delay(2000);
 Serial.print(hum);
 Serial.println('h');
 delay(2000);
 Serial.flush();
}

For Slave Esp or any other slave arduino -
String inString = "";    // string to hold input

float temp = 0,hum = 0;

boolean newtemp=false, newhum=false;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP 8266 - 01 Module is ready to receive codes from Master Arduino");
 }

void loop() {
  // Read serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {

      if (inChar == 't')
      newtemp = true;

      if (inChar == 'h')
      newhum = true;

      inString += (char)inChar;
    }
    else {
      Serial.print("Input string: ");
      Serial.println(inString);
      if ( newtemp == true ) {
      temp = inString.toFloat();
      Serial.print("Received Temperature:");
      Serial.println(temp);
      newtemp = false;
      }
      if ( newhum == true ) {
      hum = inString.toFloat();
      Serial.print("Received Humidity:");
      Serial.println(hum);
      newhum = false;
      }
      inString = "";
    }
  }
}

Pin connections -
Master Arduino TX -- Slave board RX

This is a classical application for LoRa technology, not WiFi.  Designing a LoRa mesh is no simple task, though.
Check this post, or this other post

You could use low radio frequency modules to get to the 500m. For example there are the so called xbee modules (XBee Pro 60mW PCB Antenna - Series 1). You can find cheaper ones, but from my experience they are a bit harder to understand and not reliable.
You can make a TCP-like connection, where before data is send, the "slave" asks the "master" whether he can catch data or not. If not, he'll just keep asking after a delay has passed till he gets through. Even though TCP is mostly used in WiFi 2.4G, you could still apply it to your project
If you want to use WiFi than you can make a connection between the "slave" and "master" by having some middle man chips in between that pass on the data, but you would need the middle man chips to be constantly powered on (or use a RTC to time the "wake time").


text:
String.format("%i",i) equivalent
How do I format an arduino String when I do not want to print it?
I know that one can use printf() or other methods to print a formated string and unfortunately that's all I find with google.
But that's explicitly not what I'm looking for, I want to assign the formated string to a variable instead.
There are itoa, etc. which I could use, but if there is a standard function to use like String a=format("an integer: %i",myinteger); I would really prefer this one.

The answers to the below question link might help - https://stackoverflow.com/questions/34775168/get-formatted-string-to-a-variable

see Rohan's link for sprintf. I recommend not to use Strings, but if you must: String s(32); s += "an integer: "; s += myinteger;


text:
LCD not displaying any character with I2C or when used separately
I have an arduino uno and pin connection for I2C are -
SDA --> A4
SCL --> A5
VCC --> 5v
GND --> GND

This the code i am uploading taken from the examples -
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
    // initialize the LCD
    lcd.begin();

    // Turn on the blacklight and print a message.
    lcd.backlight();
    lcd.print("Hello, world!");
}

void loop()
{
    // Do nothing here...
}

The LCD shows nothing after upload . I have tried adjusting the potentiometer on I2C; just the blank characters come up.

This looks correct. You could try lcd.setCursor(0, 0) before the print. Is the backlight coming on as expected?

There is also a chance that the display is having a different address than0x27; see this answer: https://arduino.stackexchange.com/a/28508/53450

Running the I2C scanner sketch (https://playground.arduino.cc/Main/I2cScanner) would be the first thing to do to check if the I2C is detected on the bus and with which address.

Use the I2C scanner sketch to verify the I2C address of the display. I also have a non-standard LCD that has different pin mappings between the I2C module and the LCD itself, and I had to use a version of the LiquidCrystal_I2C constructor that let me specify the pin assignments.

Thank you all i found the problem, some of the pins were not properly soldered and had to use LiquidCrystal_I2C lcd(0x27, 20, 4)

Which LCD display model are you using? There are quite a few variations.

#Duncan using 2 x 16 display with I2C serial board. I am having another major issue if you guys could help.Go to https://arduino.stackexchange.com/questions/62587/esp-01-responding-to-some-codes-not-all-like-of-adafruit-mqtt?noredirect=1#comment134355_62587


text:
Arduino LED PWM dimmer starts blinking on low PWM values
I'm trying to build a PWM led dimmer with Arduino using this circuit:

simulate this circuit – Schematic created using CircuitLab
Everything works fine until the pin PWM 3 drops below the analog value 50 (more or less) the LEDs starts blinking fast and noticeably. However, if I touch with my finger the metal cup of the BJT transistor the LEDs do not blink anymore and they work as I assumed. The test program is below, and I've tested it with an Arduino UNO and an Arduino MEGA and they both have the same problem. The DC supplier is a transformer I bought from an electronics shop and it works properly if directly attached to the strip.
Test Program:
void setup(){
  pinMode(3, OUTPUT);
}

void loop(){
  for(int i = 0;i<=255;i++){
    analogWrite(3,i);
    delay( i<=40 ? 300 : 50);
  }

  for(int i = 255;i>=0;i--){
    analogWrite(3,i);
    delay( i<=40 ? 300 : 50);
  }
}

I tried searching my problem on the internet and I've found a schematic which uses a P2N2222 transistor in this article, which is equivalent to mine, except for the fact that it uses a P2N2222. I also tried changing the transistor to a new one (in case the one I'm using is broken), but it did not help.
So I don't see what I did wrong, could you please help me in finding it out?

Did you write the program yourself? That is okay. The schematic is wrong, when you connect it that way, the transistor, the arduino board and perhaps the ledstrip as well are blown. When using 24v, you could damage your computer as well via the usb cable. Tell us more about the led strip. Can you give a link to it? How much voltage and current does it need?

The led strip requires 24V and 500mA of current. I have no links for that because I bought it from an electronics store a long time ago. I've already tried the schematic shown and it did not damage anything... why should it damage a component?

Looking at the schematic, it seems like the LED and the transistor are upside down.

Your diagram has the transistor wired backwards. It should not work that way.

You're right. I've corrected it: I just flipped the transistor in the schematic, but the circuit I've designed is the corrected one and it has the aforementioned problem for small analog values of the pin. Thank you.

Can you do a vertical flip of the led as well?

LTL307-EE is a regular red led (2V,  20 mA) Something that survives 24V and consumes 500 mA ( which is a lot for a 2N2222 btw ) and your power source they both must have some electronics inside, which might behave in strange ways when switched by your PWM transistor.

since you are editing your schematic, move the GND on the uno to one of the bottom pins and get rid of the crossover at the transistor base

How many LEDs in this strip? If there were 12 2V 20mA LEDs you could put them in series and drive them with ≈20mA of 24V. 500mA of 24V is a whole bunch of juice for LEDs.

I updated the question with all the details. @DuncanC I don't know how the LEDs are connected to the stripe because I bought the entire stripe from an electronics shop. I can only make hypothesis. I see that those LEDs are connected in series at least every 6 LEDs (the stripe can be cut every six LEDs), but I suppose that the 6 LEDs are connected in parallel because if a LED stops working, the others will work as regular. Anyway, I measured the current of 500mA by connecting the stripe and measuring the current with an amperometer in order to calculate the resistor R1

As DataFiddler says, the LED strip may well have electronics in it that get confused when you feed it pulsed power at too low a duty cycle. Without more info about the LED strip it’s impossible to tell for sure.


text:
Reading Multiple RFID tags / Reading and ignoring/holding the tag
I'm currently doing a project where ideally I will have multiple objects with RFID tags on them that are placed on top of a Adafruit PN532 RFID Shield connected to a Arduino Uno Wifi Rev 2. The idea is that once a button is pressed the RFID reader will read a Mifare tag then "ignore" it then reads the next tag until all are read. How can I acheive this?
I have read some about Anti-collision protocols and the limitations of RFID but was also wondering if it might be possible to read a tag then hold or ignore that tag until it leaves the range of the RFID shield?
I've also read a user on the Adafruit forums had some luck by altering the library that is used, I'll link it for reference, but I've tried the same method but had no luck myself. Adafruit-PN532 Library
I'm new to Arduino so I apologise if I've messed anything out.
Thanks for any help!

what is the actual question? I don't see one

Sorry MichaelT, the question is how can I achieve what I intend to do for my project? e.g. hold a tag so it is not read again until it leaves the range of the RFID shield. I have edited the original to make the question more obvious I hope.

You probably want to use UHF RFID for this.  The Adafruit PN532 is only capable of reading max 2 tags at a time in an alternating fashion.  This is confirmed by the board's designer in the Adafruit forums.


text:
Blinking 2 LED having input from serial monitor
Sir while entering the values on the serial monitor, I ask the user to enter the value for red led voltage(0-255) then again ask for yellow at the red voltage asking it produces the user to  put the value, after that it asks for yellow led input but the time to enter the value for yellow led input is very less and so it does not get entered and the futher program starts. So only red led works where as Yellow does not.
int REDledpin=9;        //RED led on pin 9 of the uno board.
int YELledpin=7;        //YELLOW led on pin 8 of the uno board.
int REDonleddelay=500;  //The red led will be on for 500 ms.
int REDoffleddelay=500; //The red led will be off for 500 ms.
int YELonleddelay=600;  //The YELLOW led will be on for 600 ms.
int YELoffleddelay=600; //The YELLOW led will be off for 600 ms.
int countredled=5;        //The RED LED count variable
int countyellowled=5;     //The YELLOW LED count variable
String red="Red led is blinking";
String Yellow="Yellow led is blinking";
int redintensity;
int yellowintensity;

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

void loop() {
Serial.println(red);
for(int j=1;j<=countredled;j=j+1)
  {
    Serial.print("The red LED blink star: ");
    Serial.println(j);
    analogWrite(REDledpin,redintensity);
    delay(REDonleddelay);
    analogWrite(REDledpin,0);
    delay(REDonleddelay);
  }

Serial.println(" ");
Serial.println(Yellow);
  for(int j=1;j<=countyellowled;j=j+1)
  {
   Serial.print("The yellow LED blink stars");
   Serial.println(j);
   digitalWrite(YELledpin,yellowintensity);
   delay(YELonleddelay);
   digitalWrite(YELledpin,0);
   delay(YELoffleddelay);
  }
 Serial.println(" ");
}

add while (Serial.read() != -1); after parseInt() to read the line termination characters

@Juraj was on the right track however the end-of-line characters for example may not be buffered and the problem could continue.
The correct approach is the wait for the end-of-line character specifically.  Let's take the easy way out and use Serial.readStringUntil
#define EOL_CHAR '\n'

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.readStringUntil(EOL_CHAR); // clear serial buffer to end of line character

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

This all depends on what you're Serial Monitor is sending as a new line; it could be CR (\r), LF (\n) or CRLF (\r\n), so change the EOL_CHAR value accordingly depending on your serial monitor setup.


text:
Attach() resets servo's angle
I'm working on code that will control micro servo. I use generic servo and built-in library for controling servo. Microcontroller is generic STM32.
Controlling servo Works as expected. But I don't want next behavior - attach() function sets servo to 180°(maybe 0°, not sure).
In my project I want next:

Servo stays at angle before going off/reboot
Servo goes to 90° after turning on/reboot

I googled about this problem and tried with write(90); before attach() in setup() function. Servo goes to 90° but after like 50ms attach() stops write(90) function and it goes back to 180°. So this didn't solve my problem.
Next I've open Servo.cpp and found that attach() function contains next code:
    bool Servo::attach(uint8 pin,
                   uint16 minPW,
                   uint16 maxPW,
                   int16 minAngle,
                   int16 maxAngle) {
    timer_dev *tdev = PIN_MAP[pin].timer_device;

    if (tdev == NULL) {
        // don't reset any fields or ASSERT(0), to keep driving any
        // previously attach()ed servo.
        return false;
    }

    if (this->attached()) {
        this->detach();
    }

    this->pin = pin;
    this->minPW = minPW;
    this->maxPW = maxPW;
    this->minAngle = minAngle;
    this->maxAngle = maxAngle;

    pinMode(pin, PWM);

    timer_pause(tdev);
    timer_set_prescaler(tdev, SERVO_PRESCALER - 1); // prescaler is 1-based
    timer_set_reload(tdev, SERVO_OVERFLOW);
    timer_generate_update(tdev);
    timer_resume(tdev);

    return true;
}

What should I do to fix this problem? Servo will adjust angle of PCB which holds LEDs. PCB will be in case and angle of 90° is default angle. 0°/180° will either destory servo or brake case/PCB/something else.

If there are limits to the angles it can travel, I think you need to look at minAngle and maxAngle

You showed us the code from the core for the Servo library.  That code is KNOWN to work.  It works for everyone else.  Most likely the mistake is in the code that you wrote that you haven't shown us.  Please post the code you are having trouble with if you really want help.  It is impossible to help you fix code that I can't see.

@Delta_G Sorry for delayed answer. HLServo.attach(PA8) is in setup() function. Immediately after reboot servo goes to "neutral" angle. So problem lays in servo lib I guess. I'll try with min and max angle parameters.

You still aren't showing the code that you are having problems with.  It's like showing up at the mechanic to ask what's wrong with your car and not bringing the car with you.  Or asking the doctor to tell you what's wrong with your friend that you didn't bring with you.  It is impossible to diagnose what we can't see.  If you can't post the code that you have that you say isn't working then there isn't anything anyone can really do to help you.  Go edit your post and remove the Servo.cpp code.  We all have that code already.  And instead paste in the code that you have that doesn't work.

You can avoid using the attach(); method by programming without the servo library.
  for(x=0; x<150; x=x+1)
  {
    digitalWrite(Servomotor, HIGH);
    delayMicroseconds(2350); //Change the delay here to change the angle it goes to
    digitalWrite(Servomotor, LOW);
    delayMicroseconds(18550);
  }

This is an example code for how it worked for me. It sends a pulse to the servo which makes it turn a bit until it reaches a "barrier".


text:
MIDI keyboard controlled LED strip
My objective is to light a led on a strip corresponding to a keyboard note.
I have Arduino Uno with MIDI in module hooked up to a serial port. Piano is hooked with a standart midi cable, Led Strip is powered using Arduino's 5v (Figured i don't need more because Max 10 leds will be active at a time).
My setup works but not accurately. All is fine when only 1 note at a time is played, but the denser the music becomes (faster or more notes are played simultaniously) more inaccuracies show - more leds don't turn off or on, or the notes I didn't play light up.
At first i used software serial and there were even more mistakes, when i switched to hardware it became better.
Could it be that Arduino UNO is just not powerfull enough and cannot keep up with incoming midi input or is there another problem?
Here is the code:
#include <MIDI.h>
#include <Adafruit_NeoPixel.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define STRIP_PIN 11
#define STRIP_NUM_PIXELS 88

Adafruit_NeoPixel strip = Adafruit_NeoPixel(STRIP_NUM_PIXELS, STRIP_PIN, NEO_GRB + NEO_KHZ800);

void handleNoteOn(byte channel, byte pitch, byte velocity)
{
  strip.setPixelColor(pitch - 21, strip.Color(50, 50, 50));
  strip.show();
}

void handleNoteOff(byte channel, byte pitch, byte velocity)
{
  strip.setPixelColor(pitch - 21, strip.Color(0, 0, 0));
  strip.show();
}

// -----------------------------------------------------------------------------

void setup()
{
    MIDI.setHandleNoteOn(handleNoteOn);
    MIDI.setHandleNoteOff(handleNoteOff);
    MIDI.begin(MIDI_CHANNEL_OMNI);
    strip.begin();
}

void loop()
{
    MIDI.read();
}

I would collect events until a gap in stream of note events and show them at once

Missing notes or releases could be due to timing but the notifications of notes you didn't play is more worrying. Try removing the neopixel stuff and just recording the notes - does the midi stuff work reliably on its own? (You might have to think of some clever way to get the data out since you're using the serial port.)

Yeah i dont really know how to properly debug. I think the notes that i didnt play are because midi packet was read incorrectly so some other parametres were read as notes somehow. When i tested through SoftwareSerial everything seemed to work fine on the input when i just read midi data.

Also consider the problem is not inside your sketch, but inside your circuit; First try to just print the values, and check if all MIDI on/off messages are received. If you are sure that the circuit (and sketch regarding MIDI input is ok), add the LED strip code again.

The biggest problem is that updating the LEDs is an intensive task.

Hand-crafted assembly is written to get the timing right
Interrupts are disabled while the update is running
88 LEDs take a (relatively) long time to update.

At about 1.2µS per LED plus 50µS for the reset pulse, you're looking at about 155µS that the Arduino can't be doing anything else at all. That includes receiving anything through serial.  And since you update for every note you receive, if there is a second note coming in with 155µS of that one, it will be missed.
You may get better results with the FastLED library instead of the Adafruit Neopixel library, but ideally you want to work with a board that is fast enough to not need to do such tight bit-banging for the protocol, so that interrupts can still be enabled for receiving data.

Thanks for this knowledge! I need it to work perfectly without missing a beat... do you think Arduino DUE will be up for this task?

Only if the LED library you use allows it to work without disabling interrupts. The FastLED library might have a DMA mode that operates completely asynchronously, but I don't know if it works on the Due. Some more research would be needed.


text:
What data type are the analog pin labels (A0, A1, etc)?
Arduino Mega
I would like to have an array containing analog pin labels something like...
int analog_pins[] = {A0, A1, A2, A3};
int num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);

Is this possible? It has compiled without any warnings or errors but I'm dont have my board with me (yes beginners mistake) so cant really check if it works.

Read the wiki entry, it should give you a good understanding of the sizeof operator. https://en.wikipedia.org/wiki/Sizeof

As you can see in Arduino.h, the analogRead() has uint8_t as parameter. You can define them as byte or uint8_t and you don't have to use the sizeof().
The type of A0 is defined in the file pins_arduino.h:
#define PIN_A0 (14)
static const uint8_t A0 = PIN_A0;

Nevertheless, what you have with integers is 100% okay as well.
When you don't have a Arduino board available, you can use the simulation of an Arduino Uno at Tinkercad.

As @DataFiddler writes below this answer, using a 'const' keyword is preferred:
const uint8_t analog_pins[] = {A0, A1, A2, A3};

const uint8_t analog_pins[] might even be better, eventually allowing for a lot of compiler optimization

Your calculation will be correct for num_analog_pins, however it's convention to use the type of the array like so
int num_analog_pins = sizeof(analog_pins) / sizeof(int);

As @Jot noted, you'd save much space by declaring your array using uint8_t like so
uint8_t analog_pins[] = {A0, A1, A2, A3};
uint8_t num_analog_pins = sizeof(analog_pins) / sizeof(uint8_t);

sizeof(uint8_t) :-) very formal

@Juraj haha indeed!  I've always written such code for portability and clarity.

@RamblinRose You should write uint8_t num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);

@MarkSmith I'm confused by your comment - sizeof returns the number of bytes allocated for an array, sizeof(array) / sizeof(array_type) = number of array elements.

Apologies, I hadn't seen the denominator there. Comment deleted.


text:
CC1101 sniffing 868Mhz Protocol from thermostat
Hello i buyed a cc1101 because I want to sniff thermostat protocol which works with 868 Mhz.
I found this repo https://github.com/veonik/arduino-cc1101.
I tried to download the repo and include the zip file as libary.
First error was cc1101.h not found. So I moved the files from .src folder one level up.
Then I get error SPI.h no file directroy. So I imported this libary.
Now I have no errors and uploaded it to arduino mega.
Then I have no serial output. I have a cc1101 with 868 mhz. And I want to log the informations from a MAX! thermostat. Somebody can help me?
Here is photo from my wiring.

SPI on Mega is not on pins 11 to 13, but on 50 to 52. 50 is SO, 51 is SI. 53 is the usual CS as it is the SS if Mega is slave. why do you wire over breadboard? use black wire for ground, red for VCC. didn't you get a pin header with the module?

Ok thank you. No pin header. Should I change the programm?

no changes in sketch. change the wiring and wire the additional pin CC1101_GDO0 to 19

So I moved the files from .src folder one level up. -- Sounds like you're on Linux, and you installed Arduino from the Debian APT repository. Uninstall it and download a version from this decade from Arduino.cc

I changed the wiring. Now I get only CC1101_PARTNUM 0
CC1101_VERSION 20
CC1101_MARCSTATE 13
CC1101 radio initialized.
showed in serial monitor


text:
Esp8266 Vin pin
I've read that Vin pin is directly connected to usb cable in esp8266 (which is 5V). I wonder if I can power a relay 5V and a servo motor Sg90  with this pin? And is there any danger of doing that ?

esp8266 is a 3.3 V chip without USB. what dev board do you have?

I have esp8266 node mcu with usb adapter

most devkits have a diode connecting USB to Vin. you can burn this diode if you draw too much current. The current handling depends on how cheap they were at the factory, but anything above 1A will fry a cheapo board. Of course, you can solder bridge out the burnt diode, as long as you take care sending when plugging the USB into an actual PC.

The GPIO pins on the ESP8266 (including the ones with built-in NodeMCU) are 3.3v tolerant.
First, if there is ever any feedback from the 5v+ from the relay coming back down the signal wire, it'll likely cook the ESP.
Also, if it's a 5v relay, 3.3v from the ESP most likely wouldn't be enough to trigger the unit anyhow.
You'll either need to power the relay from an external power supply (or the Vin pin depending on the mA the relay requires), and then use a voltage converter (eg. logic level converter) so you can have 5v on the relay side (I'm speaking of the signal pin here), and 3.3v on the ESP side, or purchase a relay that will operate on 3.3v.

(Answering in more detail, as this is the top search hit for "ESP8266 Vin", at least for me)
TL;DR: Vin is NOT directly connected to USB power. There is a protection diode between USB+/VU and Vin, which has a limited current capacity.
If your board provides VU, that one is directly connected to USB power.
As long as you only power 1-2 tiny devices, it should be OK. (controlling will need additional components, or it will fry your ESP)

Since you talk about 'Vin' and '5V', I'm going to assume you have a devboard, not a 'naked' ESP8266. If your "esp8266" has a USB-connector and flash/reset buttons, then its a devboard-version. If it is only a fingernail-sized metal cover with a 1mm edge with solderpads, then its 'naked'.
The Vin pin is a power input for the onboard regulator.
On all common devboards, there is a protection diode between the USB+ wire, and Vin.
Some devboards also provide a VU-pin, which is directly connected to the USB+ wire without anything in-between.
The 3.3V regulator converts any input voltage (5V-19V) connected to Vin into the 3.3V needed by the ESP chip and the 3V3-pins. The regulator has capacity (barely) for the ESP and a (large) handful of leds, not much more.

There is always danger when connecting mechanical/magnetic 'power'-devices (relays, servos and motors) in the same circuit with 'sensitive' microcontrollers/logic gates.
'power' devices are noisy and cause feedback which must be filtered, blocked and absorbed so it will not fry 'small' electronics. (even a toothbrush motor is 'power', compared to microchips).
'Power' devices are also hungry, causing voltage drops when activated. These drops can cause glitches, bugs and even resets in logic-level electronics.
This not stop many people from trying it anyway, and it will often work, for a while, until it someday 'mysteriously' stops working because the chip finally gave out under the repeated abuse.
(side note: as other have mentioned: You also cannot control magnetic/mechanical devices directly from the signal pins. Microcontroller outputs are too weak. Trying anyway can destroy your microcontroller with the feedback.)

A detailed background explanation for powering ESP devboards, including wiring schematics and explanations, can be found here:
https://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

Relays, motors, and other inductive loads release a surge of reverse current when you remove power from them. You have to connect a suitably sized “flyback diode” across the coil, wired backwards from the normal current flow direction to protect the other devices on the circuit from that reverse current or they will likely be damaged.
Relays and motors also draw a large in-rush of current when they are first connected, which can cause the supply voltage to droop.
You can buy relays that are made to be controlled by logic levels. They take a low power 5V or 3.3V logic level input, plus a separate power supply, and use the logic input to switch the relay on and off safely. The relay modules I’m using have optical isolation for the logic lines for extra protection.


text:
Measure small capacitances with ATtiny85 (Digispark board)
I have successfully run the code provided here on an Arduino Nano. If nothing is connected, it will output a very small capacitance (~ 1 pF).
Then I tried to migrate the code to the ATtiny85 (using a Digispark USB Development Board), but I fail to get anything reasonable out of the code. The first analogRead will always give 1023, whereas on the Nano it gives a very small value (again for nothing connected to the input pins).
It's a bit trickier on the ATtiny85 because the pin numbers are different for digital and analog, but I thought I got that right, so what went wrong in the migration?
const int OUT_PIN = 2; // digital pin PB2 is 2, positive pin of C
const int IN_PIN  = 5; // digital pin PB5 is 5, negative pin of C
const int OUT_ANA = 1; // analog read PB2 is 1
const int IN_ANA  = 0; // analog read PB5 is 0

const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

#include "DigiKeyboard.h"

void setup() {
  pinMode(1, OUTPUT);
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(IN_PIN, LOW);
  DigiKeyboard.update();
}

void loop() {

    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_ANA); // IN_PIN in Nano version
    digitalWrite(OUT_PIN, LOW);

    DigiKeyboard.println(val);
    if (val < 1000) {
      pinMode(IN_PIN, OUTPUT);
      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);
      DigiKeyboard.print(capacitance);
      DigiKeyboard.println(" pF");
    } else {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      } while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_ANA); // OUT_PIN in Nano version
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      if (capacitance > 1000.0) {
        DigiKeyboard.print(capacitance / 1000.0);
        DigiKeyboard.println(" uF");
      } else {
        DigiKeyboard.print(capacitance);
        DigiKeyboard.println(" nF");
      }
      DigiKeyboard.println(val); // usually ~ 520 (because we wait until digVal == 1?)
      DigiKeyboard.println(t); // depends on C: ~ 26000 for 1 µF, ~ 2600 for 100 nF, ~ 250000 for 10 µF
  }

  digitalWrite(1, 1);
  delay(10);
  while (micros() % 1000 != 0);
  digitalWrite(1, 0);

}

The reason this doesn't work is that PB5 is pulled high (as it's used as -RESET pin on the board). The code can be rewritten to use only one ADC pin though.


text:
Data type problem
I have a program I would like to ask:
  I use the Bluetooth control LED to light up.
In the picture, the serial port window shows r, but the LED does not light up. What went wrong? Ask everyone, thank you very much.

you read val from Serial but not send it from Serial. do val = BTSerial.read(); Serial.write(val);

it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。

Please answer in English. This is an English speaking site.

@Majenko as of what I understood he just changed his code according to what the user has commented under the question post


text:
Can a Lithium Polymer battery charging circuit on Arduino boards also charge Lithium Lion batteries?
I have a project that the form factor of 18650 batteries works well for. The board I'm using is a esp32 based board with built in battery charging:
https://www.amazon.com/gp/product/B072HBW53G/ref=ppx_yo_dt_b_asin_title_o00_s02?ie=UTF8&psc=1

I've heard that the flatpack type Lithium Polymer batteries have built in over charge circuitry. Is this generally true?
Can I directly charge a 18650 battery from Arduino type boards that have built in battery charging functionality?

EDIT:  So from looking at the battery circuit schematic from the Wemos link and the board itself it uses a TP4054 "Standalone Linear Li-lon Battery Charger with Thermal Regulation in SOT".  And since I can confirm the board works with 3.7V batteries and my 18650 is a 3.7V type I think I'm good.
EDIT:  Found info on this board:
http://www.raspberrypiwiki.com/index.php/WEMOS_ESP32_Board_with_OLED
Also by "Arduino type" boards I mean any popular micro controller board that has a battery charging function such as the Adafruit feather boards.
EDIT:  To clarify:
Reading here Li Poly and Li Ion batteries are essentially the same
https://scottiestech.info/2015/06/21/lithium-polymer-vs-lithium-ion-batteries-whats-the-deal/
I believe the board is a Wemos D32 with an attached display though I can't find any specific info on this exact board.
https://wiki.wemos.cc/products:d32:d32#technical_specs
I basically want to know if I can charge a Lithium Ion battery with this type of board.  As this is potentially a safety concern I wanted to ask some experts.

The question in your title doesn't match the rest. The title ask about LiPo but the text asks about 18650s which are not LiPo. The answer to the question in your title is not if the built in charger is made for LiPo batteries and has overcharge protection. Can you add links to the actual schematics and specs for your board? My understanding is that LiPo and regulat LiOn charging have different requirements. What do you mean by Arduino type boards? The answers really come down to getting more specs for your board to tell what kind of charging it can do well.

Thanks for the feedback, I changed the title to something hopefully more descriptive and added some info.

I have the Lolin D32 pro, and my understanding of this document on TP4054 http://igotalongdomainname.com/data/uploads/tp4054-42pdf.pdf seems it have overcharge protection at least. Also since it claims it works with 3.7V batteries which is nominal voltage, it should work with the higher than 3.7V actual voltage that 18650 batteries have when fully charged. Also just for the record you can buy charge protection circuit boards for 18650 cells. https://www.youtube.com/watch?v=1rg3ZWxBNUE  Do you have a jst connector to connect your 18650 cell to the board? If you try it, please update the post.

There are Lead based, Nickel-based and Lithium-based batteries (there are actually more, but these ones are the most popular). Each need a different charger, but since lithium polymer and lithium ion are in the same group, it should work but I don't have the option to test it out for you.
Q1: Not every battery has a built in over- and undercharge function. Some do, some don't. To find out if yours does, if the internet can't help, tear it apart (be extremely careful about it).
Q2: Depends what you mean by " built in battery charging functionality". If that includes the over- and undercharge functionality, then it will work (tested).
Looking at the board (https://wiki.wemos.cc/products:d32:d32#technical_specs) it seems doable.
The most important thing is to check, if the supported voltage of the li ion battery equals the supported voltage of the li polymer battery that can be charged with the li polymer charger. Since it says 3.7V on the data sheet, don't get a li ion battery with 3.7V+


text:
delay() not working inside loop() block
Edited and attached code here.
This section didn't execute.
The delay(15000); doesn't execute, I mean the sketch didn't execute this line no matter where to put it.
    // include the SPI library:
    #include <SPI.h>

    // set pin 53 as the slave select for the digital pot:
    const int slaveSelectPin = 53; //WAS 10 on Arduino uno.
    const int shutdownPin = 7; // was 7 on uno.
    const int wiper0writeAddr = B00000000;
    const int wiper1writeAddr = B00010000;
    const int tconwriteAddr = B01000000;

    const int tcon_0off_1on = B11110000;
    const int tcon_0on_1off = B00001111;
    const int tcon_0off_1off = B00000000;
    const int tcon_0on_1on = B11111111;

    const int analogInPin_c = A5;  // center Vc=Vss/2 from the PAD, use for set ini V. here no use, Vc directly goes to pad.

    const int analogInPin_x = A1;  // Analog input pin that the potentiometer is attached to
    const int analogInPin_y = A2;  // Analog input pin that the potentiometer is attached to

    const int analogOutPin_x = wiper0writeAddr; // write MCP POT
    const int analogOutPin_y = wiper1writeAddr; // write MCP POT

    int sensorValue_c = 0;        // value read from the PAD, Vc=Vss/2
    int sensorValue_x = 0;        // value read from the PAD, Vc=Vss/2
    int sensorValue_y = 0;        // value read from the PAD, Vc=Vss/2

    //?int outputValue_c = 0;        // value output to the PWM (analog out)
    int outputValue_x = 0;        // mid variable stored the value from 'sensorValue_c' and MAP that for use
    int outputValue_y = 0;        // mid variable stored the value from 'sensorValue_c' and MAP that for use

    int Vcr = 0;        // value read from the PAD, Vc=Vss/2
    int Vc = 0;        // value read from the PAD, Vc=Vss/2
    const int LEDpin1 = 47;
    const int LEDpin2 = 46;
    int count = 0;

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

      // set the slaveSelectPin as an output:
      pinMode (slaveSelectPin, OUTPUT);
      // set the shutdownPin as an output:
      pinMode (shutdownPin, OUTPUT);
      // start with all the pots shutdown
      digitalWrite(shutdownPin, LOW);
      // initialize SPI:
      SPI.begin();
      Serial.println("Setup complete");
      //??
      Serial.println("Starting loop");
      digitalWrite(shutdownPin, HIGH); //Turn off shutdown
    }

    void loop() {
      AnalogInOut(); //
      ArduinoDAC(); //
    }
    void AnalogInOut() {
      // take from some where used for testing joystick control LED,
      //need change to get date fron RC and write to MCP pots
      // read the analog in value:

      Vcr = analogRead(analogInPin_c);
      delay(1000);
      Serial.print("Vcr= ");
      Serial.println(Vcr);
      Vc = map(Vcr, 0, 1023, 165, 225);
      Serial.print("Vc = ");
      Serial.println(Vc);
      delay(10);
      Serial.print("count_ini= ");
      Serial.println(count);

      if (count = 0)  {

        if (Vc > 188)   {

          digitalWrite(LEDpin1, HIGH);
          Serial.print("Vc TOO HIGH: ");
          Serial.println(Vc);
          exit(0);
          delay(100);
        }

       if (Vc < 165) {

          digitalWrite(LEDpin2, HIGH);
          Serial.print("Vc TOO LOW = : ");
          Serial.println(Vc);
          exit(0);
          delay(10);
        }
        else {

          Serial.print("analogInPin_c_T00: ");
          Serial.println(analogInPin_c);

          /// digitalPotWrite(wiper0writeAddr, Vc);
          ///digitalPotWrite(wiper1writeAddr, Vc);

          digitalPotWrite(wiper0writeAddr, 100);
          digitalPotWrite(wiper1writeAddr, 220);

          count = 1;
          Serial.print("count_new= ");
          Serial.println(count);
        }
        delay(15000);
      }

      ////////////////////////////////////////////////////////////////////////////////////////////////////////////

      sensorValue_x = analogRead(analogInPin_x);
      sensorValue_y = analogRead(analogInPin_y);
      // map it to the range of the analog out:
      outputValue_x = map(sensorValue_x, 0, 1023, 70, 248);
      outputValue_y = map(sensorValue_y, 0, 1023, 70, 248);  // change the analog received to the value suite for PAD joystick

      //   print the results to the Serial Monitor:
      Serial.println("sensor_x =_T10 ");
      Serial.println(sensorValue_x);
      Serial.println("sensor_y = ");
      Serial.println(sensorValue_y);
      Serial.println("\t output = ");
      Serial.println(outputValue_x);
      Serial.println(outputValue_y);

      // wait 2 milliseconds before the next loop for the analog-to-digital
      // converter to settle after the last reading:
      delay(2);
    }

    void ArduinoDAC() {
      Serial.println("Starting loop");
      digitalWrite(shutdownPin, HIGH); //Turn off shutdown

      digitalPotWrite(wiper0writeAddr, outputValue_x); // Set wiper 0 to 200

      delay(5);

      digitalPotWrite(wiper1writeAddr, outputValue_y); // Set wiper 1 to 200

      delay(5);
    }

    // This function takes care of sending SPI data to the pot.
    void digitalPotWrite(int address, int value) {
      /// Serial.print("wiper0 position_t30: ");////
      /// Serial.println();////
      // take the SS pin low to select the chip:
      digitalWrite(slaveSelectPin, LOW);
      //  send in the address and value via SPI:
      SPI.transfer(address);
      SPI.transfer(value);
      delay(30);
      // take the SS pin high to de-select the chip:
    }

    int digitalPotRead(int address) {
      // take the SS pin low to select the chip:
      digitalWrite(slaveSelectPin, LOW);
      //  send in the address via SPI:
      SPI.transfer(address);
      // send zero to read data from the address
      delay(30);
    }

Please show us a small and working sketch. When I see those lines, then I think: "while what?". What is the condition? https://www.arduino.cc/reference/en/language/structure/control-structure/while/

yes, it can work, because you are allowed if in while

which delay(5000);? ... there are two .... also, how do you know that the command does not execute?

take a coding course

Thank you for reply, I attached the code.

Now I see no delay(5000) on attached code.

@jsotola and mico , Sorry, it was delay (15000) in the original code.

Did you notice this error in your code?  if (count = 0).

if (count = 0) is never true. = is assignment to count and the result of assignment is the assigned value. the value is 0

The code should read if (count == 0). With a single equals it is an assignment, and the if statement evaluates the value of the right-hand-side.

Basically it works.
Here you find a little sketch to see how it works. Try to transfere it to your solution.
#include <M5Stack.h>  // only necessary for my board (M5Stack)

bool condition_while = true;
bool condition_loop = true;
int condition_if = 0;

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
}

void loop() {
   while (condition_while) {
       if (condition_if == 0) {
           Serial.println("testcase #1: if path reached");
           condition_if = 1;
       }
       else if (condition_if == 1 ) {
           Serial.println("testcase #2: if else path reached");
           condition_if = 2;
       }
       else {
           Serial.println("testcase #3: else path reached");
           condition_while = false;
       }
       Serial.println("testcase #4: path reached inside while");
   }
   if (condition_loop) {
       Serial.println("testcase #5: path reached outside while");
       condition_loop = false;
   }
}

This is the output on COM3

Thank you, I'll ref. this to my code.

I can't find the line with delay(5000), can you add the line number, I also don't find a while?

@laoadam and have a look at line 77:  'if (count = 0)  {', if you want to check if count is equal to Zero you have to write  'if (count == 0)  {'

Thank you RJPlog, I did it.

@laoadam Is it working now?

I would suggest you go through the coding tutorials on arduino website. It would be absolutely possible to have the above structure in an arduino code.
This link has a working and validated example showing while loop calling other function using if-else-if structure.
https://www.arduino.cc/en/Tutorial/WhileStatementConditional?from=Tutorial.WhileLoop
Please go through the tutorials and post specific problem if and when you encounter them.

If the code (not shown) within the if/else if/else structure doesn't affect the flow of control, then either delay() placement will work.  But the placement within the loop will delay at every cycle of the loop. The placement below the loop will only delay after the loop finishes executing.

I monitor the sketch execute，even that run through but delay() in this section didn't.


text:
making power harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are)
i have been  intendng to make a power frequency harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are examples for making spectrum analyser with fft library's here is the example for the kosome made fft library
   #include <arduinoFFT.h>

   #define SAMPLES 128             //Must be a power of 2
   #define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

   arduinoFFT FFT = arduinoFFT();

   unsigned int sampling_period_us;
   unsigned long microseconds;

   double vReal[SAMPLES];
   double vImag[SAMPLES];

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

        sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
   }

   void loop() {

        /*SAMPLING*/
        for(int i=0; i<SAMPLES; i++)
        {
            microseconds = micros();    //Overflows after around 70 minutes!

            vReal[i] = analogRead(0);
            vImag[i] = 0;

            while(micros() < (microseconds + sampling_period_us)){
            }
        }

        /*FFT*/
        FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
        FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
        FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
        double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

        /*PRINT RESULTS*/
        //Serial.println(peak);     //Print out what frequency is the most dominant.

        for(int i=0; i<(SAMPLES/2); i++)
        {
            /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

            //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
            //Serial.print(" ");
            Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
        }

        //delay(1000);  //Repeat the process every second OR:
        while(1);       //Run code once
   }

how can i seperate the amplitudes for particular frequencies like amplitude of 50hz = ?, 150hz = ? and store them in other variables

please use the {} button to format your code

The general idea of your code looks OK, but consider using a hardware timer rather than the for loop for data acquisition.  The sampling rate will be much more accurate and uniform because you eliminate (possibly cumulative) errors in timing.  See this post for an example.
Do you know how the FFT.MajorPeak function works?  If it simply finds the frequency of the largest point in the magnitude spectrum, this may not be a good measure of the 50 Hz peak etc.  Instead, consider taking the area under the curve around the frequency of interest f_0, say f_0 - 2 Hz to f_0 + 2 Hz.  The same code should be usable to measure the spectral power around any of the harmonics.
Also note that the mains electricity frequency is not exactly 50 Hz / 60 Hz.  The short-term variation is around plus/minus 1 Hz.  The above approach will also help make reliable readings.


text:
Having trouble reading directly from VEML6075 UV sensor from its registers(I2C)
I'm kinda new to Arduino and decided to dive deeper into learning abit more about Arduino; So i decided to grab a Sparkfun VEML6075 UV sensor and try to:
1) Initialise it
2) Take readings from it
Without using the Sparkfun libraries at all. Based on what I read in the datasheets, this seems possible by using the I2C communication protocol provided by communicating directly with the registers of the device itself.
However, I can't seem to be able to even initialise the device properly as the readings I have gotten are weird and do not change (I presume this means the device only took one reading and stops at that)
My code is as below:
#include <Wire.h>

byte address = 0x10; // Slave address of the VEML6075
byte UVA_LSB, UVA_MSB;
word UVA_data;
uint16_t UVA_combined;
void setup() {
    Serial.begin(9600);
    Wire.begin();
    VEML6075_init(address);
//    uv.begin();
    Serial.println("Module is detected");
}

void loop() {
    VEML6075_Fetch_UV(address);   // Fetch UVA data *TEST*
    Serial.print("UVA: ");
    Serial.println(UVA_combined);
    delay(1000);
}

// shutdown module and init it; restarting the module
void VEML6075_init(byte address){
    Wire.beginTransmission(address);  // Shutdown command
    Wire.write(highByte(0x00));
    Wire.write(lowByte(0x01));
    Wire.endTransmission();

    Wire.beginTransmission(address);
    Wire.write(highByte(0x00));
    Wire.write(lowByte(0x12));   // Reset command using conf register
    Wire.endTransmission();
    delay(200); // Wait for module to reset
    // Done //
  }

 void VEML6075_Fetch_UV(byte address){
    Wire.beginTransmission(address);   // Begin transmission into I2C line with Slave address
    Wire.write(highByte(0x07));     // Issue command to read UVA data
    Wire.write(lowByte(0x07));
    Wire.requestFrom(address, 2);
    while(!Wire.available()); // Needs refining; read twice for 16 bits
    UVA_LSB = Wire.read();
    UVA_MSB = Wire.read();
    Wire.endTransmission();

    UVA_combined = ((UVA_MSB << 8) | UVA_LSB); // Combine to 16bits
  }

As stated in the datasheet:

The VEML6075 contains a CONF register (00h) used for operation control and parameter setup. Measurement results are stored
  in four separate registers, one each for UVA, UVB, UVcomp1, and UVcomp2 (07h to 0Bh respectively). All registers are accessible
  via I2C communication. Fig. 7 shows the basic I2C communication with the VEML6075. Each of the registers in the
  VEML6075 are 16 bit wide, so 16 bit should be written when a write command is sent, and 16 bit should be read when a read
  command is sent.

I have allocated 16 bits for receiving the data, and have also used the conf address 0x12 to set the timing to 100ms and activate active-force-mode which i presume is the device taking readings automatically. The readings given are way off the accurate readings given when i upload a example code that uses the Sparkfun library, so I'm quite lost at this point. How am I using the I2C protocol wrongly? Thanks!

add Wire.endTransmission(false); to send the written bytes before Wire.requestFrom(address, 2);

after Wire.requestFrom(address, 2); returns, the data are available for read

... thus the line with while(!Wire.available()) can be removed. The highbyte and lowbyte are used in the wrong way. When a 16-bit variable is for example 0x1234, then the highbyte is 12 and the lowbyte is 34. You use already bytes.

Could you explain further about what you mean by I'm using highbytes wrongly and in where? In my intitalisation function I used Wire.write(highByte(0x00));
Wire.write(lowByte(0x12));  to emulate 0x0012 for 16bits conf register. Is that correct?

0x00 is already a byte and 0x12 is already a byte. You can do highByte(0x0012) and lowByte(0x0012). If you already pick the bytes from 0x0012 then you can do Wire.write(0x00); // high byte and Wire.write(0x12); // low byte

Do you use a i2c level shifter?


text:
Arduino and Solenoid Water Valve
I use Arduino UNO and two SPST Relay (Wemos Mini D1 Relay) to make the reverse polarity circuit. I use this circuit to open and close the Solenoid Water Valve (SWV), which work with 9 to 12 volt. The connections are as follows:
NO (Relay1) --> NC (Relay2) --> +12 Volt
NC (Relay1) --> NO (Relay2) --> 0
D1 (Relay1) --> D1 (Relay2) --> Digital pin 3 of Arduino
COM (Relay1) --> SWV1
COM (Relay2) --> SWV2
GND Relay1) --> GND (Relay2) --> GND of Arduino
5V (Relay1) --> 5V (Relay2) --> 5 Volt of Arduino

the circuit work perfectly with Arduino boar. But the problem is that when I use ATMEGA328p-PU on breadboard as explained in LINK, Relays are not working properly. Actually, relays connecting and disconnecting continuously when ATMEGA328p sends 1 to D1 pins of Relays.
The point is when I de-attach the SWV, relays work properly. but if the SWV is connected it still is not working.
I've checked the connection many times and they are correct.
I used the following code in arduino:
int Relay = 3;
void setup() {
  // put your setup code here, to run once:
  pinMode(Relay, OUTPUT);
  digitalWrite(Relay, LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  digitalWrite(Relay, HIGH);
  delay(2000);
  digitalWrite(Relay, LOW);

}

Any help is highly appreciated.
Thanks in advance.

Could you show a schematic (or drawing) and a photo please. When someone puts a atmega328p on a breadboard for the first time and adds a relais or motor, then it almost never works. There are currents going the wrong way, there is a lot of noise, peak pulses bounching through the breadboard, unstable crystal, and so on.

I did exactly the same as the link mentioned in the post.

sigh... In typical Arduino fashion, the "official" documentation is woefully inaccurate and misleading. Oh dear. I wish they would stop trying to produce these tutorials - they make our lives so hard...

what is a reverse polarity circuit?

Are you using latching solenoid valves? Try using an H-bridge to reverse the polarity.

The problem is most likely EMI (electromagnetic interference) from the switching of the inductive load by the relays.
The fact that you have your setup on a breadboard means that each and every pin of the ATMega328 is connected to a little antenna. That massively increases its susceptibility to falling prey to EMI.  Add to that the fact that there is absolutely no decoupling of the power supply (thanks to Arduino producing shoddy worthless tutorials) makes the whole chip very fragile.
When running with a real Arduino board you have decoupling on the power which helps to reduce induced power rail bounce which can cause the chip to fail.
There are two things that can help mitigate this:

Add decent decoupling to the ATMega328

This means adding capacitors between each VCC pin and ground. At the bare minimum a 100nF capacitor on each VCC pin is needed. Additionally a 1nF capacitor can be beneficial. A 10µF capacitor should also be added on the breadboard's power rails to act as a board-level reservoir.

Snubber networks on the switching

A snubber network, in its most simple form, is a resistor and capacitor in series.  It is placed across the switching terminals of a device that is switching an inductive load to absorb the sudden spike of back-EMF from the collapsing magnetic field whenever the load is switched off.

simulate this circuit – Schematic created using CircuitLab
Note that the capacitors here should be rated for at least 400V since the voltages involved are quite high.

An inductor can create large pulses of power when turned off and on such as in a relay or a solenoid.  A flyback diode is usually added across inductors to suppress these pulses.  Indeed if you look at the schematic of the Wemos Relay Board used in this project you see where D1 is used in just such a way.  Unfortunately the voltage is being applied in both directions across the solenoid so a flyback diode can not be used directly across the solenoid.  However, it may be possible to add a flyback diode before the relays where the voltage is not reversing.
It is almost always better to mitigate electrical noise such as Electromagnetic Field (EMF) interference at its source.  Hence the flyback diode.  However, many combination logic and processor designers add decoupling capacitors as close as possible to the power terminal of each logic chip. This may be the reason a real Arduino board works while the bread board does not.

If the case that you mentioned is a problem the circuit with Arduino board should have not worked while, as I've mentioned, it works properly and the problem is with ATMEGA328 on breadboard.

The way I understand it, the solenoid is galvanically isolated from the Arduino by the relays. Thus no back-EMF can get to the Arduino. More likely it is EMI from the switching arcs crashing the ATMega on the breadboard due to a lack of proper decoupling and power management which the Arduino "tutiorial" (hah!) completely lacks. As always, Arduino completely misleads their poor users with the garbage they produce in the name of "tutorials".

@user42037 I will modify my answer to reason out why a real Arduino board works while your bread board does not.  But, please note, it is almost always better to mitigate electrical noise at its source.  To do otherwise almost always takes more effort.


text:
Sending command through SPI on Arduino UNO
I am assuming the default pin configuration is pin 10(SS), 11(MOSI), 12(MISO), 13(CLK) from a default setup, SPI.begin(). The code compiles OK. Not sure about the int valuex and using the SPI.transfer() function.
#include <SPI.h>

int value1 = 0x8026;
int value2 = 0x0801;
int value3 = 0x8027;
int value4 = 0x0000;

void setup (void)
{
  Serial.begin (9600);
  Serial.println ("Starting");
  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV4);

}  // end of setup

void loop (void)
{
  // enable Slave Select
  digitalWrite(SS, LOW);

  SPI.transfer (1);   // initiate transmission
  SPI.transfer (value1);
  SPI.transfer (value2);
  SPI.transfer (value3);
  SPI.transfer (value4);

  // disable Slave Select
  digitalWrite(SS, HIGH);

delay (1000);
}

transfer sends a byte only. See SPI.transfer16(intval); if necessary

Not sure about the int valuex and using the SPI.transfer() function.

A couple of things to know:

You are storing an unsigned 16-bit literal into a signed 16-bit variable. You should be using uint16_t value1 = 0x8026; etc. Also, unless you are planning to change the values, they should be const.
SPI.transfer() transfers only 8 bits of data. You are only sending the lowest byte of your valuex variables. SPI.transfer16() sends an unsigned 16-bit value.

To illustrate, this is how your program should look:
#include <SPI.h>

const uint16_t value1 = 0x8026;
const uint16_t value2 = 0x0801;
const uint16_t value3 = 0x8027;
const uint16_t value4 = 0x0000;

void setup(void) {
    Serial.begin(9600);
    Serial.println("Starting");
    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    // Put SCK, MOSI, SS pins into output mode
    // also put SCK, MOSI into LOW state, and SS into HIGH state.
    // Then put SPI hardware into Master mode and turn SPI on
    SPI.begin();
    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV4);
}  // end of setup

void loop(void) {
    // enable Slave Select
    digitalWrite(SS, LOW);
    SPI.transfer(1);    // initiate transmission
    SPI.transfer16(value1);
    SPI.transfer16(value2);
    SPI.transfer16(value3);
    SPI.transfer16(value4);
    // disable Slave Select
    digitalWrite(SS, HIGH);
    Delay(1000);
}

That will transfer the stream of 8-bit values:
0x01 0x80 0x26 0x08 0x01 0x80 0x27 0x00 0x00

Hi, and thank you.  I believe the code is right but I do not get any signaling out of MOSI pin 11; it does go from high to low.  I can 'see' (with an oscilloscope) SS pin 10 go low, I can see only 3 clock pulses on pin 13.  I am not concerned with any incoming data.

Also, when I added 16 to SPI.transfer, transfer changed from blue to black color.

The code works perfect!  Thank you and I wish I had sent this sooner.  Thanks again!

@howdyrichard Accept the answer if it worked for you


text:
Sniffing thermostat protocol CC1101 868MHZ
I am using this libary from github:https://github.com/veonik/arduino-cc1101
With this example code. I will try to read the data which is send from a 868Mhz thermostat. I am using a arduino Mega and wired it like in the following picture.

First I get this error:

When i upload the code. I get this Serial Output. But no packages send and no packacges recived. Can somebody help me?
   CC1101_PARTNUM 0
CC1101_VERSION 20
CC1101_MARCSTATE 9
CC1101 radio initialized.

example code:
 #include <Arduino.h>
    #include <cc1101.h>
    #include <ccpacket.h>

    // Attach CC1101 pins to their corresponding SPI pins
    // Uno pins:
    // CSN (SS) => 10
    // MOSI => 11
    // MISO => 12
    // SCK => 13
    // GD0 => A valid interrupt pin for your platform (defined below this)

    #if defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
    #define CC1101Interrupt 4 // Pin 19
    #define CC1101_GDO0 19
    #elif defined(__MK64FX512__)
    // Teensy 3.5
    #define CC1101Interrupt 9 // Pin 9
    #define CC1101_GDO0 9
    #else
    #define CC1101Interrupt 0 // Pin 2
    #define CC1101_GDO0 2
    #endif

    CC1101 radio;

    byte syncWord[2] = {199, 10};
    bool packetWaiting;

    unsigned long lastSend = 0;
    unsigned int sendDelay = 5000;

    void messageReceived() {
        packetWaiting = true;
    }

    void setup() {
        radio.init();
        radio.setSyncWord(syncWord);
        radio.setCarrierFreq(CFREQ_868);
        radio.disableAddressCheck();
        radio.setTxPowerAmp(PA_LongDistance);

        Serial.begin(9600);
        Serial.print(F("CC1101_PARTNUM "));
        Serial.println(radio.readReg(CC1101_PARTNUM, CC1101_STATUS_REGISTER));
        Serial.print(F("CC1101_VERSION "));
        Serial.println(radio.readReg(CC1101_VERSION, CC1101_STATUS_REGISTER));
        Serial.print(F("CC1101_MARCSTATE "));
        Serial.println(radio.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f);

        Serial.println(F("CC1101 radio initialized."));
        attachInterrupt(CC1101Interrupt, messageReceived, FALLING);
    }

    // Get signal strength indicator in dBm.
    // See: http://www.ti.com/lit/an/swra114d/swra114d.pdf
    int rssi(char raw) {
        uint8_t rssi_dec;
        // TODO: This rssi_offset is dependent on baud and MHz; this is for 38.4kbps and 433 MHz.
        uint8_t rssi_offset = 74;
        rssi_dec = (uint8_t) raw;
        if (rssi_dec >= 128)
            return ((int)( rssi_dec - 256) / 2) - rssi_offset;
        else
            return (rssi_dec / 2) - rssi_offset;
    }

    // Get link quality indicator.
    int lqi(char raw) {
        return 0x3F - raw;
    }

    void loop() {
        if (packetWaiting) {
            detachInterrupt(CC1101Interrupt);
            packetWaiting = false;
            CCPACKET packet;
            if (radio.receiveData(&packet) > 0) {
                Serial.println(F("Received packet..."));
                if (!packet.crc_ok) {
                    Serial.println(F("crc not ok"));
                }
                Serial.print(F("lqi: "));
                Serial.println(lqi(packet.lqi));
                Serial.print(F("rssi: "));
                Serial.print(rssi(packet.rssi));
                Serial.println(F("dBm"));

                if (packet.crc_ok && packet.length > 0) {
                    Serial.print(F("packet: len "));
                    Serial.println(packet.length);
                    Serial.println(F("data: "));
                    Serial.println((const char *) packet.data);
                }
            }

            attachInterrupt(CC1101Interrupt, messageReceived, FALLING);
        }
        unsigned long now = millis();
        if (now > lastSend + sendDelay) {
            detachInterrupt(CC1101Interrupt);

            lastSend = now;
            const char *message = "hello world";
            CCPACKET packet;
            // We also need to include the 0 byte at the end of the string
            packet.length = strlen(message)  + 1;
            strncpy((char *) packet.data, message, packet.length);

            radio.sendData(packet);
            Serial.println(F("Sent packet..."));

            attachInterrupt(CC1101Interrupt, messageReceived, FALLING);
        }
    }

That is not serial output. That is compiler output. To see serial output open the serial monitor.

Also note that 868MHz is not the frequency. It is the band.  That band is typically subdivided into a number of channels with a specific bandwidth (no standard, but implementation specific). The actual frequency could be anywhere between 865MHz and 870MHz.  You should use an SDR dongle (I use RTL2832U) to both locate and capture the data. Also note that there are multiple different modulation techniques that you will need to account for.

I updated the question. @Majenko thank you. When I capture the data with the RTL2842U, how can I then capture the data with the cc1101. Because I dont get any data with the cc1101. I understood that the RTL2843U is to understand the protocol. But how can I read the data with the cc1101? Or do you mean it is impossible to read the data from thermostat with cc1101?

I'm so confused: https://arduino.stackexchange.com/questions/62605/cc1101-sniffing-868mhz-protocol-from-thermostat

This was another problem I already solved...

Why is this not part of your question from yesterday on the exact same topic?

because it is another problem. I can delete this topic and change the question from yesterday. If you want it.

Before you can start messing around with a CC1101 you first have to know exactly what it is you are trying to capture. You can't configure the CC1101 until you know some basic facts about the transmission. Such things as: what is the carrier frequency? What is the modulation system used? Is there a sync word at the start of a packet, and what is it? How long is the packet? Is there a CRC that needs calculating? Without that information the CC1101 can't receive any data.

Just because the CC1101 runs in the same frequency band it doesn't necessarilly follow that it will be able to receive the data. After all Bluetooth and WiFi both run in the 2.4GHz range. So does the nRF24L01. And none of them can communicate with each other.

@Majenko, it appears that the CC1101 has "asynchronous mode" which allows the raw data to be read


text:
Arduino based hour counter
I would like to make a hour counter for a particular machine.I have a problem in coding.arduino internal clock can work only till 49 days.my hour counter should calculate 150+ hours.I thought of using a condition to store a particular value and add with next value.How can I code adding values to a variable

If you make a millis() based timer, and use it like the BlinkWithoutDelay sketch does, then you shouldn't have a problem. I think the BlinkWithoutDelay sketch comes with the Arduino IDE.


text:
More than 3 SPI devices read by a single arduino
I've been working on a project that involves SSI Rotary Encoders from CUI. They are being read through the SPI interface, and I am bit-shifting appropriately to account for the differences between SSI and SPI. Unfortunately, I am pretty limited in knowledge of how the SPI interface works, but I am attempting to connect 5 of these encoders to the Arduino (nano) to create a simple robot.
Everything was working great when I had 3 encoders, however, when I add a fourth to the same Arduino, all of the encoders stop reading. I am struggling to determine my next steps. According to one source, it appears that an Arduino is allowed a maximum of three SPI devices, but I am wondering if it is possible to have the other two read through a software interface? Here's a link to the source I found: https://esp32.com/viewtopic.php?t=1972. If you have any suggestions, please let me know!

how are you connecting the devices?

From what I see you can use Arduinos shifIn function for "software serial". But I don't see why it shouldn't work with more that 3 encoders. Ehe esp32 forum post said, that's just a software limit. You'd have to set the Chip Select pin for that encoder manually. Some something like digitalWrite(CS_ENCODER_4, LOW); SPI.readSomething(); digitalWrite(CS_ENCODER_4, HIGH);

that's a link to the ESP32 docs, not nano, and it's a limit for distinct SPI lines, not multi-device lines like you should probably be using.


text:
Arduino Due Atmel IC heats up
When i tried powering the board the Atmel IC heats up and led goes of after a second .the board does not get detected on my IDE software .
1) I have tried out finding the issues with the board and solving for same but the board does not revive .
Issues like voltage regulator gets shorted (Pin 1 and 2) .So initially i have thought that removing voltage regulator would solve the problem but still there is short between pin 1 and 2 of 3.3 voltage regulator.
2) tried removing the capacitors connecting vcc  and gnd but with no success of removing the short.
Could Someone would possibly help me to revive the board and fix for the same .

Maybe it wasn't short in regulator, but in MCU. Try to use the alcohol test (pour 100% ethanol on it and place(s) that evaporates fastest might be the short)

Ok will try it surely


text:
Can ESP8266 send AT commands to self?
I'm having some problems with my ESP8266 stopping transmission of MQTT messages after a while.
Therefore I'm writing some error handling messages, and I want to publish some AT data to MQTT.
It's probably a simple solution, but how can I, though the code, send AT messages from my 'own' device?
Also, does AT messages get parsed at a higher level than any other user input, so it can't get stuck in any user made input loop?
Many thanks!

How do I send the message to myself, though, can I write to the input buffer that belongs to the serial connection?

I'm gonna have a loop in my Arduino code, so that if the unit doesn't transmit any sensor  data for 2000ms, it will try to transmit diagnostic data provided by AP commands, so I need to read them as a c string. If I could read AP commands by mqtt subscription, that would also be quite interesting.

The AT command set for the ESP8266 is implemented through custom firmware which has to be flashed to the chip to use.
If you've written your own software which is running on the ESP8266 then that's what's flashed to it - the AT command set will not be available because you've overwritten it with your own software. So there's no way to send AT commands to yourself because if you've written software that could do that, then it's present and the AT command-interpreting software is not.
In that case you should look deeper into the Arduino core for the ESP8266 to find the equivalents to the AT commands you wanted to use. This is the code that calls setup() and loop() and implements Arduino-compatible functions like pinMode(). It also provides libraries like ESP8266WiFi. There are many un- and under-documented functions in the code. You can almost certainly find the equivalents to anything that you can do with an AT command in here.

Thanks, that's pretty much what I was confused about! I'm sure I can do without..


text:
What should the cut-off frequency be?
To convert a PWM signal to a DC voltage it must be filtered with a low pass filter. How can you know which cut-off frequency should be used and how do you calculate the values for the resistor and capacitor belonging to that cut-off frequency. I do know that the cut-off frequency needs to be much higher/lower in comparison to the PWM signal, for example a factor 100 lower/higher.

https://arduino.stackexchange.com/tour

program the cut-off based on how fast you need to change set voltage, not by PWM frequency. If you need to adjust in 100ms, aim for that, and you won't be disappointed. Also, you can use a 2nd stage to drastically improve the smoothing at a given resistor size, which can help response times by using a  higher-frequency cut-off but still getting enough smoothing.

Note also this will not work exactly as expected depending on how much current is sink on Uout

The PWM frequency on the Arduino is about 500Hz by default, so you want your -3dB frequency to be below that. How far below? That's subjective. Lower gives a smoother output but a lower response speed. Since you want DC out then you can afford to go very low, unless you need it to respond to changes in the set point quickly.


text:
Bluetooth gamepad via Adafruit Feather M0 Bluefruit BLE
I'm trying to build a Bluetooth-enabled gamepad out of an old Playstation 1 controller, using an Adafruit Feather M0 Bluefruit BLE.
I've programmed the board as a Keyboard HID and everything works: the controller button presses trigger keyboard presses through the Feather. However, treating the controller as a keyboard means I get no analog joystick support.
The Feather M0 supports a Gamepad HID mode, but it's limited to 8 buttons and one joystick (but not analog), which is obviously not enough for a Playstation 1 controller.
I'm a bit stumped here: do I have any way of registering the BLE as a gamepad, to enable analog support, but with as many buttons as I need and two joysticks?
My code so far, on GitHub.

how does it matter, if the joystick is analog? you have a mcu with analog pins. read the joystick, convert the values and send them. or am I missing something here?

It seems that adafruits firmware doesn't support/implement that.

@Juraj he means there is only D-pad support. So only left right up down (on or off).

@Gerben, thank you for the explanation. it is not about analog. joystick is a different HID profile then gamepad

and the joystick HID profile is not supported over (nRF52?) BLE. (there are really two M0 ARM MCUs on this board?)

@Juraj, my issue is sending data over in the correct manner, not reading it from the pins. But still, since joystick HID is not supported over this chip, it seems like I'm out of luck.

@Gerben, that info seems to be for the EZ-Key, not the Feather M0.

Adafruit has the same AT firmware in all Bluefruits

@Juraj, argh, I see. I'll try to map it as the mouse then, if the Feather will let me send both keyboard and mouse data. Thanks for the help!


text:
Replace Arduino bootloader
My Arduino board is malfunctioning in its bootloading and I thought weather I can overwrite the previous bootloader on the atmega. I mean to ask than can I simply reinstall bootloader on a chip that already has a bootloader installed.

yes. you need an ISP programmer or other Arduino with "Arduino as ISP" sketch.

Yes you can. A Programmer that is driven from a PC and connects to SCK/MOSI/MISO/Reset/Power/Gnd (the ICSP header on an Uno/Mega), or a Standalone Programmer that can program a bootload program stored on an SD card and connects to the same ICSP pins, is needed to access the bootload memory to load/reload the bootloader.


text:
invalid conversion from 'uint16_t* error when creating an array of uint16_t items
I'd like to create an array of remote control codes provided by the raw read feature of the irlib2 library.
irlib2 provides the following uint16t arrays using the following format:
#define RAW_DATA_LEN 68

const uint16_t powerOff[RAW_DATA_LEN]={
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000};

I'd like create an array of these arrays using the code below, but get the following errors.
CODE
#define RAW_DATA_LEN 68

const uint16_t powerOff[RAW_DATA_LEN]={
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000};

uint16_t sourceCD[RAW_DATA_LEN]={
  8546, 4310, 558, 1578, 562, 538, 498, 1638,
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000};

uint16_t sourceAUX[RAW_DATA_LEN]={
  8550, 4310, 526, 1634, 506, 566, 502, 1634,
  506, 566, 502, 574, 506, 1626, 510, 566,
  506, 1630, 506, 566, 502, 1634, 506, 566,
  502, 1634, 506, 1606, 530, 566, 506, 1630,
  506, 566, 502, 1634, 506, 1630, 506, 1630,
  510, 1602, 526, 570, 510, 566, 502, 1634,
  502, 570, 502, 570, 510, 566, 502, 570,
  510, 562, 506, 1630, 506, 1630, 510, 562,
  506, 1630, 510, 1000};

uint16_t sourceCDR[RAW_DATA_LEN]={
  8550, 4306, 530, 1606, 534, 566, 502, 1606,
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000};

//This is the problem code:
uint16_t sources[3] = {sourceCD, sourceAUX,  sourceCDR};

ERRORS
warning: invalid conversion from 'uint16_t* {aka unsigned int*}' to 'uint16_t {aka unsigned int}' [-fpermissive]
 uint16_t sources[3] = {sourceCD, sourceAUX,  sourceCDR};
warning: invalid conversion from 'uint16_t* {aka unsigned int*}' to 'uint16_t {aka unsigned int}' [-fpermissive]
warning: invalid conversion from 'uint16_t* {aka unsigned int*}' to 'uint16_t {aka unsigned int}' [-fpermissive]

I gather this has something to do with mixing and converting invalid types, but I'm not quite sure where to go from here

sources is array of pointers to arrays so uint16_t* sources[] = {sourceCD, sourceAUX,  sourceCDR};. array variable is a pointer to first member location

That doesn't quite fix it. I still get this error 3 times: warning: invalid conversion from 'const uint16_t* {aka const unsigned int*}' to 'uint16_t* {aka unsigned int*}' [-fpermissive] I also tried uint16_t *sources[] = {sourceCD, sourceAUX, sourceCDR}. Any other ideas?

I didn't notice that your first array is const and others are not. make all const. the position of * is not important. you should read the error/warning messages.

@Juraj I noticed that too, but I'm not sure what in the warnings would have indicated that was the problem. Can you help me understand the warning message?

I think the error messages in your Question are not for the code with Question. the first error message would have const mentioned. the messages say that you try to use uint16_t* where uint16_t is expected

You have two options.

You can make an array of arrays like this:

const uint16_t sources[3][RAW_DATA_LEN] = {
    { 8546, 4310, 558, ... }, // CD
    { 8550, 4310, 526, ... }, // AUX
    { 8550, 4306, 530, ... }  // CDR
};

But then you don't have the sourceCD, etc. variables any more. If you
want, you could #define aliases for them like this:
#define sourceCD  (sources[0])
#define sourceAUX (sources[1])
#define sourceCDR (sources[2])

You can make an array of pointers, as suggested in the comments:

const uint16_t sourceCD[RAW_DATA_LEN]  = { 8546, 4310, 558, ... };
const uint16_t sourceAUX[RAW_DATA_LEN] = { 8550, 4310, 526, ... };
const uint16_t sourceCDR[RAW_DATA_LEN] = { 8550, 4306, 530, ... };
const uint16_t *sources[3] = { sourceCD, sourceAUX,  sourceCDR };

This works because, in the last line, the array identifiers such as
sourceCD implicitly “decay” to pointers to their first elements. Note
the const keyword in the last line, needed for consistency with the
types of the arrays declared above.