text:
Sending letter by letter to LCD, however the LCD knows the full string?
I think this is my last post about this specific project, but I got a really weird curveball right now
I managed to do the webpage I wanted, and pass the string along. Now, when a LED lights up, it sends the corresponding letter to the LCD.
The problem now is that somehow, when I send a long string, the LCD somehow "knows" and display the overflow on the second row, which makes no sense to me. All I can think of is that the Ethernet Shield is using the same connections as my I2C that connects to the LCD.
That being said, here is my code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <Ethernet.h>
#define latchPin 5
#define clockPin 7
#define dataPin 6

LiquidCrystal_I2C lcd(0x27,16,2);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server(80);
String text;
char readHttp[100];
int i;
boolean temtexto;
char lcdtext[16];
void setup() {
  Serial.begin(9600);
  for (int i = 2; i < 7; i++) {
    if (i != 4) {
      pinMode(i, OUTPUT);
    }
   }
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  lcd.init();
  lcd.setBacklight(HIGH);
  lcd.setCursor(0,0);
  lcd.print("INICIANDO");
  Serial.println("Iniciando");
  if (Ethernet.begin(mac) == 0) {
    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("FALHA AO PEGAR");
    Serial.println("FALHA");
    lcd.setCursor(7,1);
    lcd.print("IP");
    delay(5000);
    return;
  }

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("PRONTO");
  lcd.setCursor(0,1);
  lcd.print(Ethernet.localIP());
  lcd.setCursor(0,0);
  Serial.println(Ethernet.localIP());
  server.begin();
  brilho(255);
  inicializationEffect();
}

void loop(){
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        lcd.setBacklight(LOW);
        lcd.clear();
        char c = client.read();
        if (c == ';') { temtexto = false; readHttp[i] = '\n';}
        if (temtexto) {
          if(i < 100) {
            readHttp[i] = toupper(c);
            i++;
          }
        }
        if (c == '?') { temtexto = true; }
        if (c == '\n') {
          client.println("HTTP/1.1 200 OK"); // Envia nova pagina
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();
          client.println("");
          client.println("");
          client.println("<TITLE>Parede Stranger Things</TITLE>");
          client.println("");
          client.println("");
          client.println("
Qual texto deseja enviar?
");
          client.println("<input type=text id=texto style=width:295px  maxlength=50>
");
          client.println("<input type=submit value='Enviar' style=width:150px;height:45px onClick=location.href='/?'+document.getElementById('texto').value+';'>");
          client.println("");
          client.println("");
          client.println("<string>");

          client.println("</string>");
          delay(1);
          client.stop();
          char *leader = readHttp;
          char *follower = leader;

          // While we're not at the end of the string (current character not NULL)
          while (*leader) {
              // Check to see if the current character is a %
              if (*leader == '%') {

                  // Grab the next two characters and move leader forwards
                  leader++;
                  char high = *leader;
                  leader++;
                  char low = *leader;

                  // Convert ASCII 0-9A-F to a value 0-15
                  if (high > 0x39) high -= 7;
                  high &= 0x0f;

                  // Same again for the low byte:
                  if (low > 0x39) low -= 7;
                  low &= 0x0f;

                  // Combine the two into a single byte and store in follower:
                  *follower = (high << 4) | low;
              } else {
                  // All other characters copy verbatim
                  *follower = *leader;
              }

              // Move both pointers to the next character:
              leader++;
              follower++;
          }
          // Terminate the new string with a NULL character to trim it off
          *follower = 0;
          lcd.clear();
          executeEffect(readHttp);
          memset(readHttp, 0, sizeof readHttp);
          i = 0;
        }
      }
    }
  }
}

void lineActivation(int line, int keepalive) {
  if (keepalive == 0) {
    for (int i = 2; i <= 4; i++) {
      if (i == 4) { i = 8; } //porta 4 usada pelo SD do Ethernet
      digitalWrite(i, LOW);
    }
  }
  if (line >= 1 && line <=3){
    if (line == 3) { line = 7; } //porta 4 usada pelo SD do Ethernet
    digitalWrite(line+1, HIGH); //coloca a linha 1 em estado lógico alto
  }
}

void activateLetter(char letter, int on, int off) {
  int lt;
  lt = (((int)letter - 64) % 9);
  if (((int)letter - 64) > 8) {
    lt = lt + 1;
  }
  if (on) {
    callCol(1<<lt-1);
    delay(on);
  }
  if (off) {
    callCol(0);
    delay(off);
  }
}

void callCol(int col){
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, highByte(col));
  shiftOut(dataPin, clockPin, MSBFIRST, lowByte(col));
  digitalWrite(latchPin, HIGH);
}

void executeEffect(char text[]) {
  if (strlen(text) > 0) {
    brilho(255);
    lcd.setBacklight(HIGH);
    memset(lcdtext, ' ', sizeof lcdtext);
  }
  for (int i = 0; i < strlen(text); i++) {
    if (text[i] == ' ') {
      lcdScreen(' ');
      delay(1000);
    } else if (((int)text[i] < -58 && (int)text[i] > -65) || ((int)text[i] < -28 && (int)text[i] > -33)) {
      text[i] = 'A';
    } else if (((int)text[i] < -47 && (int)text[i] > -41) || ((int)text[i] < -9 && (int)text[i] > -14)) {
      text[i] = 'O';
    } else if (((int)text[i] < -52 && (int)text[i] > -57) || ((int)text[i] < -20 && (int)text[i] > -25)) {
      text[i] = 'E';
    } else if (((int)text[i] < -49 && (int)text[i] > -53) || ((int)text[i] < -16 && (int)text[i] > -21)) {
      text[i] = 'I';
    } else if (((int)text[i] < -35 && (int)text[i] > -40) || ((int)text[i] < -3 && (int)text[i] > -8)) {
      text[i] = 'U';
    } else if (((int)text[i] == -25 || (int)text[i] == -57)) {
      text[i] = 'C';
    }
    if ((int)text[i] < 65 or (int)text[i] > 90) {
    } else {
      lineActivation(int(((int)text[i] - 64) / 9) + 1, 0);
      //Serial.println(text[i]);
      lcdScreen(text[i]);
      activateLetter(text[i], 1000, 200);
    }
  }
  for (int i = 0; i < 16; i++){
    lcdScreen(' ');
    delay(500);
  }
  lcd.setBacklight(LOW);
  lcd.clear();
}

void lcdScreen(char ltc) {
  Serial.println(ltc);
  memcpy(lcdtext, &lcdtext[1], sizeof(lcdtext) - sizeof(char));
  lcdtext[15] =  ltc;
  lcd.setCursor(0,0);
  lcd.print(lcdtext);
}

void inicializationEffect() {
  Serial.println("LineByLine");
  for (int i = 1; i < 27; i++) {
    lineActivation(int(i / 9) + 1, 0);//ativa a linha
    activateLetter(char(64 + i), 100, 10); //ativa a letra
  }
}

void waveEffect() {
  Serial.println("Wave");
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);//ativa a linha
  }
  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 100, 0);
  }

  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 0, 100);
  }
  lineActivation(0, 0);
}

void blink() {
  Serial.println("Blink");
  callCol(511);
  lineActivation(1,1);
  lineActivation(2,1);
  lineActivation(3,1);
  for (int i = 0; i < 256; i++){
    brilho(i);
    delay(1);
  }
  delay(100);
  for (int i = 255; i >= 0; i--){
    brilho(i);
    delay(1);
  }
}

void brilho(byte brt) {
  analogWrite(9, 255-brt);
}

I am using a W5100 Ethernet Shield, a I2C to LCD adapter and a 16x2 LCD. The I2C is connected to the pins A4(SDA) and A5(SCL).
Here is a picture of how the LCD appears when I send "This is a really long string":

On the first line the text scrolls, one character at a time, as intended. However, on the second line there is an overflow of the text that, as far as I can tell, I never sent to the LCD in the first place. Even if I try to lcd.clear() after every character sent, it still persists with the end of the string on the second line.

I think what you're seeing is the result of:
lcd.print(lcdtext);

and the fact that lcdtext is not null-terminated.  print() is expecting
a string, that is some sequence of zero or more non-'\0' characters followed by a '\0' character.  Not having null-terminated it yourself, in practice it will continue reading memory after your the location of lcdtext in memory until it finds a '\0'.  Somewhere in there it is probably finding the extra character(s) that you're seeing.
You could make a point of having '\0' at the end of it always, making lcdtext one character larger if necessary in order to do that.  Or you could:
lcd.write(lcdtext, sizeof lcdtext);

In this form with the length/size as a second argument, write doesn't expect a string, just an arbitrary chunk of characters whether they contain '\0' or not and knows to stop at whatever count of characters was specified.
As an aside memmove should be used rather than memcpy when the input and output destinations overlap.  What happens with memcpy when they do overlap is undefined:
memmove(lcdtext, &lcdtext[1], sizeof(lcdtext) - 1);

memmove is outwardly the same thing, only designed for this scenario.  The difference between them is a matter of which optimizations are enabled by the knowledge that the source and destination may or may not overlap. It may not be a source of a problem on your current platform, depending on how memcpy was written, but it may later or when you switch platforms.

I replaced memcpy with memmove and it worked the same way as before. The lcd.write is not a function on <LiquidCrystal_I2C.h>, which is the library I am using for I2C to communicate with led. Adding a '\0' to the end just removed the 4 lines at the end. The RING still appeared

@Feeds, I'm not surprised memmove() made no difference on an AVR.  I am sort of surprised you're not able to use that form of write() though, since it is part of the Print class which provides print() and println() among others.  Do you have a link to the exact rendition of LiquidCrystal_I2C library you're using?

Now that I think about it, the problem may reside on the lcdtext not being a string, but a char array. The library I am using is the one on sketch https://github.com/johnrickman/LiquidCrystal_I2C, version 1.1.2

At https://github.com/johnrickman/LiquidCrystal_I2C/blob/master/LiquidCrystal_I2C.h#L55 you can see where Print inherited.  At https://github.com/johnrickman/LiquidCrystal_I2C/blob/master/LiquidCrystal_I2C.cpp#L10 single character write() is implemented.  https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/Print.cpp#L34 where the default implementation is for the two-parameter version of write() mentioned uses the single character write().

