text:
IDE finds multiple libraries
I don't understand Arudino IDE. Ever.
This is a part of the compilation output:
Alternatives for ArduinoJson.h: [ArduinoJson@6.14.0]
ResolveLibrary(ArduinoJson.h)
  -> candidates: [ArduinoJson@6.14.0]
/home/mark/.arduino15/packages/STM32/tools/xpack-arm-none-eabi-gcc/9.2.1-1.1/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb @/tmp/arduino_build_952252/sketch/build_opt.h -c -Os -w -std=gnu++14 -ffunction-sections -fdata-sections -nostdlib -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -fno-use-cxa-atexit -I/home/mark/OSC -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/avr -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32 -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/LL -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/hid -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/cdc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Src -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/STM32F4xx -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Src -w -x c++ -E -CC -DSTM32F4xx -DARDUINO=10810 -DARDUINO_NUCLEO_F429ZI -DARDUINO_ARCH_STM32 "-DBOARD_NAME=\"NUCLEO_F429ZI\"" -DSTM32F429xx -DHAL_UART_MODULE_ENABLED -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/Core/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/ -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/DSP/Include -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/variants/NUCLEO_F429ZI -I/home/mark/Arduino/libraries/STM32duino_LwIP/src -I/home/mark/Arduino/libraries/STM32duino_STM32Ethernet/src -I/home/mark/Arduino/libraries/ArduinoJson/src /tmp/arduino_build_952252/sketch/OSC.ino.cpp -o /dev/null
Alternatives for FlexyStepper.h: [FlexyStepper@1.0.0]
ResolveLibrary(FlexyStepper.h)
  -> candidates: [FlexyStepper@1.0.0]
/home/mark/.arduino15/packages/STM32/tools/xpack-arm-none-eabi-gcc/9.2.1-1.1/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb @/tmp/arduino_build_952252/sketch/build_opt.h -c -Os -w -std=gnu++14 -ffunction-sections -fdata-sections -nostdlib -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -fno-use-cxa-atexit -I/home/mark/OSC -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/avr -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32 -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/LL -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/hid -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/cdc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Src -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/STM32F4xx -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Src -w -x c++ -E -CC -DSTM32F4xx -DARDUINO=10810 -DARDUINO_NUCLEO_F429ZI -DARDUINO_ARCH_STM32 "-DBOARD_NAME=\"NUCLEO_F429ZI\"" -DSTM32F429xx -DHAL_UART_MODULE_ENABLED -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/Core/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/ -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/DSP/Include -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/variants/NUCLEO_F429ZI -I/home/mark/Arduino/libraries/STM32duino_LwIP/src -I/home/mark/Arduino/libraries/STM32duino_STM32Ethernet/src -I/home/mark/Arduino/libraries/ArduinoJson/src -I/home/mark/Arduino/libraries/FlexyStepper/src /tmp/arduino_build_952252/sketch/OSC.ino.cpp -o /dev/null
Alternatives for Tasker.h: [Tasker@2.0]
ResolveLibrary(Tasker.h)
  -> candidates: [Tasker@2.0]

Più di una libreria trovata per "ArduinoJson.h"
Usata: /home/mark/Arduino/libraries/ArduinoJson
Più di una libreria trovata per "FlexyStepper.h"
Usata: /home/mark/Arduino/libraries/FlexyStepper
Più di una libreria trovata per "Tasker.h"
Usata: /home/mark/Arduino/libraries/Tasker

Più di una libreria trovata in English means more than one library found.
And Usata means Used.
It's telling me it finds multiple libraries and selects one among them. Cool. But why it doesn't tell me where are the others?
Ok, I do:
$ sudo find / -name Tasker.h
/home/mark/Arduino/libraries/Tasker/Tasker.h

the same happens with the others.
So, where are the multiples libraries it finds?

it is a known bug of Arduino IDE 1.8.10. ignore it. you don't have multiple libraries if it only lists one. https://github.com/arduino/Arduino/issues/9601

There are 3 locations for your libraries. Arduino IDE checks on the Arduino IDE (installation path) library folder. On your sketch folder. And finally in your board folder. As you can see in your log, you have a custom board STM32 installed, and the IDE is taking the library located in .arduino15, not the one located in Arduino. Tutto chiaro?

When you install your Arduino, 3 locations are used for your libraries:

Installation folder
Personal folder
Boards folder

Installation folder
This is the location where you installed Arduino. Normally they are:
On Windows: %ProgramFilesDir%\Arduino\libraries
On Linux: /home/{USERNAME}/arduino-{VER}/libraries
There, you can find 5-10 base libraries.
Personal folder
Since, on each update, the installation folder is deleted, the sketches and custom libraries are stored in your personal data folder:
On Windows: %userprofile%\documents\Arduino\libraries
On Linux: /home/{USERNAME}/Arduino/libraries/
There, you can find all libraries that you downloaded from the IDE.
Boards folder
Some libraries comes with your board and are board optimized. Arduino IDE will always check this folder, before it search for other libraries.
On Windows: %LOCALAPPDATA%\Arduino15\packages\{BOARD}\hardware\{MODEL}\{VERSION}\libraries
On Linux: /home/{USERNAME}/.arduino15/packages/{BOARD}/hardware/{MODEL}/{VERSION}/libraries

As I can see, you have a custom board selected. So the Arduino IDE search on the boards folder. If it can find a library it will take this one. If not, it will search on your personal folder and finally in the installation folder. I am not sure, but it could also get the newer one, if there is a version on it. Can't say how the right library is selected by the IDE.
If more than 1 are found, a warning message will appear. But it is just a message, you can just check if the right library was taken.

I know where the libraries are located, but it's not the point here. As you can see I searched from the root, so there are no more than one library. It's a bug, as Juraij said.

You're right. sorry... I answered without read it completly.


text:
How to initialize digital output pin as low on arduino board??? I am getting lights on initially and i want lights off
/*
Please note as I have used the android app you told , the string inputs are taken as
A,B,C,D,E,F,G and a,b,c,d,e,f,g.
I have also written code for voice on and off which has all on and all off function
but since the android app we are using dosent have such key so i didnt took them
*/

String inputs;
#define relay1 2 //Connect relay1 to pin 9
#define relay2 3 //Connect relay2 to pin 8
#define relay3 4 //Connect relay3 to pin 7
#define relay4 5 //Connect relay4 to pin 6
#define relay5 6 //Connect relay5 to pin 5
#define relay6 7 //Connect relay6 to pin 4
#define relay7 8 //Connect relay7 to pin 3
#define relay8 9 //Connect relay8 to pin 2

void setup()
{
    Serial.begin(9600); //Set rate for communicating with phone
    pinMode(relay1, OUTPUT); //Set relay1 as an output
    pinMode(relay2, OUTPUT); //Set relay2 as an output
    pinMode(relay3, OUTPUT); //Set relay1 as an output
    pinMode(relay4, OUTPUT); //Set relay2 as an output
    pinMode(relay5, OUTPUT); //Set relay1 as an output
    pinMode(relay6, OUTPUT); //Set relay2 as an output
    pinMode(relay7, OUTPUT); //Set relay1 as an output
    pinMode(relay8, OUTPUT); //Set relay2 as an output
    digitalWrite(relay1, LOW); //Switch relay1 off
    digitalWrite(relay2, LOW); //Swtich relay2 off
    digitalWrite(relay3, LOW); //Switch relay1 off
    digitalWrite(relay4, LOW); //Swtich relay2 off
    digitalWrite(relay5, LOW); //Switch relay1 off
    digitalWrite(relay6, LOW); //Swtich relay2 off
    digitalWrite(relay7, LOW); //Switch relay1 off
    digitalWrite(relay8, LOW); //Swtich relay2 off
}
void loop()
{
    while(Serial.available()) //Check if there are available bytes to read
    {
        delay(10); //Delay to make it stable
        char c = Serial.read(); //Conduct a serial read
        if (c == '#'){
            break; //Stop the loop once # is detected after a word
        }
        inputs += c; //Means inputs = inputs + c
    }
    if (inputs.length() >0)
    {
        Serial.println(inputs);

        if(inputs == "A")
        {
            digitalWrite(relay1, LOW);
        }
        else if(inputs == "a")
        {
            digitalWrite(relay1, HIGH);
        }
        else if(inputs == "B")
        {
            digitalWrite(relay2, LOW);
        }
        else if(inputs == "b")
        {
            digitalWrite(relay2, HIGH);
        }
        else if(inputs == "C")
        {
            digitalWrite(relay3, LOW);
        }
        else if(inputs == "c")
        {
            digitalWrite(relay3, HIGH);
        }
        else if(inputs == "D")
        {
            digitalWrite(relay4, LOW);
        }
        else if(inputs == "d")
        {
            digitalWrite(relay4, HIGH);
        }
        else if(inputs == "E")
        {
            digitalWrite(relay5, LOW);
        }
        else if(inputs == "e")
        {
            digitalWrite(relay5, HIGH);
        }
        else if(inputs == "F")
        {
            digitalWrite(relay6, LOW);
        }
        else if(inputs == "f")
        {
            digitalWrite(relay6, HIGH);
        }
        else if(inputs == "G")
        {
            digitalWrite(relay7, LOW);
        }
        else if(inputs == "g")
        {
            digitalWrite(relay7, HIGH);
        }
        else if(inputs == "H")
        {
            digitalWrite(relay8, LOW);
        }
        else if(inputs == "h")
        {
            digitalWrite(relay8, HIGH);
        }
        inputs="";
    }
}

some relay modules are active LOW

On the ralay, check if you see the text NC or NO. "Normally Close", means that you have to set HIGH if you want your lights ON. If you connect the lights on "Normally Open", if means that you have to set LOW if you want your lights ON.

source: Stack Exchange

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

sort: votes


text:
LSB/MSB and shiftOut
Here is the shiftOut function code from wiring_shift.c
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
     uint8_t i;

     for (i = 0; i < 8; i++)  {
           if (bitOrder == LSBFIRST)
                 digitalWrite(dataPin, !!(val & (1 << i)));
           else
                 digitalWrite(dataPin, !!(val & (1 << (7 - i))));

           digitalWrite(clockPin, HIGH);
           digitalWrite(clockPin, LOW);
     }
}

Does this mean that least significant bit is on the left and most significant bit is on the right? Or LSBFIRST means that will be the last outputted bit so it will be "first" in outputted sequence?
One more thing
here is a sample code:
shiftOut(dataPin, clockPin, LSBFIRST, B00101001);
shiftOut(dataPin, clockPin, LSBFIRST, B11010011);