In other words, it should work fine.  If that's a sticking point, take some time with it and if still stuck maybe start a new question with a cut-down code example asking about that one aspect.

I am away from my arduino right now, but I will test as soon as I get home to report my findings. I am still weirded out how the LCD works

Huh, I kinda solved it, but I still dont get it how the lcdtext was getting the full string.
I replaced the lcdScreen function with this:
void lcdScreen(char ltc) {
  Serial.println(ltc);
  Serial.print(lcdtext);
  memmove(lcdtext, &lcdtext[1], sizeof(lcdtext) - 1);
  lcdtext[15] =  ltc;
  lcd.setCursor(0,0);
  for (int i = 0; i < 16; i++){
    lcd.print(lcdtext[i]);
  }
}

It works, but I still dont understand why I had the full text when I am just calling this function with a single char each time


text:
Digital pin output voltage drops when driving a relay
I'm trying to trigger eight different 5 V relays using an Arduino Atmega 2560. The relays (70Ω coil) are powered by an external 5 V source, and I'm trying to trigger them through a driving stage which contains for each relay an NPN transistor (2N3904) and a 1 kΩ resistor directly connected to digital pin of the Arduino.
The relays in my application are supposed to be driven 2 by 2, not all of them at once.
My problem is that I don't succeed in triggering the relay with digital pins of my Arduino; once I connect it to the resistor, the voltage of the digital pins drops from 5 V to 0.4 V or less. The transistor needs only 7 mA to be triggered, the output current of the Atmega2560 pins is 20 mA max.
I tried with an external 5 V source, it triggers correctly showing 10 mA maximum of current through the driving stage.

I'm not sure I've followed everything, but I feel like I have to ask: how sure are you that your 1K resistor is really 1K?

@timemage it is 1kohms i did the conception.

A base resistor of 1kOhm at 5V will give you a max base current of 5V/1kOhm = 5mA, which is less than 7mA. That could prevent the transistor from working correctly (as you wrote, that it needs 7mA). have you tried with about 500Ohm? That would give you 10mA. Does the pin correctly output 5V, when nothing is connected to it?

Please show a schematic.

@chrisl i tried 500Ohms does not work either. the test i did with my 5V external source was with an 500Ohms, i got 10mA flowing through the resistance and the relay trigered. I did the test with 1kOhms i got 7mA.
Yes i have 5V ouput when nothing is connected.

Are you setting the pin to OUTPUT? You could be "activating" the pin with the internal pullup resistor otherwise, which would exhibit the symptoms you describe.

@Majenko yes i'm setting the pin to output and sending a digitalwrite high.

Without showing us your schematic (edit the question), you problem is not really understandable. e.g. do you set the resistor direct in series to the relay or did you add it to the base of the NPN transistor. You said the relay sees only 0.4 volt if the resistor is in place. That sounds like you have the following connections:  emiter of the transistor -->  resistor --> relay. That does not work.

@PeterPaulKiefer i just added a schematic in my post please look at it.

What is the value of the base resistor?  It looks like "16 Ohms".

There's a little arrow missing in your transistor.

@jwh20 the base resistor is 1k.

@ocrdu yes its an npn transistor

Yes, I know. There's still a little arrow missing, though. They aren't symmetrical.

@ocrdu yes you are right, but what information you need by this arrow ?

To see where you (think you) connected the emitter. Apart from that, it is missing and should be there in your drawing; it's that simple. Also, what isn't shown: is the ground connected to the ground of the Arduino? What is providing the 5V?

@ocrdu yes the ground is connected to the ground of arduino, and the 5V that is above is provided by an external power supply through a LM7805. the 5V connected to the resistor is provided by the arduino but the problem is that when i connect that 5V to the resistor, the 5V collaps. I made sure i have no short circuit.

You said: "the test i did with my 5V external source was with an 500Ohms, i got 10mA flowing through the resistance and the relay trigered. I did the test with 1kOhms i got 7mA." With 1kΩ and 7mA, 7V would drop across the resistor, plus about 0.7V BE drop, makes 7.7V. Where does that come from?

There is a very important information you gave in the last comment. You use a 7805 to stabilize the input voltage. In order the 7805 can work correct, it's input voltage must be at least about 7.5 Volt. How many volts does you power supply deliver?  That could be the problem. Also,  the Gounds of the arduino, the power supply, the 7805 and the cold end of the relay must be connected. They must all be on the same voltage level. And the little arrow of the transistor should be directed to the GND.

Your circuit will no longer work. The original transistor you used was a NPN, you have changed it to a PNP connected somehow as a low side driver.  It is important to show the emitter, as it tells us what type of transistor it is, leaving it out as you have done causes many of us to assume you have done it correctly ie the emitter is connected to the ground.  Here is a Copy of a circuit from electronics-tutorials that uses a simple MOSFET: https://www.electronics-tutorials.ws/blog/relay-switch-circuit.html Note the 10K resistor from the port pin to ground, that guarantees it will be off during reset and setup.

If the coil is 70 ohms and it's driven by 5V, it should draw about 5/70 = 71 mA.  That's pushing the 2n3904 a bit hard, and doesn't even account for inductive effects. (It's a small-signal transistor.)  Do you have an NPN power transistor to try, just as a test?  If its current gain (beta) is too low, use a Darlington configuration by combining it with your 2n3904.  (2n3904 base from digital out resistor, emitter drives power NPN base directly, both collectors are connected together to the bottom of the coil, and the power NPN emitter is the effective emitter of the just-created "super transistor" with high beta and power handling.)  Be sure to use an anti-kickback rectifier (1n4001)across the relay coil.

sorry i did a mistake, its actually a 5V relay, it means 71mA through the relay. taking in account the 2N3904 gain i would have arround 7mA through the transistor this is why im using a 1k resistor.

Just to be sure:  The relay coil must be between +5 and the collector, with the emitter grounded.

yes i just added a schematic please look at it.

Good Job, you are right on, the transistor is rated at 200 mA which is adequate for the job. The flyback diode will protect your system and the transistor. the drain source drop would be maybe 0.01V on a bad day depending on the RDSon. You will probably need a little lower value base resistor depending on the gain of your transistor.  I would use something between 220 and 510 ohm. It should work fine. Using a darlington would hurt you instead of the ~.7 volts drop across the collector it would become about 1.4 volts, leaving the relay with 3.6V assuming you are actually getting 5V. My preference would be a small logic level avalanche rated MOSFET. Use a 50 Ohm resistor in the gate circuit and it will be just fine.   Use something like a 10K pull down resistor between the gate and source, that will guarantee that it will be off during reset.

Why do you need any gate resistor at all with a MOSFET? They have capacitive inputs, and draw almost no current.

When the gate pulse starts, the capacitive input will appear as a short to the output pin (for a few nanoseconds). The gate resistor limits the current at that time. There is a lengthy discussion about this on the Arduino Forum which you might find interesting.

To prevent oscillation, it does not happen on all circuits but a good design practice. This happens because of the miller capacitance effect during the time the channel in enhancing.

source: Stack Exchange

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

sort: votes


text:
How to use millis() in my code instead of delay()?
I'm having issues trying to convert my code to non-blocking.
I was able to do so in some parts, but the rest aren't the same.
When I try to replace delay with an if statement like the spinning and sensors debounce it doesn't work at the right time, because the variable I subtract from cur_ms is not updated.
What I'm trying to do is to always switch_dir() and update_code(), and when second_btn.released() I want the other two functions to keep running but also to run a sequence of actions (those with the delay) without blocking.
I would love to get your help.
Thanks in advance :)
void loop()
{
    uint32_t cur_ms = millis();

    if (cur_ms - spin_ms >= SPINNING_MS) {
        switch_dir();
        spin_ms = cur_ms;
    }

    if (cur_ms - read_ms >= SENSORS_DEBOUNCE_MS) {
        update_code(get_sensors_state());
        read_ms = cur_ms;
    }

    if (second_btn.released()) {
        ball_servo.write(BALL_SERVO_MAX);   // drop the ball
        digitalWrite(BLOWER_PIN, LOW);  // blower on
        delay(BALL_DOOR_MS);
        ball_servo.write(BALL_SERVO_MIN);   // close ball door
        delay(BLOWER_MS);
        digitalWrite(BLOWER_PIN, HIGH); // blower off
    }
}

if (second_btn.released()) { should only run the first two commands, store ball_door_ms and set a state variable, for example state = 2........ new if statement if (state == 2 and cur_ms - ball_door_ms >= BALL_DOOR_MS) { would close ball door, store blower-ms and set state = 3 .... an so on

You had the right idea with your first few if statements! Just keep checking if time has passed, don't delay()
uint32_t releasedTime = 0;
if (second_btn.released() && releasedTime == 0) {
    releasedTime = cur_ms; // remember that the button was pressed now
    ball_servo.write(BALL_SERVO_MAX);   // drop the ball
    digitalWrite(BLOWER_PIN, LOW);  // blower on
} else if ((cur_ms - releasedTime > BALL_DOOR_MS) && (cur_ms - releasedTime < BALL_DOOR_MS + BLOWER_MS)) {
    ball_servo.write(BALL_SERVO_MIN);   // close ball door
} else {
    // must be after BALL_DOOR_MS + BLOWER_MS, time to run
    digitalWrite(BLOWER_PIN, HIGH); // blower off
    releasedTime = 0; // so this doesn't keep running
}

Re “releasedTime = 0; // so this doesn't keep running”: this won't work as promised by the comment. The line above (digitalWrite(BLOWER_PIN, HIGH);) will run over and over in the idle state. You would have to condition on if (releasedTime != 0) in order to avoid that, but note that 0 is a perfectly valid timestamp periodically returned by millis(). Also, the line ball_servo.write(BALL_SERVO_MIN); will run repeatedly during BLOWER_MS ms. May not be a big deal, but it slows down other tasks in the loop(). Both issues would be solved by using a proper “state” variable.

When second_btn.released is true, its two delay() statements will block the whole loop.  You can avoid this by rewriting so that the delay() statements are handled like you already handle spin_ms and cur_ms, which will involve some state-machine-type logic so that (for example) you set a state when you enter the BALL_DOOR_MS delay, then return to the main loop which will have a branch that is taken only if the BALL_DOOR_MS state is active.  When that state ends it sets a new state that enables a separate branch of the main loop to do the BALL_SERVO_MIN and start the BLOWER_MS state, and so on.  A switch/case chain may be
the best way to handle this, replacing the present second_btn.released.

This link might be helpful: The Finite State Machine.

Switch-case will block the rest of the loop, isn't it?
Could you write a code sample to showcase your idea?

The link was very helpful. It works. Thank you very much :)

<To design in the millis() function, you have to think of it like using a stop watch. You record a time at which you started. Let's say you started at 10000mS. Then every so often, you check the current time. Let's say the current time is 10500mS. You then take the current time and subtract it by your start time to get the time elapsed since you started. This gives you 500mS. Let's say you're desired delay time is 1000mS. Since the elapsed time isn't 1000mS you keep doing other things until the Current time - Start time is greater than or equal to your delay time. Then you do what ever task you need to do, and then record a new start time and do the process all over again. It would look something like this.>
#define DELAY_TIME     1000   // the amount of time you want to delay `

unsigned long startTime = 0;
unsigned long currentTime = 0;

void setup()
{
   startTime = millis();  // Record starting time
   currentTime = startTime; // Set current time to start time so elapsed time would = 0
}

void loop()

{

currentTime = millis(); // update the current time value

if((currentTime - startTime) >= DELAY_TIME)) // check amount of time elapsed
  {
    // The amount of delay time has elapsed
    // Do what ever you need to do here that requires the delay

       startTime = millis(); // Reset the start time so that it waits another 1000ms
       currentTime = startTime; // Set the current time = to start time to avoid negatives
    }
  // Then put the rest of the code that you want to run continuously here

}

What you advise here is exactly what the OP is already doing. He knows how to do this. His issue is about combining this technique with a state machine for handling the ball door and blower.

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


text:
Arduino Library to make http post request with bearer authentication
I want to make an Http Post request with Bearer Authentication to my api using my Arduino Mkr Wifi 1010, but I couldn't find the appropriate library to do something like this (code generated with one made with Postman):
    POST /api/v1/rilevamento/transaction/commit HTTP/1.1
Host: www.....:8082
Authorization: Bearer eyJhb.......
Content-Type: application/json
Content-Length: 233

{
    "id": 0,
    "dispositivo": "sesto",
    "nomeutente": "MyName",
    "cognomeutente": "MySurname",
    "mailutente": "name@email.it",
    "data": "2020-11-23T09:23:03.142+00:00",
    "temperatura": 37.5
}

Can you tell me where to find this library? I tried WifiNiNa httpClient, ArduinoHttpClient, HTTPClient and other but I couldn't  get any response or even enter in the method of my api on debug.

The "Authorization" is simply an HTTP header.  So add it in your request like:
http.addHeader("Authorization", token);

The value of "token" is just the string "Bearer " followed by your authorization string.  Don't neglect the SPACE after the word "Bearer".  It will look like:

"Bearer eyJhb......"

On the Arduino MKR WiFi 1010 you use the WiFiNINA library which is slightly different.  Here is some example code:
  if (client.connect(server, 80)) {
    client.println("POST /test/post.php HTTP/1.1");
    client.println("Host: www.targetserver.com");
    client.println(authorizationHeader);
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(postData.length());
    client.println();
    client.print(postData);
  }

The variable authorizationHeader will have the "Authorization: Bearer xxxxx...." authorization string.
Or you can replace the client.println(authorizationHeader); by:
client.print("Authorization: Bearer ");
client.print(token);

to avoid dealing with concatenations, etc.
client can be an instance of WiFiSSLClient which works with both WiFi101 and WiFiNINA.

I believe this is made with HTTPClient which is for ESP modules, can I use it with my MKR Wifi?

With the MKR WiFi 1010 you use the WiFiNINA library which is slightly different.  I've updated my answer with the relevant details.


text:
How to use HM-10 as client, and send messages to specific services/characteristics?
I have been messing around with this module, unfortunately i bought a fake one, but got the original firmware running inside it (V550).
So far i can set the HM-10 up as client/master and by using an peripheral emulator on Android, i set up a peripheral as my server/slave
The peripheral is able to write to its own characteristic and it sends a notification to the client HM10 that fetches this value and displays it correctly on my serial reader (cutecom and arduino serial monitor)
After this, i'd like to write to the peripheral's characteristic, but i can't find any information about this, but it should be in the realm of possibility, i think.
I am using the Arduino IDE to interface with the HM-10 module.
Any information pointing in the right direction is very, very welcomed. Its driving me crazy now...

You can upgrade the firmware to V709 available on the manufacture's website and find instructions on how to update it. You'll need a USB to TTL converter or something that can act as one.
With firmware V709 you can use AT+FINDSERVICES? and AT+FINDALLCHARS? command to get the list of services and characteristics on the server and then read, write, notify, etc, on the characteristic you are interested in. It is outlined in the datasheet. They call it self learn function and there's a document outlining how to use it.


text:
Why does my 23,032 byte Arduino sketch take 36.32 sec to upload via ISP to an Atmega328p on a breadboard w/code verification disabled?
"Sketch uses 23032 bytes (71%) of program storage space. Maximum is 32256 bytes.
Global variables use 1342 bytes (65%) of dynamic memory, leaving 706 bytes for local variables. Maximum is 2048 bytes."
I have "verify code after upload" disabled. With this enabled, it takes an additional 20 sec to upload for a total of 56 sec.
Using Sparkfun's avr programmer with USBtinyISP, win 10, arduino ide, minicore library. Code is utilizing several libraries from Mozzi. External 16mhz crystal. Have set fuse bits on the chip to use the external clock using the following command: "avrdude -c usbtiny-p m328p -U lfuse:w:0xFF:m"
Seems like it should be faster if truly uploading at 115200 bits / sec. But maybe I'm missing something in how this works.
Thanks !!

ISP programmers typically default to low ISP clock rates.  Often something like 10khz, sometimes slower, probably to just work by default with very slowly clocked AVR chips.  The ISP clock rate must be about one eigth that of the AVR's clock.  For example, by defaulting to a low rate like 10Khz, the programmer will successfully communicate with an AVR clocked at 125KHz with some margin.   Around 4 KHz would work with a 32.768 KHz watch crystal.
Look in avrdude documentation for the -B option.  Note uppercase 'B', this is the option for changing the ISP speed, not lowercase -b which is for the PC to programmer (or bootloader) baud rate.   Not all programmers support -B, but many do.
UPDATE
Well, I dug around the USBtinyISP code and in avrdude and it looks like the default value for -B is 10.  So 10uS.  The way this value is used in the USBtinyISP code is for high or low period, rather than total clock period.  So it's about 20uS per bit, or 50kHz.  If that's your rate, then the plain clocking of the SPI data only accounts for about 3.7 seconds.  So that does cast doubt on this idea.
But, it still may be worth double checking that it is operating with the value 10 and not something larger.  Just to put this in perspective: the maximum -B value is apparently 250, which would result in 2kHz ISP clock rate and about a minute and a half to clock out your roughly 23 KByte.
More findings: Per byte SPI overhead
Each byte of the flash pages is being delivered into the ISP interface by way of 4-byte long SPI commands.  The firmware for the programmer has the following code in it for writing a page in its spi/main.c file where you can see it calling spi( cmd, res, 4 ) :
extern  void    usb_out ( byte_t* data, byte_t len )
{
    byte_t  i;
    uint_t  usec;
    byte_t  r;

    for ( i = 0; i < len; i++ )
    {
        cmd[3] = data[i];
        spi_rw();
        cmd[0] ^= 0x60; // turn write into read
        for ( usec = 0; usec < timeout; usec += 32 * sck_period )
        {   // when timeout > 0, poll until byte is written
          spi( cmd, res, 4 );
            r = res[3];
            if  ( r == cmd[3] && r != poll1 && r != poll2 )
            {
                break;
            }
        }
    }
}

This code is used to deliver data to the flash page buffer during ISP programming.
You can see a comment in avrdude's code explaining that each byte becomes a 4-byte SPI transaction as an aid to explaining their calculation for a communications timeout with the programmer.  The following is in avrdude's usbtiny.c file for the usbtiny_paged_write function.
if (usb_out(pgm,
            function,       // Flash or EEPROM
            delay,          // How much to wait between each byte
            addr,           // Address in memory
            m->buf + addr,  // Pointer to data
            chunk,          // Number of bytes to write
            32 * PDATA(pgm)->sck_period + delay  // each byte gets turned into a
                                 // 4-byte SPI cmd  usb_out() multiplies
                                 // this per byte. Then add the cmd-delay
            ) < 0) {
  return -1;
}

To be clear, these two functions have the same name but are in fact two different functions; the former running in the programmer the later is running in avrdude.
So there is in fact substantial SPI transaction overhead in just delivering data into the page buffer.  Beyond that there's a second USB and SPI transaction to commit the page buffer to flash.

Great info, thank you. I looked into my output and found:
"avrdude: Using SCK period of 10 usec"
So it appears to be set to the default of 10uS.

I went into the avrdude.conf file and changed the "default_bitclock" value to 1. Code now uploads in 10 seconds and executes fine on the chip.
This is a 66% improvement but still seems like it ought to upload faster based on the math.

Or.... maybe this is about right. If we're estimating about 3.5 seconds of spi data and the bitclock is set to pause for 2uS for each bit ... if each bit took about 1uS to write wouldn't that approximately triple the total time it takes? Although I have no idea how much time it actually is taking to write one bit...

@codyblanchard, see expanded findings.   The "the plain clocking of the SPI data" probably should have been written to say "of the program data".  What I was trying to do (and probably failing at) was being conservative in saying rough 3.7 seconds for the irreducible (barring compression) SPI timing associated with program data itself.  Beyond what I've just mentioned in the update, I'm sure there are more delays.  Though they'll probably be diminishing returns.