Why does this
union
{
     word uniform;
     byte separate[2];
} state;

state.uniform = 54057; // aka 11010011 00101001
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[1]);
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[0]);

have different output but if i swap last two lines it works correctly?

You should read something about endianness. It'd work as you expect with big endian processor, but the majority is using little endian for the internal number representation.

ok, thank you for answer

Integer values of the Arduino have the MSB left and the LSB right. The shiftOut() function let's you choose, how the order should be timewise. If you provide LSBFIRST, the function will start the transmit with the LSB (on the right) and then go left to the MSB. Otherwise it will start with the MSB and then go right to the LSB. So this effects only the time order of the bits, in that they get transmitted.

Thank you for answer but there is one more problem, I've appended my question

There is no "left" or "right" in a binary number, only in the human representation of that number.
It is traditional for us to place the most significant bit on the left, purely because that his how we represent other numbers - like 1234 (1 is the most significant digit, the thousands).
Given the pseudo-number 12345678 if you shift out LSBFIRST the 8 gets output first, then the 7, then the 6, etc. In MSBFIRST the 1 gets output first, then the 2, then the 3, etc.

I would say, there is "left" or "right" in a binary number. There are even operators for shifting left or right. The human representation comes with the connection of "left" or "right" with LSB and MSB, so that the binary number can be converted to other bases or even printed out (since choosing where LSB/MSB is changes the representation in a different base, but not the binary number itself).

@chrisl There is only a left and right because we, as humans, decide to represent them that way. The shift left and shift right are again just names we have assigned to the operators. They should be called "SMS" and "SLS" for Shift Most-Significant and Shift-Least-Significant, but we choose to give these things chirality.

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


text:
ESP8266 unresolved mDNS host in .local domain
I am trying to implement a mDNS for esp8266 in Arduino IDE following this guide.
https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html
I cannot get the esp8266.local name to work - when i ping it it returns an error unresolved host and putting it in a browser also does not resolve...
The IP address does resolve though. Any advice would be greatly appreciated. I am using Mac OS High Sierra and have seen that many people have experienced this problem on both windows and mac but there does not seem to be a solution yet.
Any ideas?
Thanks x

Post your serial output. Make sure the device is getting an ip address on the network.

I have had the same issue. It gets an IP address, but seemingly won't use mDNS. I think it's either an OS or router issue. Are you able to try different routers?

There is a known bug in the example code you are using.  The author has been notified on github but has apparently chosen to not update their published code.
You need to add the following line to the loop() { } ; section of the code :    MDNS.update();
 void loop() {
    MDNS.update();
 }

Once you do that. it should start working. And without that there is not way to get it working.
Adding this comment for anyone following and searching for a solution to this same problem.


text:
how to combine two code of arduino uno
int mamank=13;
void setup() {
  pinMode (mamank,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  if(sensorValue>550)digitalWrite(mamank,HIGH);
  else if(sensorValue<500)digitalWrite(mamank,LOW);
  delay(100);
}

-----------------------------------------------AND this code----------------------
int red=2;
int green=3;
int blue=4;

void setup () {
  pinMode (red,OUTPUT);
  pinMode (green,OUTPUT);
  pinMode (blue,OUTPUT);
  Serial.begin (9600);}

void loop() {
  // read the input on analog pin 0:
  int value = analogRead(A1);

  if (value > 500) {
    Serial.println("Very heavy Rain");
    digitalWrite (red,HIGH);
    digitalWrite(green,LOW);
    digitalWrite(blue,LOW);}
  else if ((value > 300) && (value <= 500)) {
    Serial.println("AVERAGE Rain");
    digitalWrite (green,HIGH);
    digitalWrite (red,LOW);
    }
  else{
    Serial.println("Dry Weather");
    digitalWrite (blue,HIGH);
    digitalWrite (red,LOW);
    digitalWrite (green,LOW);
  delay(100);
  }
  }

Put the stuff before setup() together, fix any duplicates:
int mamank=13; <<< pin assignment? If yes, this can be byte
int red=2; <<< pin assignment? If yes, this can be byte
int green=3; <<< pin assignment? If yes, this can be byte
int blue=4; <<< pin assignment? If yes, this can be byte

Put the stuff in setup() together, fix any duplicates
void setup() {
pinMode (mamank,OUTPUT);
Serial.begin(9600);
pinMode (red,OUTPUT);
pinMode (green,OUTPUT);
pinMode (blue,OUTPUT);
Serial.begin(9600);  <<< duplicate, so delete this line
}

Put the stuff in loop() together, then check the desired functionality:
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
if (sensorValue>550) {
digitalWrite(mamank,HIGH);
}
else if (sensorValue<500) {
digitalWrite(mamank,LOW);
}
delay(100);
// read the input on analog pin 0:
int value = analogRead(A1);
if (value > 500) {
Serial.println("Very heavy Rain");
digitalWrite (red,HIGH);
digitalWrite(green,LOW);
digitalWrite(blue,LOW);
}
else if ((value > 300) && (value <= 500)) {
digitalWrite (green,HIGH);
digitalWrite (red,LOW);
}
else {
Serial.println("Dry Weather");
digitalWrite (blue,HIGH);
digitalWrite (red,LOW);
digitalWrite (green,LOW);
delay(100);
}

}

What happens when sensorValue is 500 to 550? No change on the output?

it change  ,which is not functioning is the one after it

Thank you this works well, thank you very much man


text:
ESP32 - Html link
I'm programming a ESP32 modue and I have a code that generates an Access Point and displays an html with two buttons that changes the state of 3 leDs. I want to insert a button that calls a second html code that is within (void engine() ) and on this page has the following text ( This page turns on the engine ). Detail: The page that is already displaying in the browser has to be updated by the new html code of the second html page. How can I change my Code to get this third button ?
#include <WiFi.h>
#include <WebServer.h>

const char* ssid     = "ssid";
const char* password = "password";

WiFiServer server(80);

String header;

String output26State = "off";
String output27State = "off";

const int output26 = 26;
const int output27 = 27;

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

 pinMode(output26, OUTPUT);
 pinMode(output27, OUTPUT);

 digitalWrite(output26, LOW);
 digitalWrite(output27, LOW);

 WiFi.softAP(ssid, password);
 delay(10);

 IPAddress IP = WiFi.softAPIP();
 Serial.print("IP Address: ");
 Serial.println(IP);

 server.begin();

}