I have a description of the uploading process which, if you extrapolate out from the 1082 bytes being uploaded in about 0.15 seconds (plus some overhead) should mean that you would get 23032 bytes uploaded in 23032 / 1082 * 0.15 seconds, namely about 3 seconds, including verification.
The fact that you are not achieving that would suggest (as Gil mentioned in their answer) that there is a problem with your PC actually sending data that fast down the USB port.
If you were to hook up a logic analyzer and watch what actually arrives, then you might find that there are bigger gaps between bytes (or batches of bytes) than you would expect.

It sounds like the bandwidth is limited. I have no idea how much delay the ISP is adding but it has to add some. The best would be via the USB at 115200 baud or faster if you can get it.


text:
How do I use a photoresistor?
I found this project and it seemed simple but now I don’t know. Please help. I tried changing the code and the wires but nothing happened.
int photoSensorPin = A0;
int redLedPin = 3;
int greenLedPin = 5;
int blueLedPin = 6;
int redLedVal = 0;
int greenLedVal = 0;
int blueLedVal = 0;
boolean isLedOn = false;

int brightness = 1023;
int darkThreshold = 50;
int changeColorTime = 900000;

long lastUpdate=0;

void setup()
{
    randomSeed(analogRead(1));
}

void loop()
{
    getBrightness();
    if (brightness < darkThreshold) {
        if (!isLedOn) {
            LedOn();
            isLedOn = true;
            lastUpdate = millis();
        } else if (millis() > lastUpdate + changeColorTime) {
            LedOn();
            isLedOn = true;
            lastUpdate = millis();
        }
    } else {
        LedOff();
        isLedOn = false;
    }
    delay(1000);
}

int getBrightness()
{
    brightness = analogRead(photoSensorPin);
    return brightness;
}

void LedOn()
{
    redLedVal = random(1,128);
    greenLedVal = random(1,128);
    blueLedVal = random(1,128);

    analogWrite(redLedPin,redLedVal);
    analogWrite(greenLedPin,greenLedVal);
    analogWrite(blueLedPin,blueLedVal);
}

void LedOff(){
    analogWrite(redLedPin,0);
    analogWrite(greenLedPin,0);
    analogWrite(blueLedPin,0);
}

1
2
3
4

Welcome to the site. There are some items to be improved about your question: copy your code instead of making screen shots, describe what you expect from your code, and exactly what does not work now.

have you tried outputting the analogread values via serial for various lighting situations, to see the actual measured values?

I fixed your pictures.  But you should delete your code pictures and enter the actual code then changing the format of the code using the "code format" button.

Thanks, and I’ve tried but I’m using my phone and it didn’t work. Plus, there’s a lot of code to paste on it.

Don't post screenshots of code. Copy the code into your question, then select it and use the {} button to format it.

Firstly, instead of screenshots, use the code inserts. Also, your question title is too broad, if you are having a problem list that.

Thank you @EjarisAbu-khdeir for entering you code instead of using pictures of your code.  It make it much easier to read and help you.

You forgot to set set the pins to output mode. In setup(), add:
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);

If that doesn't work, then you will need some debugging. Add also this
to setup():
Serial.begin(9600);

and this to loop():
Serial.println(brightness);

Look at the values printed. Do they vary significantly when the lighting
conditions change? If not, check the wiring of the LDR (it is fine in
your schematic). Do they go below and above darkThreshold? If not,
then change your threshold.

How fast does this project need to be for it to be useful?  A photo resistor can take as much as a second to react to bright to dark conditions.

Photoresistors also exhibit a certain degree of latency between
exposure to light and the subsequent decrease in resistance, usually
around 10 milliseconds. The lag time when going from lit to dark
environments is even greater, often as long as one second. This
property makes them unsuitable for sensing rapidly flashing lights

Consider testing the code by connecting A0 to 5 volts to simulate a bright condition.  Then connect A0 to ground to simulate a dark condition.

I don’t believe that the problem is the code. I’m very certain that it’s wiring. I even added a 2k resistor but I’m not sure how to wire it to the project.

The above answer has nothing to do with the code.  A photo resistor can have a very long on to off time.  How fast do you need to detect an on to off event?   Are you trying to detect a flashing light?  It may not work.  Are you trying to tell the difference between day and night.  That will probably work.

@EjarisAbu-khdeir Your wiring (as shown in the schematic) looks like it should work. If you're debugging the code it's always helpful to put some Serial.print(...) statements in there to see if it's really doing what you intended. Have you tried to output the values that come from the LDR input to see how it reacts to light and what value the threshold should have? You could also print something when your code turns the LEDs on or off (to see if that is really happening when you want it to happen).

Thank you @StarCat for actually trying to answer the question. It’s not the code but the wiring. Here, I’ll add another picture.

Also @StarCat, I tried adding code like that but it just did the same thing, nothing. The photoresistor isn’t connecting to the RGB.

@EjarisAbu-khdeir, to be absolutely clear, I am not commenting on your code at all.  I am just asking how fast you need the electronics to work.  I ask because a photo resistor can not detect fast flashing lights.  A photo resistor can only be used to detect light level changes that take longer then about a second.

@st2000 I need it to function correctly, I don’t care how fast it runs.

@EjarisAbu-khdeir, I hope you are not angry.  And I hope your project works as you want it to.

@st2000 I’m not mad and thank you, I’m just frustrated with this project and I don’t understand how to make it function.

@Edgar Bonet how do you change darkthreshold?

I think Edgar Bonet wanted you to first print out the value you are getting for brightness with the lights on and with the lights off.  Then to change this line "int darkThreshold = 50;"  from 50 to a number in between the value you are getting for brightness when the light are on and for brightness when the lights are off.


text:
SD seems too slow for SMTP
I have asked this question on the arduino forum as well.
I have used SMTP before using client.print (and client.println) but I am now trying to move as much text as I can from RAM to SD (and so I need the <SD.h> library). It does not work and I am thinking it may be because the SMTP server "dies of boredom" as it waits for my Arduino to read from the SD card and write it to the client (server?).
In the code below, I have included what I am trying (it will be uncommented if you copy+paste the code) and what already works (which will be commented when you copy+paste the code, but you can uncomment and comment the other section relatively easily). The text file I have on the SD in the code (commented).
If anyone can think of a workaround, that would be great.
#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>

//-v--- Ethernet -----------
byte MyMac[] = {0xFE, 0xED, 0xBE, 0xEF, 0xFE, 0xED}; // <- The physical address of the machine's network card. Should be unique (no two network cards have the same MAC address)
byte MyIp[] = {1, 1, 1, 1}; // <- This is the not the real IP address, but for the real address I have verified that the static IP works for sending mail
byte Dns[] = {1, 1, 1, 1}; // <- Not the real DNS but I got it once through Serial.println(Ethernet.dnsServerIP()); and I know that it works
byte Gateway[] = {1, 1, 1, 1}; //<- Not real
byte Subnet[] = {1, 1, 1, 1}; //<- Not Real

EthernetClient client ;
//-^--- Ethernet -----------

//-v-- Smtp --------
char ServerChar[] = "blahblah";
//-^-- Smtp --------

//-v--- SD ------
File theFile; String line;
//-^--- SD ------

void setup() {
  Ethernet.begin(MyMac, MyIp, Dns, Gateway, Subnet);
  SD.begin(4);
  bool test = TrySend();
}

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

}

bool TrySend(){

  //*-v---- What I am trying ---
  bool SuccessOrNot;

  if(client.connect(ServerChar, 25)){
    SuccessOrNot = true;
    theFile = SD.open("Smtp.txt");   //Smtp.txt is listed toward the bottom of the code

    if(theFile){
      while(theFile.available()){
        client.write( theFile.read() );
      }
      theFile.close();
    }
  }

  else{ SuccessOrNot = false; }
  return SuccessOrNot;
  //-^---- What I am trying --- */

  /*-v-- The following works if used in place of [What I am trying] ---
  bool SuccessOrNot;

  if(client.connect(ServerChar, 25)){
    SuccessOrNot = true;
    client.println("EHLO ktlan");
    client.println("AUTH LOGIN");
    //-v- Most SMTP servers require verification in the form of base64-encoded username and base64-encoded password. However, since your IP must be whitelisted by the SMTP server, you don't need authentication
    //client.println("ThisIsInBase64"); // Encoded version of 'sender@blah.blah'
    //client.println("ThisIsInBase64"); // Encoded version of the password
    //-^-
    client.println("MAIL FROM:<sender@blah.blah>");
    client.println("RCPT TO:<receiver@blah.blah>");
    client.println("DATA");
    client.println("to:receiver@blah.blah");
    client.println("from:sender@blah.blah");
    client.print("SUBJECT: TRIGGER");
    client.println();
    client.println("The temperature Monitor Triggered.");
    client.println(".");
    client.println("QUIT");
  }
  else{ SuccessOrNot = false; }

  //-^-- The following works if used in place of [What I am trying] ---*/
}

/*-v--- Smtp.txt -------
EHLO ktlan
AUTH LOGIN
MAIL FROM:<sender@blah.blah>
RCPT TO:<receiver@blah.blah>
DATA
to:receiver@blah.blah
from:sender@blah.blah
SUBJECT: TRIGGER

The temperature Monitor Triggered.
.
QUIT

//-^--- Smtp.txt -------*/

// NO NEED for authentication. For many Smtp servers you need:
//client.println("ThisIsInBase64"); // Encoded version of 'sender@blah.blah'
//client.println("ThisIsInBase64"); // Encoded version of the password
// My IP must be whitelisted by the SMTP server, and since it is, I don't need authentication

It would be very useful to also see the SMTP Server side of things (logs), if you have access to it. Also, you do not wait for any replies from the server so there's no way to determine when the server's ready for your next command.

You're reading and writing a byte at a time, which might not be optimal. Try and do that in larger chunks (SD page size if you have enough memory)

Many email servers will refuse to serve to a client that sends EHLO before it's sent its identification banner.

Thank all. Added a "ReadClient()", it works []. Tried readStringUntil(), print line by line, works [], tried not returning bool, works (!?) ... revert back to original code, works []. I say [] because when re-upload the code, email sends, but won't send another when reset-buttoned & won't send if re-uploaded with serial monitor active. Was 1 time in troubleshooting it worked fully & I saw output of client on serial monitor & email each reset. Couldn't replicate. Sorry for unclarity: since I claim unrepeatable results I should post [lengthy] instructions. I'll reinstall & if persists do so.

Try a simpler approach (with some code refactoring)
bool TrySend(){

  if(client.connect(ServerChar, 25)){
    theFile = SD.open("Smtp.txt");

    if(theFile){
      while(theFile.available()){
        client.print(theFile.readStringUntil('\n'));
        client.print('\n');
      }
      theFile.close();
      return true;
    }
  }
  return false;
}

As a side note, you might want to consider some better code structure (e.g. local variables). But I assume this is just a sample/test. Also, the code above assumes the file uses \r\n at the end of each line. If it only has \n, then you can simply use: client.println(theFile.readStringUntil('\n')); (notice the print*ln*).
println sends both \r\n.


text:
Connect 12 V DC sensor to Arduino Uno using TTL RS485
I'm trying to connect an Arduino Uno with a BGT PM2510 sensor (which uses 7-12 V DC) by using a UART TTL to RS485 Two-way Converter.
The only thing I wonder about is: can the sensor damage the MCU?
According to the information on the 12 V sensor, it says:
Output signal: RS485 (Modbus protocol). I did measurements on the A & B ports of that sensor; the multimeter showed 3.3 V.
My question is, can the sensor damage the MCU? I intend to connect the Arduino and sensor as in the diagram below:

You should be fine.
RS-485 does specify signal levels of ±1.5 V to ±5 V, but even so, and even when the sensor would misbehave or when the common mode voltage is low or high, there is still the TTL-to-RS485 converter in the middle that has 5 V TTL logic on the Arduino side.
As long as the TTL-to-RS485 converter is properly connected to the Arduino and working as it should, the Arduino is safe.


text:
CAN bus communication and LCD updation
I am trying to communicate arduino uno with CAN bus using MCP2515 shield.
Data sending and receiving both things are done.
Whatever data received is displayed on LCD.
CAN bus receive is done using interrupt of timer1 and LCD updating using interrupt of timer2.
I think LCD does not get enough time for updating hence garbage data appears on LCD.
So please suggest me solution so that I can get Both CAN communication and LCD updation.
I am posting my code for your reference.
#include <Wire.h>
#include <CAN.h>
#include <Adafruit_ADS1015.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

 Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */

 int timer2_counter;
 int timer1_counter;
 uint16_t adc0;
 uint8_t adch,adcl;
 char receive;
 uint8_t dlc = 0;
 int addr = 0;
 long sensorValue = 0;         // the sensor value
 float rpm;
 uint16_t count = 0;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

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

  // initialize timer1
  noInterrupts();           // disable all interrupts

  //---------------------TIMER_1---------------------------------------//
  TCCR1A = 0;
  TCCR1B = 0;

  //timer1_counter = 64930;   // preload timer 65536-16MHz/256/100Hz   10ms 64911
  //timer1_counter = 64911;   // preload timer 65536-16MHz/256/100Hz
  timer1_counter = 64286;   // preload timer 65536-16MHz/256/50Hz
 // timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
 //timer1_counter = 62411;   // preload timer 65536-16MHz/256/20Hz   100msec

  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

   //Setup Timer2 to fire every 1ms
  TCCR2B = 0x00;        //Disbale Timer2 while we set it up
  TCNT2  = 130;         //Reset Timer Count to 130 out of 255
  TIFR2  = 0x00;        //Timer2 INT Flag Reg: Clear Timer Overflow Flag
  TIMSK2 = 0x01;        //Timer2 INT Reg: Timer2 Overflow Interrupt Enable
  TCCR2A = 0x00;        //Timer2 Control Reg A: Wave Gen Mode normal
  TCCR2B = 0x05;        //Timer2 Control Reg B: Timer Prescaler set to 128

  interrupts();             // enable all interrupts

  Serial.println("CAN Sender");
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("DYNALEC CONTROLS");

  ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  ads.begin();
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }

}

ISR(TIMER2_OVF_vect)
{

  TCNT2 = timer2_counter;   // preload time
  count++;
  if(count >= 20000)
  {
     Serial.println("LCD");
    lcd_write();
    count = 0;
  }
}

ISR(TIMER1_OVF_vect)        // interrupt service routine
{
  TCNT1 = timer1_counter;   // preload time

  if(dlc == 1)
  {
    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);
    dlc = 0;
    CAN.beginExtendedPacket(0x0C00DAEF); //(PGN-0 Priority-3 src Addr- EF Dest Addr-DA)
    CAN.write(0x00);
    CAN.write(adch);
    CAN.write(adcl);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.write(0x00);
    CAN.endPacket();
    Serial.println(" ");
  }
   else{
  CAN.beginExtendedPacket(0x0C00DAEF); //(PGN-0 Priority-3 src Addr- EF Dest Addr-DA)
  CAN.write(0xFF);
  CAN.write(adch);
  CAN.write(adcl);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.write(0xFF);
  CAN.endPacket();
  Serial.println(" ");
  }

}
//------------------------------------while_loop-------------------------------------------//
void loop(void)
{
  //lcd_write();
  read_ads();
  read_can();
  calibration();
}
// ------------------------------lcd_write---------------------------------------------------//
void lcd_write(void)
{
  noInterrupts();

  //Serial.println("LCD");
  lcd.setCursor(0, 1);
  delay(10);
  lcd.print("RPM: ");
  lcd.print(rpm);
  delay(10);
  interrupts();

}
//--------------------------ads_read--------------------------------------------------------//
void read_ads(void)
{
  adc0 = ads.readADC_SingleEnded(0);// 10v = 64255 = 8031.875 max value speed. adjust 10v = 32127 counts.
  adc0 = adc0 * 2;
  sensorValue = adc0 - offset;
  sensorValue = sensorValue * slope;
  sensorValue = sensorValue / 10000;
  Serial.println(sensorValue);
  rpm = sensorValue * 0.125;
  Serial.println("RPM:");
  Serial.println(rpm);

  /*adch = adc0 >> 8;
  adcl = adc0 & 0x00FF;
  Serial.print("AIN0: "); Serial.println(adc0);
  Serial.println(adch);
  Serial.println(adcl);*/
}
//--------------------------------------can_read-----------------------------------------------------//
void read_can(void)
{
   // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr()) {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    } else {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available()) {
        Serial.print(CAN.read(),HEX);
      }
      Serial.println();
    }
    if((CAN.packetDlc() == 3) && (CAN.packetId() == 0x3AEF))
    {
      dlc = 1;
    }

    Serial.println();
  }
}

Interrupts are difficult.  You need to write your code such that you do not share resources or are protecting resources between the normal code and the interrupt code.  I almost always recommend beginners to stay away from interrupts for this reason.  Even seasoned programmers can find them selves in unexpected situations due to interrupts.

To add to that:  There are also things that are not well behaved inside interrupts.  To take one example from your code: Serial.print("packet with id 0x");  If there's not currently enough room in Serial's transmit buffer, it will wait until there is some.  However, the only way room becomes available is if another interrupt runs to take data out of it and put it into the serial peripheral.  But that can't happen while you're currently servicing another interrupt.  As a result, writing to Serial inside an ISR can lock up indefinitely if you fill the transmit buffer.


text:
Connecting Web Server in GoDaddy Hosting
I have a domain. It is hosted by GoDaddy. I need to connect that server and receive some data by executing PHP files.
I am not sure about the components.
Tutorials on internet describes how to control esp8266 from web server which is i do not want.
Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is 'retired'.
So do you recommend any component for this task or should i go with arduino uno wifi?

Have you also searched for something like "esp8266 web request"? Because that is what you would need to do. It doesn't matter, that it is PHP, because that is server side programming. The ESP doesn't execute the PHP site, the server does.

I have a domain.

Congratulations.

It is hosted by GoDaddy.

You have my deepest sympathies.

I need to connect that server and receive some data by executing PHP files.
I am not sure about the components.
Tutorials on internet describes how to control esp8266 from web server which is i do not want.

"Controlling" an ESP8266 from a web server is nothing more than making a request to a web server and responding to something the web server sends back.
If you don't want to respond to what is sent back you don't have to. You just have to make the request. That request can contain whatever you want in the way of data and sensor values.

Also i found arduino uno wifi board/wifi shield but in arduino store, it says: this product is 'retired'.

Yes. It's been replaced with the Arduino WiFi Rev 2, which is a more modern AVR MCU coupled with an ESP32 based WiFi interface.
It's pretty wasteful really, since the WiFi interface is considerably more powerful than the AVR that it's connected to.

So do you recommend any component for this task or should i go with arduino uno wifi?

I'd recommend an ESP32 based board. They're cheap, have direct connection to WiFi, very very powerful, plenty of inbuilt peripherals (unlike the ESP8266), and above all have great software support, examples and tutorials.

Thanks, I decided to buy nodemcu board


text:
Connect 5V relay to ESP32 WROVER B board
I need to use a ESP32 WROVER B based MCU board with a standard (cheap) one-channel 5 V relay (e.g. to switch on a mains-power appliance).
Attempted removal of excess solder around the headers permanently disabled the 5 V power output line from the board (to power a relay or other modules), but other pins functional/board boots up correctly.
So at present, there is only a 3.3 V power source and 3.3 V GPIO pins (and others such as for external microphone and speaker).
I assume it is safe to connect a 3.3 V GPIO from the MCU to IN and external 5 V power source to VCC ad GND of the relay and connect the grounds of the MCU and relay together to complete the circuit.
The relay only needs to switch the appliance on when triggered (for example a lamp) and switch off when triggered again. I have a 3.3 ↔ 5 V bidirectional level shifter, but don't think it is suitable here (unless it can be incorporated directly). An alternative maybe is to use an Arduino Uno to connect with the relay, itself triggered by the ESP32 and more complex circuitry (bearing in mind the ESP32's GPIO is 3.3 V and the Arduino's is 5 V).