void one()
{
  WiFiClient client = server.available();
  client.println("
Page One
");
  client.println("
<button class=\"button\">Pag Two 2</button>
");
  client.println();
}

void two()
{
  WiFiClient client = server.available();   // Listen for incoming clients
  client.println("
Page Two
");
  client.println("
<button class=\"button\">Page One 1</button>
");
  client.println();
}

void loop()
{
 WiFiClient client = server.available();   // Listen for incoming clients

 if (client)
 {                             // If a new client connects,
  Serial.println("New Client.");          // print a message out in the serial port
  String currentLine = "";                // make a String to hold incoming data from the client
  while (client.connected())              // loop while the client's connected
  {
   if (client.available())               // if there's bytes to read from the client,
   {
    char c = client.read();             // read a byte, then
    Serial.write(c);                    // print it out the serial monitor
    header += c;
    if (c == '\n')                      // if the byte is a newline character
    {
      if (currentLine.length() == 0)
      {

       client.println("HTTP/1.1 200 OK");
       client.println("Content-type:text/html");
       client.println("Connection: close");
       client.println("<!DOCTYPE html>");
       client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
       client.println("<link rel=\"icon\" href=\"data:,\">");
       client.println("");
       client.println("");
       client.println();

       if (header.indexOf("GET /one") >= 0)
       {
        Serial.println("Page One");
        output26State = "on";
        digitalWrite(output26, HIGH);
        one();
       }
       else if (header.indexOf("GET /two") >= 0)
       {
        Serial.println("Page Two");
        output26State = "off";
        digitalWrite(output26, LOW);
        two();
       }
       client.println("
<button class=\"button\">Page Two</button>
");
       client.println("");
       client.println();
       // Break out of the while loop
       break;
      }
      else // if you got a newline, then clear currentLine
      {
        currentLine = "";
      }
    }
    else if (c != '\r')      // if you got anything else but a carriage return character,
    {
      currentLine += c;      // add it to the end of the currentLine
    }
  }
}

 header = "";
 client.stop();
 Serial.println("Client OFF.");
 }

}

Thank You

Did I understand you correctly? You want a button that links to another page and at the same action you want to toggle (or only turn on) the engine?

why don't you use the same html code as the other two buttons? ... just make the necessary changes to make the code unique

369/5000
I'm sorry, I didn't express myself very well, let's simplify my doubts. For example, in my code there is (void one ()) and (void two ()). I want to insert a button that calls (void one ()) and insert an html code inside (void one ()), when (void one ()) is called it displays the html replacing the code of the main page that is inside (void loop ()).

this is an XY problem ... you are asking for help with what you consider to be a solution to your problem, instead of asking for help with the problem ... there are other more effective ways to update a web page ... google arduino html button led ... that will show you how to interact between a web page and a function ... here is one of the hits that may help https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/

you could have 3 buttons on a webpage and simply make one or more of them invisible ... that way you would not have to reload the web page


text:
HC-05 Bluetooth module does not send or receive data when its on-board light blinks(light blinking after its connected to a device)
HC-05 Bluetooth module does not send or receive data when its on-board light blinks(light blinking after its connected to a device)
as soon as the on-board led starts glowing it does not send or receive data but when the light turns off it works perfectly.

do you have a question?

I have a HC-06 (which is the same chip as HC-05, just a different firmware), whose light turns off, when a device is connected. Generally the LED should show the connection state, thus only one of the LED states corresponds to a successfull connection


text:
I can't use buffer without printing in my Nodemcu esp8266
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ////////////////////////////////////////////

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/photos");
  http.addHeader("Accept", "*/*");

  int httpCode = http.GET();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);

  //reading response with buffer
  static char buff[128] = { 0 };
  while (http.connected() ) {
    size_t size = client->available();
    if (size) {
      int c = client->readBytes(buff, ((size > sizeof(buff) ) ? sizeof(buff) : size));
      //if i uncomment this next line, everything is fine.
      //Serial.write(buff, c); Serial.println();

      //but if i dont use serial.write program never gets here
      if (char * pch = strstr (buff, "quis fuga")) {
        char str[20] = { 0 }; int g =   0 ;
        while (pch[g] != '\"') {
          str[g] = pch[ g];
          g++;
        }
        Serial.print("FOUND IT: "); Serial.println(str);
      }

    }
    else if (!size) {
      Serial.println( "reading done");
      break;
    }
    delay(1);
  }

}

void loop() {

  delay(222222);

}

EDIT
here i created a compilable runnable code. basically i am trying to find a word in a http response. my real examples response isnt json and it is as long as this examples response. one other problem is i cant read all of the repsponse. it unexpectedly finishes reading sometimes after a few lines sometimes after a few hundred. in this particular request my nodemcu cant read after id 258. or id 8. object in the json response: https://jsonplaceholder.typicode.com/photos
if i dont use serial.write print buffer content, it finishes reading immideatly and thats exactly where i have the problem.

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

The Serial printing creates a delay. That delay enables to collect more characters in the buffer. If you read the input in small pieces (3 to 10 bytes) then the buffer doesn't contain the searched substring because it splits into two subsequent buffers. Even if you could read full buffers, it still can happen that the search string will be split.
To search for a string in a stream of data you can use function find(string). The networking Client class inherits this function from Arduino Stream class. find will read the stream until it finds the searched string. Then the next read from the stream will read the data right after the searched string.


text:
Help with debugging code
This is NOT my code; was posted on Project Hub.   I tried to use the code (humidity controller) but it returns an error on line 270:
else if (DHT.humidity >= setpoint + 3 and syson == true) { //if humidity is 3% above setpoint

Error: expected primary-expression before '.' token
The OP is not responding to comments and I'm no expert.   Would appreciate if someone could help debug the code;
Thanks!
       //HUMIDITY CONTROLLER 1.1
//written for NANO

//controls and displays relative humidity
//sesnor used is DHT11
//uses active-low relay module to control live lines for 2 standard electrical outlets
//uses i2c lcd to display humidity and humidity setting
//turns display off during inactivity
//setting is adjustable from 10%-90% using 2 buttons
//backlight of LCD is controlled by pin 4, connected to top LED jumper pin on i2c backpack
//serial communications to monitor to ensure all code is working.

//added: "system off" function - allows both outlets to be turned off

// █ G █ L █ O █ B █ A █ L █ S █
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <dht.h>

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

dht DHT;

#define DHT11_PIN A2

//buttons and variables to adjust calibration
int calupbtn = A0;
int calup;
int caldownbtn = A1;
int caldown;

//i2c PINS A4, A5

//pin for turning on humidifier relay
int humidifier = 3;
//pin for turning on the fan relay
int fan = 2;
//pin for turning on LCD backlights
int lcdlight = 4;

//calibration variable
int setpoint = 50;  //feedback setpoint.
bool calstate = false;  //enables calibration adjustments only when LCD is ON.

//backlight timing variables
int displtime = 12000;  //amount of time the display is to be on before turning off
unsigned long displtimeon;  //last recorded time display timer was reset
int calunlock = 0;   //loop counter for unlocking calibration

//sensor timing variables
unsigned long lastcheck;  //last time DHT was read
long interval = 30000;      //time between DHT readings

//system variables
bool syson = true;    //reference for system on/off.
byte systog = 2;       //even number toggles on, odds toggle off
int syslock = 0;     //loop counter for unlocking system toggle

// █ S █ E █ T █ U █ P █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █
void setup(){

  Serial.begin(9600);  //serial communication used to ensure code is working correctly.

  lcd.init();  //initialize LCD
  lcd.backlight(); //enable LCD backlight, but doesn't turn it on

  lastcheck = 0;
  digitalWrite(lcdlight, HIGH);
  Serial.println("STARTING");
  lcd.print("   STARTING");

  //pin assignments
  pinMode(calupbtn, INPUT);
  pinMode(caldownbtn, INPUT);
  pinMode(humidifier, OUTPUT);
  pinMode(fan, OUTPUT);
  pinMode(lcdlight, OUTPUT);
  delay(1000);

  //test fan
  lcd.setCursor(0,1);
  lcd.print("<FAN>     HMDFR  ");
  digitalWrite(fan, LOW);
  digitalWrite(humidifier, HIGH);
  delay(6000);
  //test humidifier
  lcd.setCursor(0,1);
  lcd.print(" FAN     <HMDFR> ");
  digitalWrite(fan, HIGH);
  digitalWrite(humidifier, LOW);
  delay(6000);
  //stop startup test
  digitalWrite(humidifier, HIGH);
  digitalWrite(fan, HIGH);
  lcd.clear();

  displtimeon = millis();

  int chk = DHT.read11(DHT11_PIN);
  lastcheck = millis();

  lcd.setCursor(0,0);
  lcd.print("Humidity: ");
  lcd.setCursor(13,0);
  lcd.print(DHT.humidity);
  lcd.setCursor(15,0);
  lcd.print("%  ");
  lcd.setCursor(0,1);
  lcd.print("setting: ");
  lcd.setCursor(13,1);
  lcd.print(setpoint);
  lcd.setCursor(15,1);
  lcd.print("%  ");
  delay(100);
}

// █ L █ O █ O █ P █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █
void loop(){

  //check calibration buttons
  calup = digitalRead(calupbtn);
  caldown = digitalRead(caldownbtn);

  if(calup == HIGH and caldown == HIGH){  //--------SYSTEM TOGGLE
    syslock ++;
    Serial.println(syslock);
    if(syslock == 20){  //if both buttons held down for this many loops
      systog++;
      if(systog % 2 == 1){  //--------SYSTEM OFF
        syson = false;
        digitalWrite(fan, HIGH);
        digitalWrite(humidifier, HIGH);
        digitalWrite(lcdlight, HIGH);
        Serial.println("SYSTEM TURNED OFF");
        lcd.clear();
        lcd.print("   SYSTEM OFF");
        lcd.setCursor(0,1);
        lcd.print("  hold both btns");
        delay(2000);
        lcd.setCursor(0,1);
        lcd.print("  to turn on    ");
        displtimeon = millis();
      }
      if(systog % 2 == 0){  //--------SYSTEM ON
        syson = true;
        Serial.println("SYSTEM TURNED ON");
        digitalWrite(lcdlight, HIGH);
        lcd.clear();
        lcd.print("   SYSTEM ON");
        delay(2000);
        lcd.clear();
        displtimeon = millis();
      }
      syslock = 0;
    }
  }
  else(syslock = 0);

  //read humidity at appropriate intervals
  if(millis() > lastcheck + interval and syson == true){  //read the DHT humidity
    int chk = DHT.read11(DHT11_PIN);
    lastcheck = millis();
    Serial.print("DHT read = ");
    Serial.print(DHT.humidity);
    Serial.print("%");
    Serial.println(" ");
    }

  //turn on the led lights when calibration buttons are pressed
  if(calup == HIGH xor caldown == HIGH){
    digitalWrite(lcdlight, HIGH);
    calstate = true;
    displtimeon = millis();  //set display timer
    Serial.println("cal btn ACTIVE");
    if(syson == false){
      digitalWrite(lcdlight, HIGH);
      lcd.clear();
      lcd.print("   SYSTEM OFF");
      lcd.setCursor(0,1);
      lcd.print("  hold both btns");
      delay(3000);
      lcd.setCursor(0,1);
      lcd.print("  to turn on    ");
      displtimeon = millis();
    }
  }

  if(calstate == true and syson == true){  //--------DISPLAY ROUTINE
    Serial.println("printing display");
    //display variables on LCD
    lcd.setCursor(0,0);
    lcd.print("Humidity: ");
    lcd.setCursor(13,0);
    lcd.print(DHT.humidity);
    lcd.setCursor(15,0);
    lcd.print("%  ");
    lcd.setCursor(0,1);
    lcd.print("setting: ");
    lcd.setCursor(13,1);
    lcd.print(setpoint);
    lcd.setCursor(15,1);
    lcd.print("%  ");
    delay(100);

    calunlock ++;
    //keeps calibration locked until display cycles 5 times after initially turned on
    //prevents adjustments on initial button press.
  }

//--------CALIBRATION ADJUSTMENTS
  if(calup == HIGH and caldown == LOW and calstate == true and syson == true){
    if(setpoint < 90 and calunlock > 5){
      setpoint = setpoint + 5;  //increase setpoint
      Serial.println("adj setpoint up");
    }
    Serial.println(setpoint);
    delay(100);
    displtimeon = millis();     //reset backlight timeout
  }

  if(caldown == HIGH and calup == LOW and calstate == true and syson == true){
    if(setpoint > 10 and calunlock > 5){
      setpoint = setpoint - 5;  //decrease setpoint
      Serial.println("adj setpoint dn");
      }
    Serial.println(setpoint);
    delay(100);
    displtimeon = millis();     //reset backlight timeout
  }

  if(millis() > displtimeon + displtime){  //-----------------BACKLIGHT TIMEOUT
    digitalWrite(lcdlight, LOW); //turn off the screen
    calstate = false;
    Serial.println("displ + backlights off");
    lcd.clear();
    calunlock = 0;  //lock calibration
  }

  if(millis() < lastcheck){
    lastcheck = millis();  //reset timers in a millisecond rollover
  }

                                      //--------SETPOINT ERROR PROCEDURE
  if(setpoint > 91 or setpoint < 9){  //in case setpoint is ever out of bounds
    Serial.println("O/B ERROR");
    digitalWrite(lcdlight, HIGH);
    lcd.clear();
    lcd.print("O/B ERROR");  //display error message on lcd
    lcd.setCursor(0,1);
    lcd.print("RESETTING");
    delay(1000);
    for(int count = 9; count >= 0; count = count - 1){
      lcd.setCursor(15,1);
      lcd.print(count);     //count down from 10
      delay(1000);
    }
    setpoint = 50;        //reset setpoint at 50.
    displtimeon = millis();
  }

  //turn on humidifier relay if below setpoint  --------RELAY CONTROL
  //RELAY MODULE IS ACTIVE LOW
  if(DHT.humidity <= setpoint - 3 and syson == true){  //if humidity is 3% lower than setpoint
    Serial.println("humidifier ON, fan OFF");
    digitalWrite(humidifier, LOW);  //turn on humidifier
    digitalWrite(fan, HIGH);
  }
  else if(DHT.humidity >= setpoint + 3 and syson == true){  //if humidity is 3% above setpoint
    Serial.println("humidifier OFF, fan ON");
    digitalWrite(humidifier, HIGH);  //turn on fan
    digitalWrite(fan, LOW);
  }
  else{
    Serial.println("all off");  //if humidity is within 3% of setpoint
    digitalWrite(humidifier, HIGH);  //turn both off
    digitalWrite(fan, HIGH);
  }
  //delay(700);  //un-comment for serial debugging

  Serial.print("setpoint = ");
  Serial.println(setpoint);

  //delay(700);  //un-comment for serial debugging
}

/*  WIRING DIAGRAMS
 https://66.media.tumblr.com/98426b566744beacdd42bc0221092b76/tumblr_pvr0u8kvZy1yrmjh9o1_1280.png
 */

You have installed the Adafruit DHT library via the Arduino library manager

The source code does not work with that library. It is written to use the DHT library written by Rob Tillaart, named DHTLib. That library is not included in the Library Manager of the Arduino IDE. Instead, you have to download the library as a ZIP file and install it via Sketch / Include Library / Add .ZIP library.

I don't know why you have changed the source code in the meanwhile. Using DHTLib with the source code of revision 1 of your question works fine. In the meanwhile you have tried to adapt the code to match the Adafruit library, which eventually might be ok as well after some hard work. I suggest rolling back to the code of revision 1 and installing the correct library.

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

Yes, I'm right here: http://www.mapability.com/ei8ic/maps/prefix/canw.php, and I see you are a member of Amateur Radio SE. On an un-related note, +1 for your answer. The images used are clear and easy to read. 73.


text:
Arduino MKR 10100 control DC Motor
Thank you for reading my post. I have been stuck on this for several weeks now! I am trying to turn ON/OFF a DC motor from Arduino IOT Cloud. I have set up the cloud and added the switch. Everything works well with an LED: it lights on and off as needed, but the motor does not turn on or off. Below is the circuit I have set up.

My circuit specs are as follows:

I'm not using a UNO as the image illustrates, rather I'm using an Arduino MKR WiFi 1010, but the connections of the pins are exactly the same: LED at PIN 3 and Motor at 7.
The diode I am using is 1N4001.
The transistor I'm using is TIP120.
The motor I'm using is 5V DC Motor.
270 Ohm resistor on the transistor circuit and 220 Ohm on the LED circuit.

The Arduino code I made is as follows:
#include "thingProperties.h"

#define LED_PIN 3
#define MOTOR_PIN 7

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(MOTOR_PIN, OUTPUT);

  setDebugMessageLevel(2); // For debugging of cloud integration
  Serial.begin(9600);
  delay(1500);

  initProperties(); // initialize cloud properties
  ArduinoCloud.begin(ArduinoIoTPreferredConnection); // Connect to cloud
}

void loop() {
  ArduinoCloud.update(); // Update cloud background services
}

void onMotorChange() {
  if (motor) {
    // Motor & LED ON
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(MOTOR_PIN, HIGH);
  } else {
    // Motor & LED OFF
    digitalWrite(LED_PIN, LOW);
    digitalWrite(MOTOR_PIN, LOW);
  }
}

All my setup seems to be be correct, but it just is not working. I have researched a lot but to no avail. I have tested with a different motor just to be sure, but it also does not work. I'm not sure where I have made a mistake.
Please help me. Thank you very much.

never use an arduino as a power supply ... there is a good chance that the arduino will become an expensive fuse

Thank you for the tip, i do not have an external power supply that's why i resorted to the 5V pin. in regards to my question do you see why am facing this issue?

Okay i managed to solve it, the issue was actually my circuit wiring. Below is an image with the correct setup for the transistor or MOSFET.

I have changed the TIP120 to RFP30N06LE as VE7JRO suggested:

The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

but that with the circuit in question does not work. I have not tested the circuit attached with this answer using a TIP120 but i suspect it would work as well.
Finally i added a 9V battery as jsotola suggested:

never use an arduino as a power supply ... there is a good chance that the arduino will become an expensive fuse

but i have not tested using the 5V Arduino pin again i suspect it would work as well.
Bonus:
If anyone was wondering how i made these images i used TinkerCAD
Thank you all
Hope this Helps!

The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.
For a more in-depth answer, please see this answer: https://electronics.stackexchange.com/a/388468/165322

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

Hello VE7RO, hope you have been great! thank you for your input from before, i got everything working.
Now am working on making a PCB of it but i couldnt been to find an SMT version/replacement for the RFP30N06LE, i was wondering if this would work https://assets.nexperia.com/documents/data-sheet/PMV15UNEA.pdf since my aplication does not really reach the limit of 60 V or 30 A, while this provides good Rds, Thanks!


text:
Set the wall clock time or change GMT offset without ntp server?
I have been able to get the current time from an NTP server and set what appears to be an internal clock using the configTime() function from the ESP32 core.  I can then get the current time with the function getLocalTime().
I would like to be able to set the time returned by getLocalTime() from user input rather than from an NTP server.  I would also like to be able to update the GMT Offset without needing to reconnect to the server.
How do I interact with the clock value used by getLocalTime()? Is there documentation for this clock somewhere?

per request the SimpleTime example from the ESP32 install:
#include <WiFi.h>
#include "time.h"

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
}

Check out this library I wrote
https://github.com/fbiego/ESP32Time

The functions configTime and getLocalTime are from ESP32 core file esp32-hal-time.c. This wraps the ESP32 SDK functions. You can use the SDK functions to set the time and zone. They work with the RTC peripheral of the ESP32.
You can use setTimeZone to set the time zone.
The time.h is standard C time library. The ESP32 SDK makes it to work with the built in RTC (reference). To set the time it gets complicated. You would have to use undocumented SDK time functions.


text:
Why is my "port" button on the toolbar greyed out?
I am trying to program a Teensy 3.2 to act as a lightsaber controller. My code works perfectly but I can't select a port. How should I fix this problem?
Here is my code:
/* Presented without warranty, guarantee and support.
    By Bob Clagett - I Like To Make Stuff

   This is the code to accompany the lightsaber project at http://www.iliketomakestuff.com/make-lightsaber/
   Expected hardware is listed in post (Teensy 3.2, Prop Shield, DotStar LEDs)

   This is functional v1 of this code.  Lots more I want to add to it including crash detection/sounds.
   This code is dirty, bulky, poorly documented and ugly but I finally got it all functional.
   Cleanup to come later in v2.
*/

#include <SerialFlash.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

// GUItool: begin automatically generated code

// GUItool: end automatically generated code

#include <Adafruit_DotStar.h>
#include <NXPMotionSense.h>

NXPMotionSense imu;
NXPSensorFusion filter;

int motionThreshold = 2;

float lastPitch = 0, lastRoll = 0, lastHeading = 0;

int buttonState = HIGH;
int bladeState = 0; //0 off, 1, fading up, 2 on, 3 fading down
int fadeStep = 0;
int fadeStepSize = 6;
int selectedColor = 0;
int lastSelectedColor = 0;
bool isAnimating = 0;
bool bladeOn = 0;
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;
int lastButtonState = HIGH;
int pendingPress = 0;

//BC = Blade Color
int BCbuttonState = HIGH;
long BClastDebounceTime = 0;  // the last time the output pin was toggled
long BCdebounceDelay = 50;
int BClastButtonState = HIGH;
int BCpendingPress = 0;
int pendingColorPress = 0;

#define COLOR_BUTTON_PIN 1
#define POWER_BUTTON_PIN 0
#define COLOR_ORDER BGR
#define CHIPSET     APA102
#define NUMPIXELS    252

#define BRIGHTNESS  100
#define FRAMES_PER_SECOND 70

#define PROP_AMP_ENABLE 5
#define FLASH_CHIP_SELECT 6
#define LED_BUFFER_SELECT 7

#define VOLUME_POT 15

#define LED_PIN    7
Adafruit_DotStar strip = Adafruit_DotStar(
                           NUMPIXELS, DOTSTAR_BRG);

int outputValue = 0;
int presetColors[] = {0x0000FF, 0x00FF00, 0xFF0000, 0xFFFFFF};
int totalPresetColors = (sizeof(presetColors) / sizeof(int));
int selectedColorIndex = 0;

int swingSounds = 4;
int lastSwingSound = swingSounds;

int clashSounds = 0;
void setup() {
  delay(500); // sanity delay
  imu.begin();
  filter.begin(100);
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif

  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP

  pinMode(POWER_BUTTON_PIN, INPUT);
  pinMode(COLOR_BUTTON_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(POWER_BUTTON_PIN, HIGH);
  digitalWrite(COLOR_BUTTON_PIN, HIGH);
  digitalWrite(LED_PIN, LOW);

  Serial.begin(9600);
  // wait up to 3 seconds for the Serial device to become available
  long unsigned debug_start = millis ();
  while (!Serial && ((millis () - debug_start) <= 3000))
    ;

  Serial.println ("Start prop shield RAW player");
  SPI.begin();
  // Enable the amplifier on the prop shield
  pinMode(PROP_AMP_ENABLE, OUTPUT);
  digitalWrite(PROP_AMP_ENABLE, HIGH);
  pinMode(LED_BUFFER_SELECT, OUTPUT);
  digitalWrite(LED_BUFFER_SELECT, HIGH);

  // Audio connections require memory to work.  For more
  // detailed information, see the MemoryAndCpuUsage example

  // Set initial volume

  // Start SerialFlash
  if (!SerialFlash.begin(FLASH_CHIP_SELECT)) {
    while (1)
    {
      Serial.println ("Cannot access SPI Flash chip");
      delay (3000);
    }
  }

}

void powerUpBlade() {

  isAnimating = 1;
  bladeState = 1;
  Serial.println("Turn on blade");
  bladeOn = 1;

}

void powerDownBlade() {
  //animate DOWN

  bladeState = 3;
  fadeStep = NUMPIXELS;
  isAnimating = 1;
  Serial.println("Turn off blade");

  bladeOn = 0;
}

void bladeIsOn() {

}
//nothing needed here unless adding animation

void bladeIsAnimatingUp() {
  //Serial.println("bladeIsAnimatingUp");
  int midpoint = NUMPIXELS / 2;
  int newSection = fadeStep + fadeStepSize;
  for ( int j = fadeStep; j < newSection; j++) {
    strip.setPixelColor(j, selectedColor);
    strip.setPixelColor(NUMPIXELS - j, selectedColor);
  }
  Serial.println(newSection);
  fadeStep = newSection;

  if (fadeStep >= midpoint + fadeStepSize) {

    fadeStep = NUMPIXELS;
    isAnimating = 0;
    bladeState = 2;
    //      delay(200);
    Serial.println("blade up complete");

  }
}

void bladeIsAnimatingDown() {
  //Serial.println("bladeIsAnimatingDown");
  int midpoint = NUMPIXELS / 2;
  int newSection = fadeStep - fadeStepSize;
  for ( int j = fadeStep; j > newSection; j--) {

    strip.setPixelColor(j - midpoint, 0x000000);

    strip.setPixelColor(midpoint + NUMPIXELS - j, 0x000000);
  }
  //Serial.println(fadeStep);
  fadeStep = newSection;

  if (fadeStep <= midpoint - fadeStepSize) {
    fadeStep = 0;
    isAnimating = 0;
    bladeState = 0;
  }
}

void detectMotion() {
  float ax, ay, az;
  float gx, gy, gz;
  float mx, my, mz;
  float roll, pitch, heading;

  if (imu.available()) {
    // Read the motion sensors
    imu.readMotionSensor(ax, ay, az, gx, gy, gz, mx, my, mz);

    // Update the SensorFusion filter
    filter.update(gx, gy, gz, ax, ay, az, mx, my, mz);

    // print the heading, pitch and roll
    roll = filter.getRoll();
    pitch = filter.getPitch();
    heading = filter.getYaw();

    // does it need a time threshold too?

    float headingDiff = abs(lastHeading - heading);
    float pitchDiff = abs(lastPitch - pitch);
    if (lastHeading != 0) {
      if (pitchDiff > motionThreshold || headingDiff > motionThreshold) {
        //cyle through swing sounds
        lastSwingSound++;
        if (lastSwingSound > swingSounds) {
          lastSwingSound = 1;
        }
        String swingFile = "saberswingX.raw";

        char charBuf[50];
        swingFile.toCharArray(charBuf, 50);
        triggerSwing(charBuf);  // needs sequence to iterate through
      }
    }
    lastHeading = heading;
    lastPitch = pitch;
  }

}
void loop() {
  // Add entropy to random number generator; we use a lot of it.
  // random16_add_entropy( random() );

  //handle color selector button
  int BCreading = digitalRead(COLOR_BUTTON_PIN);

  if (BCreading != BClastButtonState) {
    // reset the debouncing timer
    BClastDebounceTime = millis();
  }

  if ((millis() - BClastDebounceTime) > BCdebounceDelay) {
    if (BCreading != BCbuttonState) {
      BCbuttonState = BCreading;

      if (BCbuttonState == HIGH) {
        nextColor();
      }
    }
  }
  BClastButtonState = BCreading;

  selectedColor = presetColors[selectedColorIndex];
  if (selectedColor != lastSelectedColor && bladeState != 0) {
    Serial.print("COLOR CHANGE");
    Serial.println(selectedColorIndex);
    for ( int j = 0; j < NUMPIXELS; j++) {
      strip.setPixelColor(j, selectedColor);
    }
  }
  lastSelectedColor = selectedColor;

  //handle blade on/off

  int reading = digitalRead(POWER_BUTTON_PIN);
  //debounce
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
    }
  }
  lastButtonState = reading;

  if ( pendingPress == 1 && buttonState != LOW) {
    buttonState = HIGH;
    pendingPress = 0;
    Serial.print("execute pending blade press");

    if (bladeOn) {
      powerDownBlade();
    } else {
      powerUpBlade();
    }
  }

  if (buttonState == LOW && !isAnimating) {
    Serial.println("BLADE BUTTON IS PRESSED");
    pendingPress = 1;
  }
  switch (bladeState) {
    case 0:
      //blade is off
      break;
    case 1:
      //blade is animating up
      bladeIsAnimatingUp();
      break;
    case 2:
      //blade is on
      bladeIsOn();
      break;
    case 3:
      //blade is animating down
      bladeIsAnimatingDown();
      break;
  }
  SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
  digitalWrite(LED_PIN, HIGH);  // enable access to LEDs
  strip.show();                     // Refresh strip
  digitalWrite(LED_PIN, LOW);
  SPI.endTransaction();   // allow other libs to use SPI again

  delay(10);

  if (bladeState == 2) {
    detectMotion();
  }

}
void nextColor() {
  selectedColorIndex++;
  if (selectedColorIndex >= totalPresetColors) {
    selectedColorIndex = 0;
  }
}
void triggerSound(const char *filename) {

}
void triggerSwing(const char *filename) {

}

void startHum() {
  //Serial.println("startHum");

}

what port are you talking about? ... how is it related to your sketch?

please format your code to make it readable

So your problem is with the Arduino IDE or with the detection of the teensy board on your PC? Which of OS and which IDE version do you use?

From what I understand TeensyDuino modifies your Arduino IDE installation to make it work with the Teensy. Once that is done it is no longer the Arduino IDE. It doesn't use the standard board manager installation system, but direct modification of the IDE itself. I am not aware of a "port" button in the Arduino IDE (there is a port menu entry though, which only appears if you have a serial port available). The Teensy doesn't use serial for uploading code. You shouldn't need a port for that.

The error message says “you do not have a port selected”. I am talking about the port button in the too bar.

I mean the tool bar

There is no port button in the toolbar of the Arduino IDE. There is "Verify", "Upload", "New", "Open", "Save", and on the far end "Serial Monitor".

Did you fix the problem? I am Working with the same code, but something is stocking with
Colors. I am working with NeoPihel and WS2812.


text:
Best way to send I2C commands between Arduino and ESP32
I made a board with an Arduino nano and a ESP32 Dev kit. I connected them via I2C with voltage adaptation. I'm using arduino IDE and the related library Wire.h.
I send messages as ascii chars or native bytes from the ESP32 (master) to the Arduino (slave) and all work fine.
I have to take a decision now. I have to implement a simple protocol to send command to the Arduino, in order to ask it do some tasks or in order to ask it to send some data to the esp32 (e.g. the speed of a motor or the state of some sensors and so on).
What I would ask is your suggestion if the simple protocol has to be managed as native bytes (the natural way I2C work) or as string (managed by mean of an array).
I try to explain.
In case of bytes I could send for example FF 0E14 01 to ask arduino to start the motor=FF at the speed=0E14 and direction=01. So the specific command is coded in the first byte.
What I miss is the need or not for a delimiter like "<" and ">" as used in case of string. In case of exchange of native bytes the value of "<" is "busy" in an integer and couldn't be distinguish by the parser. So what delimiter could I use?
On the other hand in case of strings I don't like the necessity to convert number "213" or "1529" in the relative integer. In case of the previous command I could send the string
""
having in mind the first char as command and for this specific command "S" ("S" for example) parsing the following chars until the "," and convert it in a integer and last char as direction (as byte or as char the test is the same).
I don't know... what way do you suggest and in case of native bytes what delimiters?
Thanks.

That‘s quite opinion based. To me it seems like you‘ve already figured out the pros and cons of i2c. I personally don’t recommend using a string-like protocol on i2c and stick with the common i2c protocol. You don‘t need start/stop bytes in this case

First, using a byte-value based protocol is the standard with I2C. There is no real reason to go to ASCII encoded data (The reason for doing this with Serial (UART) is normally, that the message is human readable at the PC. This is normally not the case with I2C, since only computers like the Raspberry Pi even have I2C interfaces).
About delimiters: They are only really needed for asynchronous data transfers (as UART)(to frame a full packet/message) or maybe, if you have an unknown transmission size. Both is not the case for I2C (it is a synchronous interface, that already implements transmission packages/message). You can look at the datasheet of any I2C sensor. The standard communication protocol is a command send by the master, then sending/receiving a specific number of bytes with a specific protocol, that defines, which bytes contains which information. Here you don't need a delimiter, because you already know, in what format the data will be send.

Let's take an example from your question: You want the Arduino to report the speed of your motor to the ESP. You implement the first byte of every master write transmission as a command, for example the decimal value 10 as command to report the motor speed. Then you terminate the master write transmission and request 1 byte from the Arduino (since you already know, that the motor speed has 1 byte). The Arduino knows through the command, that it should send the motor speed byte, and the ESP knows, that the byte received will be the 1 byte motor speed.
Now we define the command 11 to report the motor speed and the 3 bytes sensor value. The ESP sends 11 and then requests 4 bytes, as it knows, that the message will be 4 bytes long. The Arduino sends the data and the ESP knows, that the first byte will be the motor speed and the following 3 bytes the sensor value. No delimiter is needed, since the structure of your data is already defined through the implementation of your protocol. Start or end markers for a message are not needed, since I2C already works with distinct message/packets of data (a transmission is started with a START condition on the bus and ended with a STOP condition).

This solution is used for most I2C devices, since it is easier to implement at a low level. At the first glance for us humans it seems easier to use ASCII encoded and thus human readable data. But as you already mentioned, this makes it more complex for microcontrollers (writing parsers for ASCII data is more complex than using binary data on a fixed protocol). Keep in mind, that I2C means "Inter Integrated Circuit", so communication between integrated circuits, not communication between an integrated circuit and a human.
But in the end it is up to you to decide, which protocol you want to use.

As you might not know the concept yet: A Finite State Machine (FSM) is a good way to implement such a communication protocol on both sides. You define a state variable and based on this variable only the corresponding code is executed. You can change the state by changing the state variable.
For example on the Arduino (receiver side): First state could be the command state, where the Arduino waits for an I2C transmission. If a transmission was received, it will read it's first byte. Depending on this byte it will go into a different state, for example into the "Send motor speed" state. There it will prepare everything to send the motor speed to the master, should the master request data from the Arduino.
How to implement a FSM in detail is covered in many tutorials on the web and also in many questions on this side. You can see my answer to this question, where I explained this in more detail.

I appreciate all the details chrisl. I can't vote your answer as I am with low reputations yet. I will proceed as you suggested.

The only concern is about the position of the parser or finite state machine. Since the function "void receiveEvent(int howMany)" is called as an ISR routine following an interrupt, it should be as small as possible. So I shouldn't write the parser inside it. How to deal with this problem? Another question is: could I use the howMany number of byte to understand the correct length of the incoming current packet of byte? Thanks.

If the processing of the message would be too long for an ISR, the normal way is to buffer the message in an extra buffer and set a flag inside the ISR. This flag get's polled inside loop() and the processing is done there, when the flag is set.

Yes, the parameter howMany is the number of data bytes from the transmission, e.g. the number of bytes being received.

You can accept my answer, if you think it is correct. You don't need reputation for that. And you are the only one, that can accept an answer, since you asked this question.

Before giving pointers to your question; First I will start to recommend to avoid using i2C for these kind of things and recommend UART (Serial) which is much better for communication between multiple mcu's.
The UART) Serial Gives you a stack (memory of received data) meaning that you receive data when processing other functions and act on them in arduinos' own time. UART is more then fast enough for things like this and enables longer distances then few cm, its more resilient to interference
UART (Serial) uses fewer ports and most ports can be converted into Software Serial
You will find many libraries which deal with communication even encryption over Serial If you use write() rather then print you don't have to convert the data.if you use correct input on your arduino, you can even read the data as it comes from your PC and much more
Anyway, to your question Most of the data communications tend to have a starting byte and the ending byte to package the pocket among common ones is 00-Start and 0xFF as end.Now assuming that we only have one slave and single priority level etc we don't need to be too much of smartasess for package header... next I would define Process as it will let you chose the function that then can receive then next details as variables.
This option means that you will have to number the operations from 1 not 0Major benefit is that as different function may take different number of variables (for example one only states on off, while other states vector distance) you will not have to decide on a packet length, but simply deal with any number of variables (within reason)

As you can‘t use all numbers between 0-255 on uart (at least you need a stop byte) you‘ll always have to convert data to a char array representation. Also asynchronous is not always an advantage as it makes a parser necessary

I don't get many of your points against I2C. The I2C libraries have a "stack" (which is actually a FIFO buffer, not a stack) just like the Serial library. I2C uses 2 pins just like UART. Libaries for encryption normally handle the data itself; over which interface the data is send is irrelevant for them. write() sends binary data for both interfaces; no difference here. I don't see, why you would need start and end bytes for an I2C transmission (as it already has a START and an END condition; it is already send in a packet). Serial is good for comm between 2 MCU's. More is rather difficult

Also I don't understand everything after "Now assuming that". I just don't get the point, what you want to say there. Can you please explain, what the core point there is?


text:
Super fast UART transimission return error
The code was based on Fahad Mirza's very helpful example here Send structure through Serial
The Sender's code now became
struct Gyro_data_structure
{
  char command_name[5];
  float gyro_X;
  float gyro_Y;
  float gyro_Z;
};

Gyro_data_structure Gyro_data;
int size_gyro = sizeof(struct Gyro_data_structure);

void setup() {
  //Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  //Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
  Serial.begin(250000);
}

void loop() {

  Gyro_data.command_name[0] = 'H';
  Gyro_data.command_name[2] = 'l';
  Gyro_data.gyro_X++;
  Gyro_data.gyro_Y=12;

  Serial.write('p');
  Serial.write('L');
  Serial.write(Gyro_data.command_name, sizeof(Gyro_data.command_name));

  Serial.write('m');
  Serial.write('x');

  send(&Gyro_data);
  delay(100); //---------------------the parameter played in this post
  //Serial.flush();
}