Assuming a relay module: check if it is OK to drive it with 3.3 V logic when it is on a 5 V power supply, or show the specs for us to look at.
Driving a relay module with 3.3 V logic is unlikely to harm the ESP32, but it may not drive the relay properly if the relay module expects 5 V logic.
Generally, I would even prefer using an external power supply rather than the 5 V pin on a microcontroller board to power a relay module.
As long as you connect everything as you describe, it should work just fine (if the relay module accepts 3.3 V logic).

These "digital relay" modules are available in 3.3V and 5V versions. Simply buy one of the 3V models. Here is one, for example: https://www.dfrobot.com/product-1572.html


text:
Converting 8 bit binary to a hexadecimal pair as unsigned char
I have a function:
void Epd::SendData(unsigned char data) {
  digitalWrite(dc_pin, HIGH);
  SpiTransfer(data);
}

At the moment I am hardcoding data sent to it by calculating on paper and then writing the result as code, but I want to improve that. For example, I am calling:
SendData(0x03);
SendData(0x1f);

To get those two values (0x03 and 0x1f) I am converting the decimal value of 799 to binary: 1100011111 and then adding 0 at the beginning to make sure my binary result is 16 digits long: 0000 0011 0001 1111. After that, I convert every 4 bits to hexadecimal value and sending them as pairs using the SendData function.
I feel like I am almost there, but I don't know how to convert my result to proper type in order to send it to the SendData function:
void Epd::SendDecAsData(int dec) {
  int binary[16];
  for (int i = 0; i < 16; i++) {
    binary[i] = dec % 2;
    dec = dec / 2;
  }

  int dec1 = binary[15] * 8 + binary[14] * 4 + binary[13] * 2 + binary[12];
  int dec2 = binary[11] * 8 + binary[10] * 4 + binary[9] * 2 + binary[8];
  int dec3 = binary[7] * 8 + binary[6] * 4 + binary[5] * 2 + binary[4];
  int dec4 = binary[3] * 8 + binary[2] * 4 + binary[1] * 2 + binary[0];

  String val1 = "0x" + String(dec1, HEX) + String(dec2, HEX);
  String val2 = "0x" + String(dec3, HEX) + String(dec4, HEX);

  SendData(val1); // error because I'm sending `String` instead of `unsigned char`
  SendData(val2);
}

I need help converting those strings (val1, val2) to the right data type, or even better, optimizing this process to get the final result in the right type with less code/computation (probably avoiding conversion to String).

If I understand you correctly, you want to split a 16-bit int into two unsigned chars and send them. Why the convoluted conversion to hex? Why not use something like SendData(dec >> 8); SendData(dec & 0xff);. It's just binary data, no need to convert.

@StarCat I just got the existing code (e-ink board) and I see they are sending hex value so I assumed I have to do the same. There is a ton of hardcoded SendData that is manually converted from dec to hex (for some reason as two SendData calls of 2 digit hex). So even when I just need to send 0 dec it is sent as SendData(0x00) called twice. I hope that explanation helps

What you are sending with SendData(0x00) is not a hex value. It's just represented in your code text by a hexadecimal value but it is converted to an (unsigned char) binary value during compilation. You can replace all occurences of 0xNN with their decimal value (as long as they're not part of a string) and your program will work exactly the same. Just try it.

799, 0x031f and B0000001100010111 are all stored as the same 16 bit binary number ... the differences are only in the source code for human reading ....  compiled code always deals with 0000001100010111 ... your whole conversion program is a waste of resources ... do what @StarCat suggested in the first comment

Thank you guys. I'll try as soon as I get to the office tomorrow

I am hardcoding data sent to it by calculating on paper and then writing the result as code ... what exactly are you doing here? ... please provide an example of the data involved in the calculation

@jsotola for example 031f is 799 which represents the width of the image I'm adding to the e-ink board. The code I'm using says that it needs to be broken into two separate calls of SendData but I will try the suggestions above. If that works I can delete sooooo much code :D

ok, the image width is hard coded ... if same value is used a lot then define something like width_h and width_l ... otherwise use the code that @StarCat suggested ... the reason that you have to break down 16 bit values is because the data is transmitted in bytes .... check the library, there may be 16 bit transmit function that does it for you

@jsotola there are a lot of images and each one with values (x, y, width, height) and not easily understandable because they are split as those two SendData commands so I wanted to make it easier to add new images and make the existing ones easier to read + delete a lot of code

I can indeed send decimal values instead of hexadecimal (mind blown). The board I'm working with can only take 8 bits of data at once so in order to send 799 decimal I first send 3 and then 31 (3*256 + 31). Knowing this I will manage to drastically clean up the code. I will just write a new method that breaks the decimal value I send as a pair of smaller decimal values. Thank you StarCat and jsotola

As StarCat suggested, I can just send decimal values using the same function SendData I was provided with. Because the e-ink board can only communicate in 8-bit commands I still had to split my decimal value before sending it.
This is the function I used to send decimal data in 8-bit pairs:
void Epd::SendDecAsData(int dec) {
  if (dec == 0) {
    SendData(0);
    SendData(0);
  } else {
    SendData((dec-1) / 256);
    SendData((dec-1) % 256);
  }
}


text:
Communicate from Arudino to computer over 3.5mm port
I'm wondering if it would be somehow possibly to have easy communication with a computer for Arduinos that don't have USB like the pro mini. That would make an easy way of having two-way communication with a computer. The computer could just play or record audio using software written specifically for this purpose. Would something like this require any special circuitry or would it just be a matter of connecting the right wires?

This is exactly how old home computers loaded and saved data to cassette.

@Majenko I guess a good question would be, what standard was used, and if that standard maybe already has an Arduino implementation.

FSK is the most common and easiest to implement. You can transmit just with the tone() function if you time it right...

I didn't read the all page, but it seems it can be achieved, see David Awehr's blog (this one is conected to a android phone instead to a PC tho) and this Hackaday page where they seems to it, but the PC's audio input normally use 44,1kHz or 96kHz, so if you wanna go for the higher Serial speed (let's say just 115200bauds) you should think about it this.

Thanks, those articles will be a point to further my research.


text:
Can anyone help be get readings off of my potentiometer with a push of a button?
Hi I'm trying to get my Arduino Uno code to work with a in a specific way where if I push a button, the Arduino will read the raw potentiometer value once and if I don't push it nothing happens.
https://i.stack.imgur.com/uCHkR.jpg
int switchState = 0
int switchPin = 2
int potPin = A0;

void setup() {
pinMode (potPin, OUTPUT);
pinMode (switchPin, INPUT);
Serial.begin (9600);

}

void loop() {
switchState = digitalRead(2);
if (switchState == High) {
Potval = analogRead(potPin);
Serial.print("potval:");
Serial.Println(Potval);
delay(200);
}

else {
(switchState == LOW);
while (Potval);
}
}

what is your question about the arduino? ... the question in your title is not really related to the arduino, and it has an answer of yes

What should that do: (switchState == LOW); while (Potval);? The first line is doing nothing, since this expression is not inside of any flow control command. The second line will loop forever (blocking the code indefinitely), when Potval is not zero. Doesn't seem fitting to me. Why are you even doing this?

Beware that the Arduino language (C++) is case sensitive: Println is not the same as println, High is not the same as HIGH.

I had a very similar issue an it is that you aren't setting up your button as an INPUT_PULLUP. When you press the button, you are sending 5V or ground through it depending on your circuit. But then it won't reset on release. That is why either you can put a physical resistor as the schematic shows here:

or you can simply change the button initialization to INPUT_PULLUP.

There were several issues with your code:

It would not compile due to some missing semi-colons (lines 1 & 2);
The 'else' clause in your loop() function didn't do anything useful;
If your code didn't get trapped in the loop within the 'else' clause (it probably would!), it would print repeatedly as long as you were NOT pressing the button, since you wired the button to read LOW when pressed (which is perfectly fine, buy your code has to take that into account).
Buttons appear to bounce (electrically) when you press or release them. They don't switch once and stay that way. They switch multiple times before they settle down, due to the rough contact surfaces sliding over one another. The code has to allow for this as well.
An analog pin has to not be set to OUTPUT if you want to read analog with it.

Here is a revised version of your code, compiled and tested. You'll find notations in the comments where I made changes:
int switchState = 0;            // (';' was missing)
int switchPin = 2;          // (';' was missing)
int potPin = A0;
int Potval = 0;             // (this declaration was missing)
bool didPrint = false;      // true if we printed on this button-push
// prevents multi-printing while button stays high

void getSwitch();               // declare the new function

void setup() {
  //  pinMode (potPin, OUTPUT);  // not OUTPUT for analog read
  pinMode (switchPin, INPUT_PULLUP);  // needs pullup or reads may be unreliable
  pinMode (13, OUTPUT); digitalWrite(13, LOW); //DEBUG
  Serial.begin (9600);

}

void loop() {
  getSwitch();
  if (switchState == LOW ) {        // pressed == LOW the way you've wired it

    if (!didPrint) {
      Potval = analogRead(potPin);
      Serial.print("potval:");
      Serial.println(Potval);

      didPrint = true;      // prevent printing again til button has been released
    }
  }
  else if  (switchState == HIGH) {
    didPrint = false;       // printing allowed on next button push
  }
}

void getSwitch() {
  switchState = digitalRead(switchPin);
  delay(30);                // waits for button to settle - may need to tweak this
}


text:
How can I send and receive data from an Arduino MEGA 2560 and Python?
Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. [Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.]
Arduino:
int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received
}

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';

              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    Serial.print(cnt);
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED
                    }
              }

          }
}

Python code:
import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
    print('Hello')
    dat.write(1)
    print('Works')

if (dat == 1) would make more sense since you already converted the character to a corresponding digit

Your problem is that you aren't sending the values from python in bytes. A more reliable way is to send the data in bytes like dat.write(b'1') and then receive it on the Arduino using Serial.readString(). I also had many issues with this and this is the best solution. "https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/#:~:text=The%20easiest%20way%20is%20to,Arduino%20IDE)"
If not, you can use the I2C interface. Just be careful, the logic level if your Python is running on a Raspberry Pi.

try with Firmata, it is a protocol that establishes serial communication between the computer with Arduino. All you have to do is have the Firmata on Arduino Board, and pyFirmata plugin available to talk with Arduino from Python on your machine.


text:
Adafruit Neopixel Individual Addressable LEDs issue - Any and every code make LEDs go "crazy"
Hi everyone I have an issue with getting these LEDs to cooperate.
I'm using a 470ohm resistor on the data port and a capacitor for the power. I complied and uploaded the "strandtest"(I changed the variables NUM_LED & LED_PIN) and this occurs [10s Video: https://drive.google.com/file/d/1xabkHW1xgFo9kh3YnGwIsaS5tSfFCsrb/view?usp=sharing]
This happens to all code in a loop. If I send no signals (aka put an empty pin and run) then the lights that were last on stay lit. If I try to clear the LED nothing happens. If I try to set a specific LED to a specific color/brightness nothing happens.
I'm at my wit's end; help a brother out!
LEDs Used:https://www.amazon.com/gp/product/B00ZHB9M6A/ref=ppx_yo_dt_b_asin_title_o02_s01?ie=UTF8&th=1
AC to DC 5V 5A: https://www.amazon.com/ALITOVE-Converter-5-5x2-1mm-100V-240V-Security/dp/B078RT3ZPS/ref=pd_bxgy_img_2/143-9706163-2199558?_encoding=UTF8&pd_rd_i=B078RT3ZPS&pd_rd_r=4133e781-45a6-4112-a571-c311f45e0720&pd_rd_w=t0bs4&pd_rd_wg=TIEcS&pf_rd_p=f325d01c-4658-4593-be83-3e12ca663f0e&pf_rd_r=PPCEVPJVY8N6XFTY1AD4&psc=1&refRID=PPCEVPJVY8N6XFTY1AD4
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 150

// For led chips like WS2812, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define DATA_PIN 3
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
    // Uncomment/edit one of the following lines for your leds arrangement.
    // ## Clockless types ##
    //FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);  // GRB ordering is assumed
    // FastLED.addLeds<SM16703, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1829, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1812, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1809, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1804, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1803, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS1903B, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS1904, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS2903, DATA_PIN, RGB>(leds, NUM_LEDS);
     //FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<WS2852, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical

  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical

    // FastLED.addLeds<GS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<SK6812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<SK6822, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<APA106, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<PL9823, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<SK6822, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2813, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<APA104, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2811_400, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<GE8822, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<GW6205, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<GW6205_400, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<LPD1886, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<LPD1886_8BIT, DATA_PIN, RGB>(leds, NUM_LEDS);
    // ## Clocked (SPI) types ##
    // FastLED.addLeds<LPD6803, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2803, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<SM16716, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    // FastLED.addLeds<DOTSTAR, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    // FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    // FastLED.addLeds<SK9822, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

Please also describe with words, what is actually happening and how that doesn't fit your expectations. Not everybody wants to first watch your video and the link might go dead in some time, making the question not understandable. And please share your code. If you used an example code, please link to it. Also exactly describe what you have changed how.

Of course the last LED state stay, when you send no signals. Thats how these LEDs work. They keep their state, until you send them new data or power cycle them. What do you mean with "If I try to clear the LED nothing happens"? Are you trying while the strip is on an unused pin? If not, how and where in the code exactly are you trying to clear it?

Did you connect the ground of the LEDs to the ground of your Arduino? I can't really see from your video but I suspect you did not. BTW it's much better to describe how everything is connected together instead of showing a video in which you really can't see much except for flashing LEDs. A schematic would be even better.

@StarCat I can see a ground connection from the Arduino to the breadboard. If the breadboard's ground is continuous, though, I can't quite tell.

@Alex try this library: https://github.com/FastLED/FastLED instead of the Adafruit Neopixel, the FastLED library is very handy and very powerful, I prefer it over the Neopixel. Just for you to know there are other options.

Ok so i'm using the basic blink example on FastLed library and updated the post to include the code. However, after uploading the LED strip, it's giving the random results again. This time only the first 10 LED are flashing random colors about 1-2 a second, the rest of the LEDs are off.

I attached a new photo of my wiring plan as well as what I actually did (the 5V power supply is out of the photo)

Don't use the Neopixel library. for LEDs that have WS2812B the FastLED is the best option. I also had issues with the LEDs flashing on and off randomly but using this library and then changing the driver to W2812B made it work. Your power supply is plenty strong.


text:
DHT11 not working with LED in arduino
the point of my code is to turn on a LED when the humidity level reaches a certain amount. However it reads the amount of humidity but the LED is not turning on. Why isn't it working??
#include <SimpleDHT.h>

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11;

void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  }

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT11...");

  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  if (humidity > 70 ) {
     digitalWrite(9, HIGH);
  }
  else if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("Sample OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

Can you please share the schematic

why do you expect it to light? ... you set the humidity to zero just before you check if it is above 70

Your code does not work because in fact error statement reads the value of temperature and humidity sensor.
You set the humidity and temperature variables to 0. If statement compares this variables to 70, before actually reading sensor data.
I haven't tested but this should work.
#include <SimpleDHT.h>

int pinDHT11 = 2;
SimpleDHT11 dht11;

void setup()
{
    Serial.begin(9600);
    pinMode(9, OUTPUT);
}

void loop()
{
    // start working...
    Serial.println("=================================");
    Serial.println("Sample DHT11...");

    // read without samples.
    byte temperature = 0;
    byte humidity = 0;

    int err = SimpleDHTErrSuccess;
    if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL))
        != SimpleDHTErrSuccess)
    {
        Serial.print("Read DHT11 failed, err=");
        Serial.println(err);
        delay(1000);
        return;
    }

    Serial.print("Sample OK: ");
    Serial.print((int)temperature);
    Serial.print(" *C, ");
    Serial.print((int)humidity);
    Serial.println(" H");

    if (humidity > 70 )
    {
        Serial.println("Humidity is above 70%");
        digitalWrite(9, HIGH);
    }
    else
    {
        Serial.println("Humidity is below 70%");
    }
    // DHT11 sampling rate is 1HZ.
    delay(1500);
}

hi, unfortuantly this code does not work, but thank you. It delivers me with the error message 'exit status 1
no matching function for call to 'SimpleDHT11::read(byte*, byte*, NULL)'

@Miri, It’s fixed in the answer now by adding DHT11pin to the dht11.read() call. This is very basic troubleshooting and you could have fixed this yourself.


text:
Plotting data from Arduino and using the serial monitor in parallel
I'm very new to the Arduino world so bare with me.
I would like to plot live data that I receive from my arduino. I use the Serial Monitor to read user input, show text, etc.
The only way I found to plot data from the arduino is by printing the data out in the serial monitor
I would rather prefer the data not to be shown in the serial monitor at all (just from a visual standpoint) but I guess there is no way around it.
Anyways, I would like to read and plot the data only when the user makes a specific input into the Serial Monitor.
Let's say the user types in: "start"
now the arduino prints out the values that needs to be plotted.
But every plotting tutorial on plotting with the arduino that I could find always prints out the data right from the start. I want to start the plotting with the specific user input.
I hope I could explain my question well enough.
Thank you in advance for your help.
Luca

What plotting tutorials have you looked at? Have you tried programming a plotting application in processing? Then you should be able to write code, that will implement the mentioned interaction

the title does not match the question ... please correct it

You're right: Unfortunately, you cannot combine the SerialPlotter part of the Arduino IDE with the SerialMonitor tool in parallel. (COM port blocked). Check @chrisl's hint writing a PC application...

You can also use the Serial Plotter in the Arduino IDE. If you use Serial.println(<some number>) and then open the Serial Plotter(Tools-Serial Plotter), you will see a live graph. Based on your baud rate, the update speed will change. It is very powerful.

Is using the Serial Monitor a requirement, or are you just looking for a good way to get and plot the data?  If the latter, you may be interested in the open-source DaqPort sketch. https://www.daqarta.com/dw_rraa.htm  This was created to use the Arduino as a peripheral for data acquisition, as opposed to the more typical case of the Arduino being the central device.  With DaqPort you can program in any language you like on the host computer, and use it to plot data from the Arduino. The Daqarta software package that includes DaqPort has several examples that use Daqarta's macro language to implement a multi-channel chart recorder, high-speed multi-function oscilloscope, timers, signal generator, etc.  You can use these for free, forever, even after Daqarta's 30-day trial ends.  Since Daqarta already has plotting, you may find it simpler to use than rolling your own, perhaps by modifying one of the examples.


text:
Pro micro Wire.endTransmission() does not return
I have an Arduino Pro Micro(blue version) and I'm having trouble using the I2C. To test it, I use the code below and the result is an infinite square wave on SCL and SDA lines and I only get the number 1 on the terminal output. I have pullup resistors on both wires, 2k each.
Since the board uses an ATMEGA32U4, I tried the same code on a bare MCU and the code works as expected. The difference between the two is the bootloader type. The bare PCB is flashed over USB, using the factory bootloader(ATMEGA32U4-AU, QFP44).
By debugging the code, I found out that endTransmission does not return.
Does anyone have an idea, why the I2C is not working as expected on the Pro Micro module?
Thanks!
#include <Wire.h>

void setup() {
  Serial.begin (115200);
  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }
  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  Wire.begin();
}  // end of setup

void loop() {
  byte count = 0;
  for (byte i = 1; i < 120; i++)
  {
    Serial.println(i);
    Wire.beginTransmission (i);
    Wire.endTransmission ();
    delay(10);
  }
}

What do you mean by "infinite square wave"? Does that mean, that both SDA and SCL get continuously pulsed forever, when Wire.endTransmission() blocks?

Yes, and it does not stop. The waveform looks good, signal level is VCC and GND for 1 and 0.

Mhh, strange. Does this also happen, when nothing is connected to the bus?

Yes, it's the same. With and without the pullup resistor.

To be clear, SCL and SDA have nothing at all attached to them but pullup resistors and perhaps your scope?

Yes, that's right.

And nothing is printing on the Serial Monitor? then I guess your microcontroller is broken. Your sketch seems legit to me. And the lines should never just pulse continuously. A common problem is the bus getting stuck, because one line gets stuck at low, but I haven't seen your problem ever. Can you tell us the frequency of the pulses? Just to check