void send (const Gyro_data_structure* table)
{
  Serial.write((const char*)table, size_gyro);  // 2 bytes.
}

The Receiver's code
struct Gyro_data_structure
{
  char command_name[5];
  float gyro_X;
  float gyro_Y;
  float gyro_Z;
};

Gyro_data_structure  Gyro_data_received;
int size_gyro = sizeof(struct Gyro_data_structure);

void setup() {
  Serial.begin(9600);
  //Serial1.begin(9600);
  //Serial1.begin(115200);
  Serial1.begin(250000);
}

void loop() {

  //if(Serial1.available()>0)
  if(Serial1.available()>=size_gyro)//----------------worked very welll//------------------------
  {
      Serial.println(Serial1.available());

    //Serial1.findUntil('p','L');
    //Serial1.find('p');
    //Serial1.find('L');

  if ((Serial1.read() == 'p') && (Serial1.read() == 'L'))
  {
    Serial1.readBytes(Gyro_data_received.command_name, sizeof(Gyro_data_received.command_name));

    Serial.println("Received confirmation");
    Serial.println(Gyro_data_received.command_name[0]);
    Serial.println(Gyro_data_received.command_name[2]);

    if ((Serial1.read() == 'm') && (Serial1.read() == 'x')) {

      Serial.println("Gyro data received");
      receive2(&Gyro_data_received);

      Serial.println(Gyro_data_received.command_name[0]);
      Serial.println(Gyro_data_received.gyro_X);
      Serial.println(Gyro_data_received.gyro_Y);
    } else {
      Serial.println("Gyro data lost");
    }

  } else {

    Serial.println("No code confirmed");
    while(Serial1.peek()!='p'){
    Serial.print(Serial1.read()); //basically clean the receiver
    //Serial1.flush();
    }

  }

  }
}

bool receive2(Gyro_data_structure* table)
{
  return (Serial1.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
}

What it does is for sender send a 5 byte char array and a structure to receiver. If receiver received the "code", i.e. char 'p' 'L' and 'm' 'x' it read the incoming 5byte char array and structure. If the code was not confirmed, it clear the incoming bytes.
However, I encountered the following issue.
First, at receiver's code, one pay attention to
  if(Serial1.available()>0)
  if(Serial1.available()>=size_gyro)

the condition for which the receiver start to process the read() sequence.
However, at speed(9600), I noticed that if one use
if(Serial1.available()>0)

very often it start to read when Serial1.available()=1, and return incorrect numbers which got cleared out by
Serial.println("No code confirmed");
while(Serial1.peek()!='p'){
Serial.print(Serial1.read()); //basically clean the receiver
//Serial1.flush();
}

But if one use
  if(Serial1.available()>=size_gyro)

as the condition to trigger the read(), it worked out very well. On the other hand, if one increase the serial speed to, say 115200, this does not matter, as they both return the correct result. Could you explain to me why this was the issue, please?
Second, please pay attention to
  send(&Gyro_data);
  delay(100);

At speed at or above 100, with nano board and mega board, this worked out fine. But if one wants to increase the transmission speed, change delay(100) to delay(20) in sender's code, the receiver's code returns error. This issue could not be resulted by change the wiring or increase the serial speed. Especially, the receiver's at part
  Serial.println(Serial1.available());

usually return a number of 62~63 when there's an error.
Could you explain to me where did those two questions come from? Were they because the chip set on Arduino? Especially, how to achieve a communication response under 20 ms?

what two questions are you talking about?

In my answer to your previous question, I wrote: “Binary is, however, harder to handle: [...] you may need to define a protocol of sorts in order to get the framing right. [...] I generally recommend using ASCII unless you really need the extra efficiency of a binary protocol.”. You see what I mean now?

Do you have an idea what serial speed means? Think about what your program does, and how fast bits and bytes are transfered.

First, you got some logic wrong in the receiver: you have a test for
Serial1.available()>=size_gyro and, when this is true, you read
size_gyro + 9 bytes. You should change the test in order to only start
reading when you actually have size_gyro+9 bytes available.
Then, note that command_name is transmitted twice: first as part of
the 9-byte preamble (between "pL" and "mx"), then as part of the
transmitted Gyro_data_structure. There is no point in doing so.

at speed(9600), I noticed that if one use if(Serial1.available()>0)
  very often it start to read when Serial1.available()=1, and return
  incorrect numbers

This is expected: you wait for 1 byte to be available in the input
buffer, then you attempt to read the 9-byte preamble. One of your calls
to Serial1.read() is going to find the buffer empty, and it will then
return −1.

But if one use if(Serial1.available()>=size_gyro) as the condition
  to trigger the read(), it worked out very well.

In other words, when you wait until 17 bytes are available before
reading the 9-byte preamble, you get at least the preamble right. Is
this surprising?

if one increase the serial speed to, say 115200, this does not matter,
  as they both return the correct result

Your code takes some time to do the reading. At a fast enough baud rate,
the serial port receives the incoming bytes faster than your code reads
them, so you never run into an empty buffer.

if one wants to increase the transmission speed, change delay(100) to
  delay(20) in sender's code, the receiver's code returns error

The sender is going too fast, and the receiver cannot cope with the data
rate.

Serial1.available() usually returns a number of 62~63 when there's
  an error.

This means the receive buffer is full.
Note that the receiver would be way faster if it wasn't printing so
much. Upon receiving a correct transmission, it will Serial.println()
a bunch of messages that should total at least 64 bytes. Transmitting
those bytes at 9600 b/s takes more than 66.5 ms.

Edit: proposed solution.
Your idea of prepending a “code” to the data structure in order to
identify a correct transmission is in the right track. This is a kind of
format indicator commonly known as a “magic number” or a
“signature”. It does not ensure correct transmission with 100%
confidence, as the signature could be present by accident as part of the
data structure itself. But if the signature bytes are unlikely enough to
happen by accident, you have a pretty high confidence that wherever you
find the signature in the data stream it's the start of a new packet.
You can increase this confidence by making the signature longer, at the
cost of longer transmission times.
Now, for a matter of simplicity, I would not send the signature as two
disjoint parts. Common practice is to send it as one contiguous set of
bytes, at the very beginning of the packet. For example, I would send
your packets like so:
// 5-byte signature, including the terminating '\0'.
const uint8_t Gyro_signature[] = "Gyro";

void Gyro_send(const Gyro_data_structure &gyro) {
    Serial1.write(Gyro_signature, sizeof Gyro_signature);
    Serial1.write((uint8_t *) &gyro, sizeof gyro);
}

You may want to change the signature to something less likely to happen
by accident.
On the receiver side, when you expect the signature, you read from the
port one byte at a time while counting how many correct bytes you have
so far. The algorithm goes as follows:

let i = 0 be the number of correct bytes received so far
read an incoming byte
if that incoming byte is correct, increment i
otherwise, if we just got the first signature byte, reset i = 1
otherwise reset i = 0
unless we got the full signature, go to 2

This assumes that the first signature byte doesn't appear elsewhere
within the signature. Otherwise steps 4–5 would be more complex.
Here is a receiver function that implements this algorithm, then reads
the data structure:
void Gyro_receive(Gyro_data_structure &gyro) {

    // Read until we get a complete signature.
    int discarded = 0;
    for (size_t i = 0; i < sizeof Gyro_signature; ) {
        if (Serial1.available()) {
            char c = Serial1.read();
            if (c == Gyro_signature[i]) {  // correct byte
                i++;
            } else if (c == Gyro_signature[0]) {  // first byte
                discarded += i;
                i = 1;
            } else {
                discarded += i+1;
                i = 0;
            }
        }
    }
    if (discarded) {
        Serial.print("Discarded ");
        Serial.print(discarded);
        Serial.println(" bytes.");
    }

    // Wait for the data.
    while ((size_t) Serial1.available() < sizeof gyro)
        /* wait */;

    // Read it.
    Serial1.readBytes((char *) &gyro, sizeof gyro);
}

Note that this function is blocking. If you need a non-blocking version,
you should be able to easily convert the signature-checking part into a
finite state machine where i is the state variable.


text:
Noob here.. Need help with a thermostat controlled relay
So After trying several sketches for a LM35 and none working I finally found one that was giving me accurate results. The problem is the code is way over my head. I was able to modify it enough to get the serial and temperature to a LCD but I cant figure out why its not tripping the relay after set values. The sketch completely ignores the temperature value therefor will never set the relay HIGH. What am I missing?
/*
 LM35 thermometer, no floats, no delays

  http://www.ti.com/lit/gpn/lm35
*/
const int relay = 0;
const byte sampleBin = 8, // number of samples for smoothing
           aInPin = A5;
const int fudge = 170; // adjust for calibration
const int kAref = 1090, // analog ref voltage * 1000
          kSampleBin = sampleBin * 1000,
          tEnd = 5000; // update time in mS
int tempC,
    tempF;
uint32_t total,  // sum of samples
         tStart; // timer start
int sensorPin = 5;// The analog pin the LM35's Vout is connected to.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

/*
Initialize serial connection with the computer*/
void setup()
{
  pinMode(relay, OUTPUT);
  Serial.begin(9600);
  lcd.begin(16,2);
  analogReference(INTERNAL); // use 1.1V internal ref
  analogRead(aInPin);
  for (int i = 0; i < sampleBin; i++) // for smoothing, fill total
    total += analogRead(aInPin);   // with sampleBin * current
                                   // reading
}

void loop()
{
  if (millis() - tStart > tEnd)
  {
    tStart = millis(); // reset timer
    total -= (total / sampleBin); // make room for new reading
    total += analogRead(aInPin); // add new reading
    tempC = total * kAref / (kSampleBin + fudge);
    tempF = (tempC * 18 + 3200) / 10;
    Serial.print("Temperature- ");
    prntTemp(tempF);
    Serial.println();
  }
}

void prntTemp(int temp)
{
  Serial.print(temp / 10); // whole degrees
  Serial.print(".");
  Serial.print(temp % 10); // tenths
  Serial.print("\t");

  // display Temperature on LCD
  lcd.setCursor(0,0);
  lcd.print("Temperature-");
  lcd.setCursor(0,1);
  lcd.print(tempF);
  lcd.println(" degrees F ");
  delay(10);// print data every 10milliseconds

  if (tempF >= 78.0)
  {
    digitalWrite(relay, HIGH);
  }
}

Does the LCD show the expected temperature? -- Are you sure that your relay is connected to Pin 0? Did you check this with another simple sketch? -- tStart is initialized with 0, do you want this?

Not related to your problem: The delay(10); in prntTemp() is not necessary, because the latter is called only every 5 seconds. -- Not related to your problem that relay is not set HIGH, but will be a problem if that will work: You need an else branch that resets the relay to LOW. -- And, again not related to your problem: You don't need to access tempF in prntTemp() as it is provided as the argument in parameter temp.

Please show us the serial output


text:
Power Source for Arduino
So I have SIM900 Shield and Arduino Uno and they have both power jack, is it possible to power one of them using one power jack and connect it's power with another? If it is possible, I sincerely need the explanation.
I've research about the VIN pin of Arduino but I didnt quite get it and can't take the risk that I might fry the board since Im new here.

It depends on what voltage the devices run at and what their current draw is from the power supply versus what voltage & current your power supply provides.
If everything runs at 3.3V or 5V and minimal amps then you're good to go.
Read the datasheet for each device and for your power supply.


text:
Digispark clone not recognised when plugged in
When I plug in my digispark clone the computer doesn't make any sounds or some kind of acknowledgement that it has been plugged in. Anyone know why this may be or is it just a dodgy clone?

possibly not pre programmed

The Digispark does not use a "standard" USB-to-Serial chip but is dependent on a special bootloader called "micronucleus" that makes it (sort of) act like a USB device.
Below is a description of the steps you need to perform for a Windows system and the Arduino IDE.

First, you will need to install a Windows driver for Micronucleus: Zadig USB driver

If your ATTiny is recognized by Windows after performing the driver installation, then all is fine and you can skip to step 4.
If Windows still does not recognize your Digispark clone, its ATTiny processor might not have come with micronucleus pre-programmed and you need to perform steps 2 and 3. Unfortunately this is for advanced users and might be difficult if you're inexperienced with electronics and/or Arduino.

Download Micronucleus from Github
Follow This tutorial from Digispark to install micronucleus on your ATTiny. You will need another Arduino (Uno, Nano, Mega, Mega2560, ... or clone) for that.
Then follow This tutorial from Digistump to enable the Arduino IDE to program your Digispark clone directly from USB.

I assume one wants t85_default.hex for an ATTiny85 IC?

@Scott Correct, you need to download it from the Github repository (linked to by the Digispark site), or from the zip file in the 3rd step (it's under firmware/releases).

yeah I got that part and found the repository but there were about 9 or 10 hex images in there with no documention I could see as to what was what

It sounds like a driver problem.
If you are on Windows, check your Device Manager and see if the new device is detected and has proper driver installed. If it is, you should see a COM port added when you attach the board.
There are different USB chips that manufacturers use (CH340G and FT232RL, as far as I know), and not all of them have their drivers already installed on Windows.
Check your board to see what chip it is, google for the drivers and the setup procedure for your OS.
You can also check Digispark Installation Instructions and try the driver they provide.


text:
Arduino Zero RTC alarm not running loop
Using an ATSAMD21 with the Arduino core, I'm running into an issue where the RTCZero alarm callback won't continue running the loop() function. If I schedule another alarm inside the callback, the second alarm will execute the loop() function after the callback is done. Every second time it works, every other time it doesn't.
Minimal example in which I expect the LED to change state every 2 seconds, which does not happen:
#include <RTCZero.h>
#include <time.h>

RTCZero rtc;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  rtc.begin();
  rtc.attachInterrupt(alarmMatch);
  schedule_wake_up();
  rtc.enableAlarm(rtc.MATCH_HHMMSS);
}

void loop()
{
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  schedule_wake_up();
  rtc.standbyMode();    // Sleep until next alarm match
}

void schedule_wake_up() {
  time_t wakeupTimestamp = rtc.getEpoch();
  wakeupTimestamp += 2;
  struct tm *wakeupTimeStruct = gmtime(&wakeupTimestamp);

  rtc.setAlarmSeconds( wakeupTimeStruct->tm_sec );
  rtc.setAlarmMinutes( wakeupTimeStruct->tm_min );
  rtc.setAlarmHours( wakeupTimeStruct->tm_hour );
}

void alarmMatch()
{
  // Do nothing, just wake up
}

Arduino IDE 1.8.9
RTCZero ver 1.6.0
SAMD core ver 1.8.4 and 1.6.20 tried

I ended up deleting my copy of RTCZero and installing a new one via the Arduino IDE library manager. This solved the issue.
The difference between my local copy and the upstream one is in the standbyMode() function. I had the following PR merged into my local copy of this function:
https://github.com/arduino-libraries/RTCZero/pull/46/files
After I installed the clean copy I went and replaced the standbyMode() function's content with the following:
https://github.com/arduino-libraries/ArduinoLowPower/blob/892594adbccf45b198fc067ea994048c76523936/src/samd/ArduinoLowPower.cpp#L18


text:
What happens to serial output when no-one is listening?
This question probably needs a better title but I'm having trouble thinking of one! Please feel free to edit or suggest one.
My target system is a pair of Arduino Leonardos linked by XBee radios. One is the coordinator and is expected to communicate with a host PC over the USB connection (virtual serial port). The coordinator parses commands and potentially forwards them on to the endpoint by radio. The endpoint replies to commands and can also generate output spontaneously. Both devices can also send diagnostic output to the USB/Serial port. The endpoint sends "heartbeat" messages every 8 seconds. If the coordinator misses 2 consecutive heartbeats then it'll reinitialize. If the endpoint sends a heartbeat and doesn't get a response within a couple of seconds, then it will also reinitialize.
This all seems to work pretty well, but I've noticed something odd. If I connect to both devices with a terminal emulator and just watch the output, everything is good and the system is stable for at least 14 hours (the longest I've tested it). I can see the heartbeat messages happening and the diagnostic output coming out. However, as soon as I disconnect one of the serial ports, things begin to fail. The XBee comms state machine appears to time out at both sides and goes into an endless re-initialization loop.
I'm struggling to think why this might be, but disconnecting one of the serial ports reliably causes the issue within 10 to 20 seconds (I think the "no heartbeat" timeout is being hit).
It seems like if nothing is listening to the serial port, something is getting jammed up. My understanding is that its OK to read from and write to a port that nothing is connected to, and that data will just fall into the bitbucket. Is this not the case? Why should disconnecting the client from the serial port jam everything up?
UPDATE: I've tested with this modified "blink" sketch:
#include <Arduino.h>