Same thoughts as chrisl.  I suppose I should go a step further and ask: what happens if you have nothing connected to the Pro Micro at all except the USB cable?  No external pullup resistors; the internals that are enabled for Wire.begin() are sufficient for this test.  No scope.  Just the USB cable.  Pro Micro not even attached to a (solderless) breadboard, just the board sitting on something non-conductive.

I just bought a new pro micro and the I2C is working. Maybe the other one is really broken. Strange...
Thanks for the help!

I dunno how useful it would be to anyone, but that seems to technically be the answer for your question.  So you could post it as an answer to your own question.  If you've accepted that it's the answer you can accept it as well, although as I understand it, you'll only be able to do that in a couple of days.

Seems like the module has a defect, since the same code on another board produces the expected output on the I2C lines


text:
switching power sources
I have a small project I am working on that accepts power from either a 5v DC power source or a USB power source.
Now, I know that both of the power sources are effectively 5v. I have measured the power on both with my meter and can see that the USB supply is at 5.4 and the DC supply is at 5.01v.
I would like to be able to build something that switches over to the USB supply when the cable is connected. However, I have never done this before. I have taken a look around on Google already and have read some things about P Channel MosFETs and PowerPath controllers - but I am a little confused as to whether the two incoming voltages I have are suitable for this?
Would someone be able to give me a little advice on this at all?
Cheers,
Rafa

You might get a useful response here, but this sounds like something that would be better asked on http://electronics.stackexchange.com

Just a side note: 5.4V on a USB supply is outside of specs. It should be 5.25V maximum.

Consider copying the Arduino Uno reference design.  This is part of that schematic showing the MOSFET used to turn on / off the USB power when the barrel jack power source is active:

actually, just the part of picture containing mosfet on the left would suffice.

It's more of a personal preference, but I never liked it when someone post a bit of a schematic and a key net name (in this case "+5V") is missing the source of the signal.  That's why when I copied the schematic I included the 5 volt regulator on the right.


text:
Current Sensor ACS712 not changing its value even when connected bulb is lit
My task is to find the amount of current a light bulb uses, with that motive I used ACS712 current sensor of 30A connected all the connections properly as shown in the circuit diagram below

I tried all different codes available to calculate current...
Arduino Code :
void setup(){
    Serial.begin(9600);
}

void loop(){
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
  Serial.println(analogRead(A0));
}

Output

The output remains the same, even when the bulb is still lighting up.
Thank You in advance :)

print the values of rSquaredSum / sampleCount and voltRMS

How much current does your bulb actually use?  Or put differently: what percentage of 30A is that?

@timemage, on the picture it is 230 V / 100 W.  it should make a difference in my experience. but it could be lost in calculation

That is in part what I'm thinking, but also to make sure his expectations are in line with what the sensor will actually do.

do 10 readings at less than 100 ms intervals between readings ... do not do any calculation with the values ... store them in an array ... after the readings are completed, print the values to serial

Try to tell us the different types of code and the tutorials you followed so we can better narrow down the answer.

In a comment about rZero = 511;, you wrote:

For illustrative purposes only - should be measured to calibrate
sensor.

This may well be the cause of your problem. If, instead of 511, the
“zero” of your measurement is around 445, then you end up measuring a
non-existing DC current of about 3.23 A. When you turn on the light
bulb, you add roughly 435 mA (100 W / 230 V) of AC
current. The total RMS current you see is then:
√(3.232 + 0.4352) ≈ 3.26 A
Barely visible at the resolution at which you are printing the result.
And this is assuming you are using a 100 W bulb, as shown in the
diagram. These bulbs are getting hard to come by. If you are using
anything less powerful, you may not see any change in the displayed
value.
As a quick and dirty fix, you may replace 511 by 445. A better
solution would be to compute the quadratic average of the AC part of the
signal alone. In other words, compute:
√(average(current2) − average(current)2)

how did you conclude that the zero is 445? the time between those measurements is more then 100 milliseconds. it could simply catch the same part of the wave

@Juraj: A constant reading yielding 3.23 A must be 511±66, but the values shown in the serial monitor are only consistent with 511−66.


text:
How to connect two arduinos with smartphone wirelessly
I'm working on a project that have two separate setups for Arduino, each Arduino read sensors and send data to smartphone. how to connect two Arduino then send all data to smartphone over Bluetooth?

Do you really want to use bluetooth, or is that just a idea? Should the two Arduinos connected with each other, or just each one with the phone? If the first, should this also be wireless?

Yes I want to use Bluetooth to connect Arduino with the smartphone, I want to use nrf24 module to connect two Arduino and send all data to the smartphone with HC-06 Bluetooth module, but I need a guide for connection and code.

Then please describe, what exactly your problem is. There are lots of tutorials about these on the web, so we need to know, how you can help you better, than they can.

The internet is full of information, mate. If you have a precise question we may help you with more acuracy


text:
ESP32 with Lolin 2.4 inch TFT Shield Power control
I am running out of intelligence trying to control a Lolin 2.4 Inch TFT shield.
I connected the shield via the official TFT connector to a Lolin D32 Pro. I am using the ILI9341 libary from Adafruit. With the libary it is no porblem controlling the display.
Unfortunately, as soon as I put the esp32 into Deep Sleep, the display goes white but the background illumination stays on.
Does someone know, how I can trun off the background illumination?
As far as I understood, the background light is not controlled via the ILI9341. Instead I tried putting the GPIO32 on Low, since accoring to the schema of the Lolin TFT cable it is responsible for the TFT_Led
Unfortunately that does not work either

forget about sleep for now ... focus on IO32 ... set to HIGH, wait a second, set to LOW, wait a second ... see what happens ... also, try to find a datasheet for the Lolin 2.4 Inch TFT shield

i did a search https://duckduckgo.com/?q=Lolin+2.4+Inch+TFT+shield+schematic ... the first hit points to wemos ... hit comes back as "not found" ... examined URL and found a mis-selling ... corrected mis-selling in the URL and got a good webpage that contains a schematic

@jsotola Sorry for not answering earlier. Thanks a lot for your help!

The backlight of this shield is ON as long as there's power on the 3.3V pin, unless you make GPIO 32 an output and pull it low.
In deep sleep, however, GPIO 32 will stop acting as a pulled down output pin but the esp32 keeps its 3.3V output pin powered, so the backlight will switch ON.
You could power the display over a mosfet, controlled by a GPIO.

Thanks for your help! It works now.
If someone else with mediocre coding skills read this question in the future. All you need to do is to put in the setup: pinMode(32, OUTPUT);
and when you want to use the screen put:
digitalWrite(32, HIGH); in front of it and digitalWrite(32, LOW); after it to disable the screen


text:
Timer STM32 #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting
I have installed the library of TimerInterrupt_Generic for ArduinoSTM32 module via Arduino IDE, so i have tried to test the example of library as you can see below:

and i have gotten this error:

TimerInterruptLEDDemo:45:4: error: #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
   #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
    ^
In file included from /home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/examples/STM32/TimerInterruptLEDDemo/TimerInterruptLEDDemo.ino:64:0:
/home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/src/TimerInterrupt_Generic.h:86:4: error: #error Unsupported Board! Please check your Tools->Board setting.
   #error Unsupported Board! Please check your Tools->Board setting.
    ^
exit status 1
#error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.

Also, This question is asked here:
https://github.com/khoih-prog/TimerInterrupt_Generic/issues/2

The Roger Clark's STM32 core  you're using is not currently supported. I don't know in the future if I can add that core into the supported list.
You have to use this Arduino_Core_STM32.
Convert to new core by following the intructions in Getting Started

I have not installed the rogerclarkmelbourne, my STM32 Module is stm32duino, but your suggestion for changing the STM32 board module is working and solved the TimerInterrupt_Generic, problem.


text:
What’s the most stable digital communication protocol for sewable electronics?
I’ve spent the past few days trying researching communication protocols and I have a few issues. With sewable electronics, you need to work with cables with a fairly high resistance that are constantly moving. That means unreliable and noisy communication. Furthermore relying on multiple data lanes increases the needed number of stitches and the chances of failure.
Adafruit Neopixels use a good system that allows them to only use 1 data pin for a large number of individually controlled addressed devices with a total of 3 connections between each device. Disconnecting the devices while in use doesn’t cause them to crash most of the time, and there’s a lot of expandability. Best of all, the circuit design is incredibly simple because most of the hardware is on board the IC. The problem is that the communication type they use seems to be specifically designed for use on those circuits only, and to my knowledge there is no version of the logic circuit that isn’t coupled with the SMD RGB LED component, and even if there was there’s no way to directly adapt it to other components.
I’ve looked into I2C, SPI, UART, FTDI, USB, CAN-bus, and a bit of DMX and I’m still fairly certain none would work. All I need is to exchange bytes of data between two microcontrollers without them constantly crashing. I’m willing to try the most exotic solutions imaginable.

I found this some time ago ... did not test though ... https://www.pjon.org/SoftwareBitBang.php

Neopixel strings are like (well, not unlike) a giant shift register; the data for each LED is clocked in serially; not easily implemented for what you want. Two-wire RS-485 is very robust but requires transceivers and a two-wire bus. There is also differential I2C, which should be robust enough for your purposes, but it requires transceivers like the PCA9615 and twisted-pair connections. You'll notice why I didn't put this as an answer 8-). Maybe a slow connection over Maxim 1-Wire? Not sure if that is robust enough. Maybe the EE people could come up with a solution.

Try this one: https://en.wikipedia.org/wiki/1-Wire

Ya at this point I think my best solution is to build a new library inherited from the stream class based on 1 Wire. Instead of modulating the VCC supply it could just use a third connection to maintain power consistency, then add capacitors everywhere

You will not get reliable communications over intermittent connections.  one wire sounds great but in reality it needs a second wire called ground. If you go to error correction and detection the target has to respond to ACK or NACK the message. I think the best solution is to use better wire for the connections, you can probably hide them on the inside of the clothing.  You might Try some AWG 28 gauge silicone wire.

RS-485 would be the best if you want robust communication it works on differential voltage principle and also with twisted shielded pair of communication wire it provides very high noise immunity that's its very popular in industrial use.
If you want more out of RS485 then you can use RS-422.