auto& host = Serial;

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  host.begin(115200);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  host.print("Time ");
  host.println(millis());
}

With something (PuTTY) connected to the USB/serial port, I get a nice even mark-space ratio on the LED. As soon as I disconnect PuTTY, the 'off' period of the LED becomes about twice as long as the 'on' period, i.e. there is upwards of a second delay each time I write to the serial port. Is that normal?

It depends what the mystery devices you have that communicate over USB are and how they are programmed.

@Majenko, [arduino-leonardo]

@Juraj I never trust tags.

add some LED on/off code to aid debugging ...for example, LED on before serial comm and LED off after serial comm

Do you also read from serial? Eventually (un)plugging the serial port causes an edge on the receiving line which results in an arbitrary value. Depending on how you manage serial inputs on the arduino anything could happen

@jsotola that's a great idea, I think I will do that.

@SimSon yes I do (read from serial). My command parser is pretty bomb proof though so it shouldn't be an issue.

Arduino Leonardo uses its built-in USB to create "Serial Port". Probably that's why it's print acts differently than Arduino UNO. UNO has a separate IC for the virtual com.

OK so here is my solution.
I made a wrapper class called SafeSerial. In SafeSerial.h:
#pragma once
#include <Arduino.h>

class SafeSerial : public Serial_
    {
    size_t write(const uint8_t* buffer, size_t size) override;
    };

In SafeSerial.cpp:
/*
 * SafeSerial implementation for Arduino Leonardo.
 * Overrides the Serial_::write() method and checks that there is enough room
 * in the output buffer. If not, the output is discarded.
 * The intent is to prevent serial output from blocking when no host is listening.
 * All other operations are handed off to the underlying Serial_ instance.
 */

#include "SafeSerial.h"

size_t SafeSerial::write(const uint8_t* buffer, size_t size)
    {
    /*
     * Check if we can write without blocking. If we need to block,
     * then we assume that the host has disconnected.
     */

    if (availableForWrite() < size)
        return 0;

    return Serial_::write(buffer, size);
    }

In my sketch, in global scope:
SafeSerial host;

Now, because I'm using <ArduinoSTL> and all my output goes via std::cout, I need to take some actions to correctly configure that library. This requires modifying the library code per the instructions in the README.md file to make it not default to the built-in Serial instance and to not create default instances of cin and cout. This now needs to be done in the sketch, so (again in global scope):
// cin and cout for ArduinoSTL
namespace std
    {
    ohserialstream cout(host);
    ihserialstream cin(host);
    }

and in setup():
    host.begin(115200);
    // Connect cin and cout to our SafeSerial instance
    ArduinoSTL_Serial.connect(host);

...and finally, I have fully non-blocking Serial I/O even when the host has disconnected, at the risk of some possible data loss. However so far, in my application, data loss doesn't seem to be an issue as I only produce minimal terse output and generally only 1 line every few seconds.
Thank you all for your valuable input.

Theoretically, nothing should happen to serial data if nothing is listening.

For a traditional UART the data is just sent regardless. It doesn't need someone listening for that to happen.  Like a light doesn't need someone to see it for it to be on.
For USB CDC/ACM the data should be discarded even before it's attempted to be sent.

The latter, though, does rely on the host computer "playing ball" and cleanly closing the port properly.  On most operating systems that is handled by the OS and happens automatically. However on Windows it is handed off to the driver, and I guess the driver may even hand it off to the terminal software.
So in Windows there is a chance that when you disconnect your serial port it's not cleanly closing the connection and the USB thinks it's still connected, thus blocking waiting for the serial data to be collected.

I've updated my question with additional info and a simple test sketch. When I disconnect the serial port, I'm seeing something like a second delay every time around my loop.

OK let's try a different angle. It looks like I have a problem with serial output blocking even though there's nothing connected to the serial stream. If I were to write a new stream class that wraps the serial stream, maybe I could make manual checks to see if I should write the data to the underlying stream, or simply discard it. In that situation, what do you think I should check for?

@TimLong Well, the only thing you really can check is the CDC/ACM "Line State" - and the existing code already does that.

You could try looking at the returned value of Serial.availableForWrite() to see if there is enough buffer space...

https://www.arduino.cc/reference/tr/language/functions/communication/serial/availableforwrite/

That looks like it might be worth a try. Thanks for the input.


text:
Communication between Arduino and python: serial port sending empty data
Arduino code:
this code is provided communication between sensor gy-521 and arduino. I read data by the command "1", after 1000 samples arduino is waited for new command for read data.
Arduino code works well in arduino port.
#include<Wire.h>
const int MPU=0x68;
int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;
//int incom = 0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(19200);
  while (!Serial);// wait for serial port to connect. Needed for native USB port only
}

void loop(){
  if (allow){ //if allow == true, read data

    for (int i = 0; i < 1000; i++){
      Wire.beginTransmission(MPU);
      Wire.write(0x3B);
      Wire.endTransmission(false);
      Wire.requestFrom(MPU,12,true);
      AcX=Wire.read()<<8|Wire.read();
      AcY=Wire.read()<<8|Wire.read();
      AcZ=Wire.read()<<8|Wire.read();

      time = millis();
      Serial.print(time);Serial.print(",");Serial.print(AcX);Serial.print(",");Serial.print(AcY);Serial.print(",");Serial.println(AcZ);
      delay(0);
    }
    Serial.println(0); //see UPD.3
    allow = false;
  }
}

void serialEvent() {
  while (Serial.available()){ //wait for command
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0){ //if 0 - stop
      allow = false;
      delay(100);
    }
    if (incom == 1){ //if 1 - read data
      allow = true;
      delay(100);
    }
  }
}

Python code:
    def sensors(self):

        self.arduino_port_sensor.reset_input_buffer() #clear buffer

        self.arduino_port_sensor.write(str(1).encode()) #send command to arduino - read data

        main_array = []

        pbar = tqdm(total=self.time_observation) #just to see the progress

        while True:

            values = self.arduino_port_sensor.readline().decode().rstrip().replace(" ", "") #read data, some manipulation for cleaning
            main_array.append(values)

            pbar.update(1)

            if values == '': #if data is empty
                print('!!!!')
                continue
            if values == '0': #see UPD.3
                break

        pbar.close()
        ...bla bla...

I call this function time to time, then in some step, arduino stops sending data -- it sends empty string.
It looks like:
PS. In this code I use 2 ports: for sensor and for motor, 2 different arduino. The principe of working second arduino with motor the same, but it works without any problem (I just send command with "action" to arduino with motor, and then receive answer "received back")

Question: what's wrong with python? how to fix this problem?

UPD
Initialization:
arduino_port_sensor = serial.Serial('/dev/tty.usbmodem143101', 19200, timeout = 1)

UPD.2
It receive command - "1" - read data, the interruption occurs while reading data:

UPD.3
Also i changed the code of arduino -- added the "0" after loop.
UPD.4
If I recall this function after arduno stopped sending data, I get this:

How did you initialize the PySerial? Your python code doesn't show that.

There can be different issues:

Are you sure Arduino is sending something? For example, when you say you stopped getting gata, check if the TX LED on the Arduino board is blinking or not.
Did Arduino actually receive "1" before you stopped getting data?
What's the timeout of the PySerial? Are you trying to read faster than Arduino can provide?

I added initialization 1) yes, because it works some iterations (the most long work about 39 iterations). My program wont work if arduino not sending data. 2) yes, I checked this. Before getting data I always have "1" in the beggining. 3) timeout = 1, btw how it can work in some iterations and not working after?

What I actually meant, WHEN it stopped working, it can be either your Python or the Arduino. It worked for 39 iterations. So Arduino was sending data during those 39 iterations. But when it stopped working, is it because of Arduino is not sending anymore or 'for some reason' Python is not able to read it. One way to verify is, check the Tx LED on the Arduino board WHEN your system stopped working. If the LED still blinks as it was, when the system was working, then we know for sure its the Python we need to fix.

Same for this too, did you receive '1' in the Arduino right before it stopped working? One way to check this is when it stops working print the main_array. If main_array doesn't have '1', that means your Arduino never sent '1' i.e. it never received '1'.

I showed this in UPD.2: arduino receives command - read data - but then something happens 1) YES! Thanks, i didn't really notice this. You are right - when it works (python read data) the  Tx LED blinks. But then I see "!!!!" - empty string - Tx LED is not blinking. So, the problem in arduino?

There can be different reasons for your issue. But from the update you added later, we can at least say that your Arduino sometimes doesn't receive the character "1". And when that happens, your Python gets stuck in the infinite loop of trying to read something from the serial port.
As your Arduino responds with "1" when it receives "1", you can base your application on that i.e. if Arduino doesn't respond with "1", keep sending "1".
I wrote a sample program based on your code. I removed the "Wire" part in the Arduino code as I don't have your sensor. I would urge you to test with this Arduino code to make sure that Your sensor is not blocking your Arduino. Wire read can be blocked forever depending on the IC you are trying to read (and if you don't have a timeout).
int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;

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

void loop()
{
  if (allow) //if allow == true, read data
  {
    for(int i = 0; i < 10; i++)
    {
      AcX = 1;
      AcY = 2;
      AcZ = 3;

      time = millis();
      Serial.print(time); Serial.print(",");
      Serial.print(AcX);  Serial.print(",");
      Serial.print(AcY);  Serial.print(",");
      Serial.println(AcZ);
    }
    Serial.println('0');
    allow = false;
  }
}

void serialEvent()
{
  while (Serial.available()) //wait for command
  {
    int incom = Serial.read() - '0';
    Serial.println(incom);
    if (incom == 0)          //if 0 - stop
    {
      allow = false;
      delay(100);
    }
    if (incom == 1)          //if 1 - read data
    {
      allow = true;
      delay(100);
    }
  }
}

In the Python code, I checked if I received "1" from Arduino. If not I kept trying.
import serial
import time

def sensors():
    # Clear receive buffer
    arduino_port_sensor.reset_input_buffer()

    while True:
        # Send command to arduino to send data
        arduino_port_sensor.write('1'.encode())

        # As arduino send LF and CR at the end, let's strip those from the end
        response = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        # Arduino should respond with the cmd that it received,
        # if not, send cmd again
        if response == '1':
            # Arduino acknowledged
            break
        else:
            print('Did not receive 1. Retrying...')

    main_array = []

    while True:
        values = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

        if values == '':
            print('!!!!')
            # This should never happen, but if it does happen, try to read again
            continue
        elif values == '0':
            # print(main_array)
            # We are done receiveing packets
            break
        else:
            # We are still receiving packets
            main_array.append(values)

arduino_port_sensor = serial.Serial('COM50', 19200, timeout=3)

# Let PySerial get ready
time.sleep(3)

while True:
    sensors()
    time.sleep(1)


text:
Regarding Geared motor encoders
I wrote a simple code to count the number of pulses when the motor runs.
The code just counts the number of interrupts from the encoder, but the output is very weird.
Even when the motor is not running it outputs huge numbers of the range of 10000s as the number of pulses.
Same case with the other motor.
Is something wrong with the encoders or am i missing something?

what are you counting? ... i do not see any circuit diagram

Please edit your question to add the sketch you're using in text format. Highlight the sketch then click the {} button to give it the correct formatting.

You should use digitalPinToInterrupt(pin) instead of directly passing the interrupt number (0 should be correct, though). The reason for those readings you get when the motor isn‘t running could be that the interrupt pin is floating. Try pinMode(encoder_in, INPUT_PULLUP);.