text:
Unable to find/connect I2C devices (SHT31 & SGP30)
I have recently purchased an Arduino Nano 33 IOT together with two sensors:

Adafruit SHT31-D (https://learn.adafruit.com/adafruit-sht31-d-temperature-and-humidity-sensor-breakout)
Adafruit SGP30 (https://learn.adafruit.com/adafruit-sgp30-gas-tvoc-eco2-mox-sensor/)

However, so far I have not succeeded in reaching any of these two sensors. For example I connect the SHT31 sensor like this:

+3.3V to Vin
GND to GND
A4 to SDA
A5 to SCL

I have tried the default Adafruit  SHT31-D example without success, the program appears to hang. I have tried a standard I2C scanner but it does not find any devices with the sensor connected. When the sensor is disconnected, it does find two devices (the IMU and something else I guess).
I believe there is something funky going on with the I2C connection of the internal sensors and the external ones but I have no idea how to troubleshoot this issue. I read some stuff about TwoWire (extern TwoWire Wire1; after the #include) but I am having a hard time figuring out if this is what I need and how to implement it.
I found these topics myself:
https://forum.arduino.cc/index.php?topic=639188.0
https://forum.arduino.cc/index.php?topic=658967.0
edit: I haven't had success dealing with these issues so far and I am still looking for some help with my problems!

Did you try to use Arduino Uno (or similar) with these sensors? Nano 33 IOT is a little bit different compare to Uno (and similar) boards. That will verify if your sensors are fine or not.

I had a similar problem, but the fix turned out to be simple. All the tutorials for SHT3x sensors say to connect the VIN to the 3.3V GPIO. I checked using a test meter, the SHT3x was getting voltage but numerous SH3x libraries didn't seem to work, and a couple of I2C sketches also found nothing. So I tried moving the VIN lead to the 5V GPIO pin - it works perfectly. Perhaps my USB connection lacks enough power, or perhaps my SHT3x needs 5V. Either way it
works - happy now !

one can code an I2C sensor (I'm using a SHT31) using custom GPIO ports like so:
//I2C Bus Pins
#define SDA 8
#define SCL 9

#include "Adafruit_SHT31.h"
TwoWire I2Cbus = TwoWire(0);
Adafruit_SHT31 sht31 = Adafruit_SHT31(&I2Cbus);

void setup(){
  Serial.begin(115200);            // USB communication with Serial Monitor
  Serial.print("Starting serial...");

  Serial.print("Starting SHT31...");
  startSHT();
}

 // ********************************************************
 void startSHT(){
  I2Cbus.begin(SDA, SCL, 100000ul);
  if (! sht31.begin(0x44)) { // Set to 0x45 for alternate i2c addr
     Serial.println("Couldn't find SHT31");
while (1)
delay(1);
  }
}

Without a schematic I will take a SWAG" For I2C to work it needs a pull up resistor for SCL another for SDA. Both are open drain/collector outputs neither of which can drive a + (logic 1) on the bus.


text:
Converting the 3.3V PWM signal to 5V PWM signal
I am using ESP32....the max Pwm signal of it is 3.3V...And I have to control two motors speed by TB6612FNG motor driver...when i was using Arduino.. The arduino can send max 5V Pwm signal to the motor drivers PWM pin.. And the motor runs at the exact speed...but now i have to use ESP32..which sends 3.3V and the motors slow down..
So what should I do to convert the ESP32's PWM signal to 5v and according If i change the PWM value at the program..the output will also change similarly as Arduino??
Please help me

Looking at TB6612FNG datasheet i read

Logic supply voltage (VCC) can be in the range of 2.7--5.5VDC

So, if you supply 3.3V to VCC all should be ok, if the motors themselves get enough power (via VM)

source: Stack Exchange

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

sort: votes


text:
ESP 8266 HTTP Client Data is not changing correctly
I'm Trying to control a pin "D1" from HTTP API everything was working fine but when i'm going to change the data from server it's done on the server but on device it's takes so long time almost 20 minutes i also checked the Serial Monitor the data is not updating please help me.
My Device: Node MCU V3,
Here is my code:
/**
   BasicHTTPClient.ino

    Created on: 24.05.2015

*/

#include <Arduino.h>

#include <Arduino_JSON.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClient.h>

ESP8266WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  pinMode(D1, OUTPUT);

  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("Maruf Hasan", "marufhasan");

}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {

    WiFiClient client;

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, "http://marufhasan.net/api/test.txt")) {  // HTTP

      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String response = http.getString();
          //Converting response object;
          Serial.println(response);
          JSONVar myObject = JSON.parse(response);

          if (JSON.typeof(myObject) == "undefined") {
            Serial.println("Parsing input failed!");
          }else{
            if (myObject.hasOwnProperty("status")) {
              String status = (const char*) myObject["status"];

              if(status=="on"){
                    Serial.println("ON");
                    digitalWrite(D1, HIGH);
              }else{
                    Serial.println("OFF");
                    digitalWrite(D1, LOW);
              }

            }
          }
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  }

  delay(5000);
}

Your server has a cache control of 10-min. Cache-Control: max-age=600.

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


text:
How do I put timers by using millis on 3 PIR sensors?
I want to make the PIRs to stay on for about 1 minute. I've found the code that can do so for 1 PIR, but I dont know how to apply the code for 3 PIRs.
Here is the code for 1 PIR with timer using millis:
int ledPin = 8;
int pirPin = 3;

unsigned long piron;
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

int off;
int on;
const int LDR = A0;
int ldrStatus;

unsigned long currentMillis =( millis()/1000 ) / 60;

/////////////////////////////
//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
  }

////////////////////////////
//LOOP
void loop()

{
ldrStatus = analogRead (LDR);
if (ldrStatus <= 700)     // variable reading(ldrStatus) according to ldr
                          // the higher reading(ldrStatus), the dimmer light
                          // the lower the reading(ldrStatus), the brighter light

{
analogRead (pirPin) == off;

Serial.println ("Its SUNNY DAY !!!");
digitalWrite(ledPin, LOW);

}

if (ldrStatus >= 700)
{
Serial.println ("Its DARK already");

    if(digitalRead(pirPin) == HIGH){
       digitalWrite (ledPin, HIGH);
     piron = ( millis()/1000 ) / 60;
  }

  if ((currentMillis - piron) > 1) {
    digitalWrite(ledPin, LOW);

  }

    }
}
`

and here is the code for 3 PIRs without the timer

    int calibrationTime = 10;

int pirPin = 3;
int ledPin = 8;

int pirPin1 = 4;
int ledPin1 = 9;

int pirPin2 = 5;
int ledPin2 = 10;

int ledPin3 = 11;

int off;
int on;
const int LDR = A0;
int ldrStatus;

/////////////////////////////
//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

   pinMode(pirPin1, INPUT);
  pinMode(ledPin1, OUTPUT);
  digitalWrite(pirPin1, LOW);

   pinMode(pirPin2, INPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(pirPin2, LOW);

 pinMode (ledPin3, OUTPUT);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
  }

////////////////////////////
//LOOP
void loop()
{
ldrStatus = analogRead (LDR);
if (ldrStatus <= 700)     // variable reading(ldrStatus) according to ldr
                          // the higher reading(ldrStatus), the dimmer light
                          // the lower the reading(ldrStatus), the brighter light

{
analogRead (pirPin) == off;
analogRead (pirPin1) == off;
analogRead (pirPin2) == off;
Serial.println ("Its SUNNY DAY !!!");
digitalWrite(ledPin, LOW);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
}

if (ldrStatus >= 700)
{
Serial.println ("Its DARK already");
digitalWrite(ledPin3, HIGH);

    if(digitalRead(pirPin) == HIGH && digitalRead(pirPin1)== LOW && digitalRead(pirPin2) == LOW){
      digitalWrite (ledPin, HIGH);
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2,LOW);
    }

    if(digitalRead(pirPin) == LOW && digitalRead(pirPin1)== HIGH && digitalRead(pirPin2) == LOW){
      digitalWrite (ledPin1, HIGH);
      digitalWrite (ledPin, LOW);
      digitalWrite(ledPin2,LOW);

}
   if(digitalRead(pirPin) == LOW && digitalRead(pirPin1)== LOW && digitalRead(pirPin2) == HIGH){
      digitalWrite (ledPin2, HIGH);
      digitalWrite (ledPin1, LOW);
      digitalWrite (ledPin, LOW);

   }

     if(digitalRead(pirPin) == HIGH && digitalRead(pirPin1)== HIGH && digitalRead(pirPin2) == LOW){
    digitalWrite (ledPin1, HIGH);
    digitalWrite (ledPin, HIGH);
    digitalWrite (ledPin2, LOW);

}

     if(digitalRead(pirPin) == HIGH && digitalRead(pirPin1)== LOW && digitalRead(pirPin2) == HIGH){
      digitalWrite (ledPin, HIGH);
      digitalWrite (ledPin2, HIGH);
      digitalWrite (ledPin1, LOW);
     }

     if(digitalRead(pirPin) == LOW && digitalRead(pirPin1)== HIGH && digitalRead(pirPin2) == HIGH){
     digitalWrite (ledPin2, HIGH);
     digitalWrite (ledPin1, HIGH);
     digitalWrite (ledPin, LOW);
     }

    if(digitalRead(pirPin) == HIGH && digitalRead(pirPin1)== HIGH && digitalRead(pirPin2) == HIGH){
      digitalWrite (ledPin2, HIGH);
      digitalWrite (ledPin1, HIGH);
      digitalWrite (ledPin, HIGH);

    }

     if(digitalRead(pirPin) == LOW && digitalRead(pirPin1)== LOW && digitalRead(pirPin2) == LOW){
      digitalWrite (ledPin2, LOW);
      digitalWrite (ledPin1, LOW);
      digitalWrite (ledPin, LOW);
     }

}

}

@jsotola ive try rewriting the first code from `if(digitalRead(pirPin) == HIGH){
digitalWrite (ledPin, HIGH);
piron = ( millis()/1000 ) / 60;
}
if ((currentMillis - piron) > 1) {
digitalWrite(ledPin, LOW);
}   to   digitalWrite (ledPin, digitalRead(pirPin));
piron = ( millis()/1000 ) / 60;
if ((currentMillis - piron) > 1) {
digitalWrite(ledPin, LOW);
}`    but it seems to ignore the timer or am i writing the code wrong

and thanks! now i know i dont need to use if :)

okay, ive tried changing to 50seconds in this code   digitalWrite(ledPin, digitalRead(pirPin));        piron = millis();    currentMillis = millis();   if ((currentMillis - piron) > 50000) {     digitalWrite(ledPin, !digitalRead(pirPin)); startMillis = currentMillis;  but the timer still doesnt work. The led turns off in like 3  seconds....

can you give me an example? sorry for asking too many question...im still new to this.

it means pir on = led on, i want to make the led on by using the pir, and after 1 minute  the led is automatically off

your question still says make the PIRs to stay on for about 1 minute .... please edit the question and delete the comment

This is not a complete answer, but an idea of how to accomplish the task.
I just typed it in without testing the code.
Use arrays to hold variables. That way a loop can be used to service the three sensors and the three LEDs..
for (i = 0; i<3; i++) {
   currentTime = millis();                             // save current millis() value

   if (digitalRead(pirPin[i]) == HIGH) {               // check if PIR is detecting motion
      trigTime[i] = millis();                          // save trigger time
      trig[i]     = true;                              // set a state variable that indicates
   }                                                   //   that a trigger happened

   if (trig[i]) {                                      // if trigger happened
      if (currentTime - trigTime[i] < 50000) {         // is it less than 50 sec since last motion?
         digitalWrite (ledPin[i], HIGH);
      }
      else {
         trig[i] = false;                              // 50 second timer ran out
         digitalWrite (ledPin[i], LOW);
      }
   }
}

thanks a lot!! though i did some changes in that code and put the pirs and leds in different loops. i finally got it. thanks again, i really appreciate it. :D


text:
Combined code and nothing works. Head scratcher for sure
I have spent a little over 2 hours trying to debug this code. All I did was combine a section of code to write to the SD card. Both of the codes work fine on their own. I can't figure this one out. I am hoping fresh eyes can spot the error. I am using a Arduino Nano with a Robot-Deek data logger board. Pin 10 is used for the data logger. I was using a DTH11 but switched to a LM35, both codes worked with LM35.
#include "RTClib.h"
#include <SD.h>
#include <SPI.h>
#define sample 500
#define current_ms millis()
RTC_DS1307 rtc;
File myFile;
int inPin = 0;   //analog in
float val;       //where to store info from inPin reading
int pinRed = A3;  //output of red led
float tempin = A5;  //input of temp sensor
float tempf;     // variable to hold temp in Fahrenheit
float vout;      // variable to hold voltage from sensor
int array1[sample];  //creates an array with number of elements equal to "sample"
unsigned long averaging;  //the program uses this variable to store the sum of each array it makes
int pinCS = 10;   // write to SD card
float last_dht11_reading_ms = 1;
DateTime now = rtc.now();
#define DHT11_SAMPLE_DELAY 500

void setup() {

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  SD.begin();
  pinMode(pinCS, OUTPUT);
  pinMode(tempin, INPUT);
  Serial.println("Volt and Temperature\n\n");
Serial.println("middle the setup loop");
 // SD Card Initialization
  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
    File myFile = SD.open("Datalog.csv",FILE_WRITE);
    if (myFile) {
      myFile.println("Time, Temp, Volt");
      myFile.close();
    }
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}//end "setup()"

void loop() {

  for (int i = 0; i < sample; i++) {         //this code tells the program to fill each element in the array we made with
    array1[i] = analogRead(inPin);           //information from the antenna wire coming out of the Arduino
    averaging += array1[i];                  //more information about for loops http://arduino.cc/en/Reference/For
  }                                          //the averaging line is simply saying: add averaging to whatever is in array position i
                                             //averaging += array[i] is the same as averaging = averaging + array[i]

  val = averaging / sample;                  //here the program takes the sum of all numbers in array1, and divides by the number of elements "sample"
  val = constrain(val, 0, 100);              //this constrains the variable value to between two numbers 0 and 100
  val = map(val, 0, 100, 0, 255);           //for more information about constrain http://arduino.cc/en/Reference/Constrain
  analogWrite(pinRed, val*20);                  //the map statement tells the program to map out 0-100 to 0-255
  averaging = 0;                                 //this line of code sets averaging back to zero so it can be used again
Serial.println("past the emf loop");

  if ( (current_ms - last_dht11_reading_ms) > DHT11_SAMPLE_DELAY ) {
    vout = analogRead(tempin);                //read LM35 output
    float mv = (vout/1024)*5000;              // conversion to mV
    float celc = mv/10;                       // convert to C
    float tempf = ((celc*9)/5 + 32)/10;       // convert to F
    myFile = SD.open("Datalog.csv", FILE_WRITE);      //open datalog file on SD card

  if (myFile) {                              //write to the SD card time, tempf and val
    myFile.print(now.hour());
    myFile.print(":");
    myFile.print(now.minute());
    myFile.print(":");
    myFile.print(now.second());
    myFile.print(",");
    myFile.print(tempf);
    myFile.print(",");
    myFile.println(val);
    myFile.close(); // close the file;    // close the file
    last_dht11_reading_ms = current_ms;
  }
Serial.println("past the logger loop");
  //delay(1000);//Wait 1 seconds before accessing sensor again.

}
}
// end loop()

What exactly is not working how? Please explain, what you expected and what behavior you actually see

I expect it to write to the SD card and write to the serial monitor. However it is not. I even put in some "markers" to print out to the serial monitor letting me know what part of the code fired off, but they don't print either. The LED does not work. It is like the code is not running.

remove the first SD.begin() and the pinMode for pinCS. add pinCS as parameter of the second SD.begin(). if (SD.begin(pinCS))

Thank you. I made the changes you suggested and still nothing. I run code A, no problem. I run code B, no problem. Run this code, a  combination of the two and I get nothing. No outputs.

DateTime now = rtc.now();
Does not belong above void setup()
4hours to troubleshoot this little mistake.


text:
serial problem with python to arduino
when i execute the python script, the arduino response but the code between the if(Serial.available()) not responding.
python script
 import  time, serial
 arduino = serial.Serial('COM7', 9600)
 time.sleep(2)
 while True:
    arduino.write(str(input("1")))                  # write position to serial port
    # and the pysthon script cant read the code below this line
    reachedPos = str(arduino.readline())            # read serial port for arduino echo
    data.append(reachedPos)
    arduino.close()

arduino script
 #include <Servo.h>
 Servo servo;
 int angle = 0;
 String in;
 int pos = 1;

void setup() {
 servo.attach(7);
 Serial.begin(9600);
 servo.write(0);

}

void loop() {
if(Serial.available())  // if data available in serial port
{
in = Serial.readStringUntil('\n');
Serial.print(in);
pos = in.toInt();
  if(pos == 1){
if(angle == 0){
  servo.write(180);
  delay(10);
  angle = 180;
  delay(1000);
}

if(angle == 180){
  servo.write(0);
  delay(10);
  angle = 0;
  delay(1000);
}}
}
}

What is the problem?
Te arduino code works fine

You're reading up until a \n, but you're never sending a \n - so you end up receiving until a timeout. That consumes everything in the buffer. 2. You then look to see if there's something available. There isn't. You've consumed it all.

i have the same problem when i use Serial.read()

You mean you read everything, and then you look to see if something is available? Of course that will never work. You need to rethink your whole strategy.


text:
arduino cont down timer in minutes with out using delay
i have one code with delay pleas help me remove the delay i will using this code in air cooler with some sensors delay stop working sensors
void startCycle(int cycleTimeInMinutes, const char *type) {
  lcd.clear();
  const char *topRow[1] = { type };
  printTopRow(topRow, 1, 5);

  cool1(true);

  for (int cycleTimeLeft = cycleTimeInMinutes; cycleTimeLeft > 0; cycleTimeLeft--) {
    char buffer[2];
    const char *bottomRow[3] = { itoa(cycleTimeLeft, buffer, 10), "Minutes"};
    printBottomRow(bottomRow, 3, 6);
    delay(60000);
  }
  cool1(false);
}

Check this sketch: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


text:
Why this program works on an old Nano and doesn't work on Nano Every
Can someone tell me why "XTronical graphical Pulse and Oxygen monitor Displays"
https://www.xtronical.com/colour-ecg-monitor/
works perfectly on an old Nano or an Uno and doesn't work on the new Nano Every
even with Registers emulation: "ATMEGA328" ?
Is the Nano Every a "BAD BUY" ?
I very much welcome an explanation.
JFT

you need to explain in detail what you are talking about ... problem descriptions like doesn't work are meaningless

why would it be "bad buy"? because of some incompatible library you try to use?


text:
Programming pic microchip
I have a few pic chips, mainly pic16f72 and pic16f73 on old ups circuits, realized they are not that bad. Their adc capabilities are my point of focus.
I have an esp32 (my first mcu) and i am very disappointed mainly because its adc being crap, I did some research on programming pic chips, some could be programmed via an arduino but my chips were not mentioned anywhere. I wanna program them via my esp32..
Is there a way to program them via arduino (esp32 in my case)? I can build some basic circuits but diy pic programmers require a preprogrammed pic chip which I can't produce if I can't program one already.

In principle you should be able to program every PIC, that works with ISP, over an Arduino. Though I haven't done that myself yet

Can you point me in the right direction? I asked here because i don't know pic[s] and if arduino projects on internet for programming them gonna work with my pics

What exact select criteria for picking pic16F72/73? You mentioned esp32 ADC(which is 12-bit) bad performance so you drop it and pick two MCUs that only offer 8-bit resolution ADC? Getting an Arduino Nano or Uno will give you at least 10bit ADC. If you said ESP32 ADC is a crap because of its non-linearity, it can be calibrate with a Look-up table, here is how I did it, it is still noisier than lower-speed MCU, but it is 12-bit ADC, so depend on what you are looking for.

8-bit ADC resolution on Pic16f72 means 5/256=19.5mV/bit resolution. 12-bit ADC resolution on ESP32 means 0.8mV/bit resolution. if whatever you are measuring can tolerant 19.5mV/bit, then the non-linearity and the higher noise on ESP32 is probably doesn't matter much to you anyway.

BTW, you can find all the info about PIC IDE and toolchain at Microchip website

Makes sense, thanks for calculations, my first attempt was trying to use a thermistor for temp readings and i wasn't satisfied and i did calibrate it

Ha, using a thermistor was exactly what I did when I discover the non-linearity problem of ESP32 (I saw 2 degree Celsius differences caused by non-linearity), read my blog

Thats the blog i followed, did you use a capacitor? And should i connect it to 5v or 3.3v?

For PIC32 you need chipKIT.  Not all chips are supported, but most of the PIC32MX and PIC32MZ chips are. Which exact PIC32 chip(s) do you have?
You will need to install a bootloader, for which you will need a programmer. It is possible to build a programmer using an Arduino, though TBH I'd just pick up a cheap PICkit2 clone from China.
As for the 8-bit PICs, no, they can't be programmed like an Arduino, simply because there is no open source C++ compiler available.

It seems, that you are talking about 2 different things:

The programming/burning of the PIC can be done via an Arduino (so you don't need to build a complex PIC programmer circuit). It is irrelevant, what microcontroller type is on the programmer, as long as the programmer speaks ISP (the programming protocol). So even, when your specific PIC is not mentioned at your found sites, it should work nonetheless. The connections are every time the same, though of your specific PIC the used pin functions might be on other pins (consult the datasheet for this).
An Arduino project - meaning the sketch/program, that was written for a normal Arduino, is normally not easily reusable. PICs are different microcontrollers with different hardware, so you need to port those projects to your specific microcontroller, which might involve extensive changes. When you have an Arduino Project, that was directly written for your PIC, then you can reuse it. (Be sure to install the correct core for your PIC in the Arduino IDE)


text:
"Manually" generating a PWM signal
I've been trying, just out of curiosity, to write my own function that generates a PWM signal, just like analogWrite(), and to make it light up an LED. Here's my attempt so far:
const int pin = 3;
int cycle = 2; // analogWrite() outputs a 498 Hz signal, so each cycle has approximately 2ms

int duty = 0.5; // for a 50% duty cycle

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

void loop() {
  digitalWrite(pin,HIGH);
  delay(cycle*duty);
  digitalWrite(pin,LOW);
  delay(cycle*(1-duty));
}

The LED does light up, but very dimly, as shown below:

However, when using analogWrite() with a 50% duty cycle to achieve the same result, the LED shines much brighter:

Is there something wrong with my code, or is there a special reason why more power is dissipated with analogWrite()?

have you tried different values in cycle?

I've just tried that, and indeed the brightness increases as the cycle values get smaller. However, I had to use cycle values as low as 2 microseconds in order to get a brightness comparable to the one provided by analogWrite(). I can't really understand why, though, so I'd really appreciate it if you could provide some clarification. :)

i do not know ... i suspect that the signal waveform is not what you and I expect it to be ... only way to check is to put a scope or a logic analyzer on the output

You need to review your code and also the capabilities of the Arduino UNO.

int declares an integer.  So int duty = 0.5; is going to get rounded to either 0 1.
delay(0); also will not work.  The instruction will simply get skipped. Likely the reason why you get a brighter LED. Try to use delayMicroseconds(); if you need shorter time but the minimum delay you can have is 4 us for Arduino UNO.
If you are using times as short as 2 us, then from the above comment the delayMicroseconds(); function is not going to be sufficient.  Also, you should consider the loop overhead, which will be a few microseconds.

All in all this is not a great method.  If you do want to create your own PWM signals, it is much better to use the hardware timers.  For example this tutorial on the Arduino website.  You should also be able to find posts about hardware timers on Arduino SE.


text:
Is there a way to retrieve signature from the Voice Recognition module? (Elechouse Voice Recognition V3.1)\
As of right now, I'm attempting to build a voice recognition system that will respond to what I say accordingly. I have been scouring as to how to retrieve the signature from the voice recognition module's library.
This is my result:

My arduino code that produced the result is below:
#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"

VR myVR(2,3);

uint8_t record[7];
uint8_t buf[64];

#define onRecord (0)
#define offRecord (1)

void printSignature (uint8_t *buf, int len) {
  int i;
  for(i = 0; i < len; i++) {
    if(buf[i] > 0x19 && buf[i] < 0x7F) {
      Serial.write(buf[i]);
  } else {
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]");
    }
  }
}

void printVR(uint8_t *buf)
{
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");

  Serial.println(buf[2], DEC);
  Serial.println("\t\t");

  Serial.print(buf[2], DEC);
  Serial.print("\t\t");

  if(buf[0] == 0xFF){
    Serial.print("NONE");
  }
  else if(buf[0]&0x80){
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3] >0) {
    printSignature(buf+4, buf[3]);
  }
}

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

  Serial.begin(115200);

  if(myVR.clear() == 0) {
    Serial.println("Recognizer cleared.");
  } else {
    Serial.println("Not find VR Module");
    while(1);
  }

  if(myVR.load((uint8_t)onRecord) >= 0){
    Serial.println("onRecord loaded");
  }

  if(myVR.load((uint8_t)offRecord) >= 0){
    Serial.println("offRecord loaded");
  }
}

void loop() {
  int ret;
  ret = myVR.recognize(buf, 50);

  if(ret > 0) {
    printVR(buf);
  }
}

Any suggestions as to how I'd go in retrieving the signature from this module?
Edit: The module have been trained to recognize my speech saying "two" and is assigned
 the signature 'two'.


text:
Can not receive data from Python code
I want to send 4 float numbers from Python code to an Arduino; I was trying to send it via serial and I have some problems.
here is my Python code:
import time
import serial
import struct

data = serial.Serial('COM6', 9600, timeout=1)
time.sleep(1)

while True:
   a = str(47.256*1000)
   data.write(a.encode())

Here is my Arduino code :
String msg;

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

void loop()
{
  if (Serial.available()) {
    msg = Serial.readString();
  }

  if (msg.toInt()>30){
    digitalWrite(13, 1);
  }
}

end of code
Thanks in advance.
My problem is that it does not work (LED does not turn on while I send data from the Python code in a while loop; when I remove the while and make it send data 1 time it works (LED turns on). Any ideas why this could be happening?

https://www.instructables.com/id/Interface-Python-and-Arduino-with-pySerial/

"I can't do it" is not a good problem description. What exactly is your problem in writing the code? What exactly did you try? Please add this information to the question by editing it

When you say it does not work, what do you mean? Exactly what happens? What is in your init () method? Are you setting up Serial? Are you setting the LED for output? Please submit the entire code.

That while loop in the python code is going to send that number over and over really really fast.  I wonder if you shouldn't slow that down just a little.  Put a sleep call in that while loop.

It would be easier if you used Arduino <--> Python compatible libraries to ensure the communication between the two is robust and reliable. An example of such libraries would be pySerialTransfer and SerialTransfer.h.
pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.
Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.
Example Python Script:
import time
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
    try:
        link = txfer.SerialTransfer('COM17')

        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        while True:
            send_size = 0

            ###################################################################
            # Send a list
            ###################################################################
            list_ = [1, 3]
            list_size = link.tx_obj(list_)
            send_size += list_size

            ###################################################################
            # Send a string
            ###################################################################
            str_ = 'hello'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size

            ###################################################################
            # Send a float
            ###################################################################
            float_ = 5.234
            float_size = link.tx_obj(float_, send_size) - send_size
            send_size += float_size

            ###################################################################
            # Transmit all the data to send in a single packet
            ###################################################################
            link.send(send_size)

            ###################################################################
            # Wait for a response and report any errors while receiving packets
            ###################################################################
            while not link.available():
                if link.status < 0:
                    if link.status == -1:
                        print('ERROR: CRC_ERROR')
                    elif link.status == -2:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == -3:
                        print('ERROR: STOP_BYTE_ERROR')

            ###################################################################
            # Parse response list
            ###################################################################
            rec_list_  = link.rx_obj(obj_type=type(list_),
                                     obj_byte_size=list_size,
                                     list_format='i')

            ###################################################################
            # Parse response string
            ###################################################################
            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=str_size,
                                     start_pos=list_size)

            ###################################################################
            # Parse response float
            ###################################################################
            rec_float_ = link.rx_obj(obj_type=type(float_),
                                     obj_byte_size=float_size,
                                     start_pos=(list_size + str_size))

            ###################################################################
            # Display the received data
            ###################################################################
            print('SENT: {} {} {}'.format(list_, str_, float_))
            print('RCVD: {} {} {}'.format(rec_list_, rec_str_, rec_float_))
            print(' ')

    except KeyboardInterrupt:
        link.close()

    except:
        import traceback
        traceback.print_exc()

        link.close()

Example Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    // send all received data back to Python
    for(uint16_t i=0; i < myTransfer.bytesRead; i++)
      myTransfer.txBuff[i] = myTransfer.rxBuff[i];

    myTransfer.sendData(myTransfer.bytesRead);
  }
}

Note that you can send more than just individual chars with these libraries. It is possible to transfer floats, ints, bytes, arrays, and even structs (or any combination of the like) within your program using the libraries! See the examples in SerialTransfer.h for more info
For theory behind robust serial communication, check out the tutorials Serial Input Basics and Serial Input Advanced.


text:
How to send and receive data from serial using analog pins?
I have L293D shield connected to my arduino UNO and it fills nearly all the digital pins including TX(1) and RX(0) pins.
I know this function, but as far as I know, it works for digital pins.
SoftwareSerial NAME(Rx,Tx);

How can I set 2 analog pins as Tx and Rx? I will use them for HC-06.

The analog pins also have all the functionality of general purpose input/output (GPIO) pins (the same as digital pins 0 - 13). You can just declare it as SoftwareSerial mySerial(A0, A1).

BTW, read the caveats on Arduino Reference when using the analog pins as GPIO.

Is the shield really using all these pins, or is it just covering them up?


text:
the boxservo works contrary to the code
i want to make a uselessbox .i connected the circuit correctly,i  checked every thing several times and every thing is in right place[ based on  descriptions and pattern],but when i turn  it on,the box servo closes the door and then handservo starts to turn off the switch ,the code says:[the boxservo opens the door then handservo starts to turn off the switch,when the switch  is off and handservo returned to its place then boxservo closes the door]but my box works like this(the boxservo closes the door then handservo starts to turn off the switch,when the switch  is off and handservo returned to its place,then boxservo opens the door).what should i do to solve this problem?Useless box wiring and code
this is the code that i have uploaded:
#include <Servo.h>

Servo handServo;
Servo boxServo;

int switchStatus=0, action=1, vot, randNumber=0;
const int ledPin = 13;
const int frontSwitchPin = 2;
const int handServoPin = 5;
const int boxServoPin = 6;

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

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin,HIGH);

  handServo.attach(handServoPin);
  boxServo.attach(boxServoPin);
  handServo.write(180);
  boxServo.write(70);

  //randomSeed(analogRead(0));
}

void loop()
{
  switchStatus = digitalRead(frontSwitchPin);
  //action = random(1,16);

  if (switchStatus == LOW){

    if (action == 1)
    {
      Serial.println("Action 1");
      for (int i = 70; i <= 110; i++)
      {
        boxServo.write(i);
        delay(20);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(20);
      }
      delay(1000);
      handServo.write(26);
      delay(200);
      for (int i = 26; i <=180; i++)
      {
        handServo.write(i);
        delay(20);
      }
      for (int i = 110; i >= 70; i--)
      {
        boxServo.write(i);
        delay(20);
      }
      action++;
    }

    else if (action == 2)
    {
      Serial.println("Action 2");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(550);
      handServo.write(26);
      delay(550);
      handServo.write(180);
      delay(550);
      boxServo.write(70);
      delay(1500);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(3000);
      boxServo.write(70);
      action++;
    }

    else if (action == 3)
    {
      Serial.println("Action 3");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(1000);
      boxServo.write(70);
      delay(2000);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(550);
      handServo.write(180);
      delay(500);
      boxServo.write(70);
      action++;
    }

    else if (action == 4)
    {
      Serial.println("Action 4");
      for (int i = 70; i <= 110; i++)
      {
        boxServo.write(i);
        delay(20);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(20);
      }
      delay(2000);
      handServo.write(26);
      delay(200);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 5)
    {
      Serial.println("Action 5");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(2000);
      handServo.write(65);
      delay(550);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(2000);
      handServo.write(26);
      delay(400);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 6)
    {
      Serial.println("Action 6");
      for (int i = 70; i <110; i++)
      {
        boxServo.write(i);
        delay(20);
      }
      delay(1000);
      for (int i = 0; i < 12; i++)
      {
        for (int j = 70; j <= 110; j++){
          boxServo.write(j);
          delay(6);
        }
        delay(200);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(30);
      }
      handServo.write(26);
      delay(400);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      delay(1500);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(3000);
      boxServo.write(80);
      action++;
    }

    else if (action == 7)
    {
      Serial.println("Action 7");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(400);
      handServo.write(26);
      delay(1000);
      for (int i = 0; i < 6; i++)
      {
        for (int j = 70; j <= 110; j++){
          boxServo.write(j);
          delay(6);
        }
        delay(200);
      }
      delay(500);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 8)
    {
      Serial.println("Action 8");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(2000);
      for (int i = 0; i < 7; i++)
      {
        handServo.write(75);
        delay(100);
        handServo.write(40);
        delay(100);
      }
      delay(500);
      handServo.write(180);
      delay(1000);
      boxServo.write(70);
      action++;
    }

    else if (action == 9)
    {
      Serial.println("Action 9");
      for (int i = 70; i <= 105; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(2000);
      boxServo.write(110);
      for (int i = 180; i >=35; i--)
      {
        handServo.write(i);
        delay(40);
      }
      delay(500);
      handServo.write(26);
      delay(200);
      for (int i = 26; i <=180; i++)
      {
        handServo.write(i);
        delay(40);
      }
      boxServo.write(70);
      delay(2000);
      boxServo.write(100);
      delay(3000);
      boxServo.write(70);
      action++;
    }

    else if (action == 10)
    {
      Serial.println("Action 10");
      for (int i = 70; i <= 105; i++)
      {
        boxServo.write(i);
        delay(100);
      }
      delay(1000);
      for (int i = 0; i < 10; i++)
      {
        for (int j = 70; j <= 100; j++){
          boxServo.write(j);
          delay(6);
      }
        delay(100);
      }
      boxServo.write(110);
      delay(100);
      handServo.write(26);
      delay(650);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 11)
    {
      Serial.println("Action 11");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(2000);
      for (int i = 0; i < 3; i++)
      {
        handServo.write(65);
        delay(200);
        handServo.write(40);
        delay(200);
      }
      delay(1500);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      delay(1500);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(3000);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 12)
    {
      Serial.println("Action 12");
      for (int i = 70; i <= 110; i++)
      {
        boxServo.write(i);
        delay(50);
      }
      delay(1000);
      for (int i = 180; i >= 26; i--)
      {
        handServo.write(i);
        delay(50);
      }
      delay(2000);
      handServo.write(26);
      delay(200);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 13)
    {
      Serial.println("Action 13");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(2000);
      for (int i = 180; i >= 60; i--)
      {
        handServo.write(i);
        delay(40);
      }
      for (int i = 0; i < 3; i++)
      {
        handServo.write(60);
        delay(200);
        handServo.write(40);
        delay(800);
      }
      handServo.write(26);
      delay(2000);
      handServo.write(180);
      delay(500);
      boxServo.write(70);
      action++;
    }

    else if (action == 14)
    {
      Serial.println("Action 14");
      for (int i = 70; i <= 105; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(4000);
      boxServo.write(110);
      handServo.write(26);
      delay(650);
      handServo.write(180);
      delay(500);
      boxServo.write(100);
      delay(4000);
      boxServo.write(70);
      action++;
    }

    else if (action == 15)
    {
      Serial.println("Action 15");
      for (int i = 70; i <= 105; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(1000);
      for (int i = 0; i < 3; i++)
      {
        for (int j = 70; j <= 105; j++){
          boxServo.write(j);
          delay(50);
        }
        for (int j = 105; j >= 70; j--)
        {
          boxServo.write(j);
          delay(50);
        }
      }
      for (int j = 70; j <= 110; j++){
        boxServo.write(j);
        delay(50);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(40);
      }
      delay(1000);
      handServo.write(26);
      delay(400);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action = 1;
    }

  }

}

please edit your post ... convert the wall of words into clear sentences  .....what is the actual problem that the program is exhibiting?

And please point us to the action, that is doing problematic, so that we know, where to search in your long code

you are mistaken about this the boxservo works contrary to the code ...... it should say the boxservo works exactly as programmed

when the switch is off boxservo opens the door and when the switch is on boxservo closes the door that is the problem.it's supposed to open the door when the switch is on and close the door when the switch is off.

If the switch is mounted upside down, then pushing the switch up would close the box; but you need it to open the box instead. In that case, turn the switch so that pushing it up would open the box.

no i didn't mount the switch

and my problem isn;t the switch,my problem is that when the switch is on , boxservo closes the door then handservo comes out to turn off the switch and when the handservo turns the switch off and returns to it's place,boxservo opens the door but it's supposed to boxservo opens the door when the switch is on and then handservo comes out to turn it off and after that handservo turns it off and returns back ,boxservo closes the door

You have probably installed the box servo backwards so that when it tries to open it actually closes and vice versa.

no im sure that it is not bacward

Then you probably have a servo that is wired in reverse. You need to change the code to reverse the door movement servo.

i don't know exactly how to change the code.can you help me to change it?please


text:
Arduino Mega LED doesn't light as expected
I wrote this for my Arduino Mega 2560:
int LED[14] = { 28,29,30,31,32,33,34,35,36,37,38,39,40,41 } ;
...
... (some other code like setup(), etc. Note:pinmode output for this 14 leds wich pins is defined in
... array named LED[]
...
void intro(){
  for(int j=1; j<100; j++ ){
    for(int r=1; r<15; r++ ){ digitalWrite(LED[r],HIGH); delay(100);  }
    delay(100);
    for(int r=1; r<15; r++ ){digitalWrite(LED[r],LOW); delay(100);}
    delay(100);
  }
  Serial.print("Pattern started");
  delay(1000);
}

So when I run this script, I expect that each LED will light up in the sequence and remain lit until the second loop to turn it off, but I see that when lighting each LED, when lighting the 9th LED, the first 8 LEDs shut off inexplicably and LEDs 9 through 14 light one by one, remaining lit. That I expected but why do the first 8 LEDs shut off before the loop ends and the second loop starts?

maybe you are overloading the data pins

for (int r = 0; r < 14; r++). first index is zero and the size of the array is 14

While it is true that your loop is incorrect, the coding error is unlikely to cause the behaviour that you have described.
Please ensure that a current limiting resistor is placed in series with each LED. Since you have 14 LEDs, you will need 14 current limiting resistors. 470 Ohm resistors (or similar) should be adequate for this purpose.
As per the other comments, C++ Arrays start at 0, not 1. The last element is the size of the array minus 1. In your case 14 - 1 = 13. Thus the loop can continue as long as the index is < 14 (or <= 13)
Thus your loops should read:
for(int r=0; r<14; r++ ) {
  digitalWrite(LED[r],HIGH);
  delay(100);
}

your for statements with r=1 need to be changed to r=0;r<14  Arrays always start with the first item being 0, so yours is 0 to 13.

and how does it cause the described behavior of the code?


text:
Problem with I2C
I trying to make a project to write and i2c display from a renault megane vehicle. There is many people showing it but there is no code that i can use.
So i buy a cheap analyzer and i can clearly see what radio says to display.
Now i try to do it with arduino... but there is something wrong... i can just read a sequence of "01000110" thats i think that is begin transmission ... but what i write with "Wire.write" is not sending or something... Im so frustrating ... if anyone can tell me why im not receiving more data than 01000110 will be awesome. I will give 2 screens to let us know more.
This is the sniff from the radio

This is the sniff from my code

As you can see only the 01000110 bits is same for both, but there is no more data...
This is my arduino code
    #include <Wire.h>
int _mrq = 2;
void setup() {
  pinMode(_mrq, OUTPUT);
  digitalWrite(_mrq, HIGH);

  Wire.begin();
  Wire.setClock(7140);
  Wire.beginTransmission(0x23);
  delay(500);
  digitalWrite(_mrq, LOW);
  sendInit(0x01, 0x01);
  digitalWrite(_mrq, HIGH);
  delay(100);
  digitalWrite(_mrq, LOW);
  sendInit(0x01, 0x10);
  digitalWrite(_mrq, HIGH);
  Wire.endTransmission();
}

void loop() {
  delay(500);
  Wire.beginTransmission(0x23);
  digitalWrite(_mrq, LOW);
  sendInit(0x01, 0x01);
  Wire.write(0x0c);
  Wire.write(0x90);
  Wire.write(0x7e);
  Wire.write(0x72);
  Wire.write(0x01);
  Wire.write(0x20);
  Wire.write(0x4c);
  Wire.write(0x4f);
  Wire.write(0x53);
  Wire.write(0x34);
  Wire.write(0x30);
  Wire.write(0x20);
  Wire.write(0x20);
  sendInit(0x01, 0x11);
  digitalWrite(_mrq, HIGH);
  Wire.endTransmission();
  delay(1);
}

void sendInit(int a, int b)
{
  delay(20);
  Wire.write(a);
  delay(100);
  Wire.write(b);
  delay(20);
}

so, what is your question?

The NAK that you're getting is stopping any further communication. Either whatever you're sending to doesn't like what you're sending, or it's wired up wrong.

Please tell us, how everything is wired up. Also: What voltage levels do the Atmega2560 and the I2C display use?

@chrisl I have 3 cables, PIN 2 is MRQ that is a stuff that use radio / display, and pin 20 and 21 (SDA/SCL) display uses 12v but sda/scl is digital and works from 0 to 5.

What is MRQ here? Has it something to do with the display? The delays around Wire.write() are meaningless. This function only puts the data into a buffer. The actual transmission is done only in Wire.endTransmission()

@chrisl nope https://i.gyazo.com/b568257e5489418adaafaaa700c23234.png now i put MRQ to ground before endtransmission and then high again... but sill missing all, only 01000110 is received (again)

Please try to add a delay between outputting ground to MRQ and Wire.endTransmission(). I think the MRQ pin activates the I2C peripheral of the display. It might need some time, before it is ready to answer.

After reading something about I2C i know that i got NACK... so something goes wrong... but in the radio sniff it get ACK so its OK ... maybe the speed is the problem ? https://i.gyazo.com/6c397a8063fce2bb183753653bc100ba.png (radio) https://i.gyazo.com/2b5190053f046b0402271bb6204a8f0c.png (arduino) (i set speed to 7140 (7.14 Khz with Wire.setClock(7140), its ok ?

Only specific values are valid for the frequency. You cannot set it to arbitrary values. At least thats what the documentation says. Have you included the delay before endTransmission?

yep, i added a 500 microseconds after and before endTransmission


text:
Sim900b(chinese sim900a) AT+HTTPACTION=(0/1)reboots the module
I am trying to make an HTTP request in two ways

Connecting sim900 to pc using TTL converter (without external power, only USB power)
Connecting sim900 using Arduino nano (tried with and without external power, with common ground)

in the first case, everything is ok
but in the second case after sending AT+HTTPACTION= the module resets
Arduino sketch
#include <SoftwareSerial.h>
SoftwareSerial sim900(3, 2);

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

void loop() {
  if (sim900.available())
    Serial.write(sim900.read());
  if (Serial.available())
    sim900.write(Serial.read());
}

Serial monitor:
AT

OK
AT+SAPBR=1,1

OK
AT+HTTPINIT

OK
AT+HTTPPARA="URL","http://veterok.xyz:8888/service/time"

OK
AT+HTTPACTION=0

OK
⸮⸮⸮⸮
RDY

+CFUN: 1

+CPIN: READY

Call Ready

how are you powering the sim900?

@jsotola I've updated the question, I tried with external power (5V ~12W) and power from Arduino

Your code SoftwareSerial sim900(3, 2); means D3 is Rx, which means that it should connect to SIM900A's Tx, but your wiring diagram connect to SIM900A's Rx.


text:
Problem with if condition
So my project is including detecting the temperature in the room by using dth11 sensor.
my idea is to add 3 LED lights were each light represent the temperature if its cold or hot or perfect.
the wiring and coding is done and it's working .However, i'm having a problem were the perfect temperature is always on no matter if the temperature is hot or cold.
example: if the temperature is cold the cold LED will blink and the perfect temperature LED will be on.
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHTPIN A0
#define DHTTYPE DHT11
#define LED_TOO_COLD 6
#define LED_PERFECT 8
#define LED_TOO_HOT 7
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  Serial.println("DHT11 test!");

  dht.begin();
}

void loop() {

  pinMode (6 , OUTPUT);
  pinMode (7 , OUTPUT);
  pinMode (8 , OUTPUT);
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
  if (t < 22) {
    Serial.println("Too cold!");
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
    delay (2000);
  }
   if (t >26) {
    Serial.println("Too hot!");
    digitalWrite(7, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(8, LOW);
    delay (2000);

  } else {
    Serial.println("Perfect temperature!");
    digitalWrite(8, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (2000);
  }

}

firstly, move your pinMode() settings to setup section.
in your code, when the temperature is 21 active pin will be 6 and 8.
you should rewrite your code in next ways:
1:
if (t < 22) {
  ... its cold temp ...
} else if (t > 26) {
  ... its hot temp ...
} else {
  ... it's nor temp ...
}

2:
if (t < 22) {
   ... its cold temp ...
}
if (t > 26) {
   ... it's hot temp ...
}
if (t >= 22 && t <= 26) {
   ... it's nor temp ...
}

and my small advice for u, rewrite in this way, it is more readable
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
digitalWrite(8, LOW);

digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, LOW);

digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, HIGH);

visually changing ENUMS (like LOW or HIGH) more noticeable than changing numbers (6/7/8)


text:
LCD write a line at bottom without lcd.setCursor and without deleting any char above already there?
lcd.cursor and lcd.noCursor won't work for what I want to use it for since it seemed to be "global" sort of speak and follow lcd.setCursor which I don't want it to but it is otherwise exactly what I want to be done; just to put a line at the very bottom and also remove the line whenever I want to but without removing the entire char above.
Just like lcd.cursor do but as said it won't work in the code since the line has to reside where it is even if lcd.setCursor is used elsewhere but then the cursor line follow to that other point which I don't want and such a controllable cursor that sits at the place even if lcd.setCursor is used elsewhere. But the char there first and then the line of vice versa doesn't matter just as long as there it a line. And I cant create custom chars with a line under them since its numbers from 0 - 9 and so many custom chars can't be made.
It's fully possible to write to the bottom row though and I thought it would be possible to do something with lcd.createChar by not no write anything at all at the bytes rows but the lowest one, but that surprisingly failed. This is what I tested:
byte line[8] = {

  B,
  B,
  B,
  B,
  B,
  B,
  B,
  B11111,
};

And that writes on the lowest row as expected, but strangely enough STILL deletes any char that is written above even if nothing should have been written there as I see it.
The test here put out pretty much garbage and pretty much delete the char written but something still remain but the line is written at top instead of bottom and I guess it all goes out of the normal bounds in the registry or something:
#include <LiquidCrystal.h>
LiquidCrystal lcd(40, 42, 28, 26, 24, 22);

byte line[1] = {

  B00000,
};

byte noline[1] = {

  B11111,
};

byte sure[8] = {   //It didn't like to use "square" as name by whatever the reason

  B00000,
  B00000,
  B01110,
  B01110,
  B01110,
  B01110,
  B00000,
  B00000,
};

void setup() {

  lcd.createChar(0, line);
  lcd.createChar(1, noline);
  lcd.createChar(2, sure);

  lcd.begin(20, 4);
  lcd:clear:
}

void loop() {

  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(2));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(1));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(0));

}

Any tips on how to do the same with create.Char or any other simple way? I mean the lcd.cursor and lcd.noCursor can do it, how do that do it then? It's an ordinary 20X4 LCD if that would matter.

Often instead of using a cursor you would just blink the character that is currently the "selected" one.

I do not really understand what you mean by your first sentence. Did you succeed in getting a "hardware" cursor to display together with a character or not? And if you do, why doesn't this fulfill your requirements?
You have to realize that your LCD cannot display partial characters, like a line at the bottom, leaving the rest of the character that was already there intact. An exception is a hardware generated cursor.
You also have to realize that createChar always expects a full character with 8 rows.
Your code examples
In your first example, starting with byte line[8] = {, the first 7 "empty" B, lines actually produce a value of (binary) zero. So here you create an empty character with a line at the bottom, exactly like you said you see on the display.
In your second piece of code, you define characters byte line[1] = and byte noline[1] = consisting of just 1 byte. createChar expects 8 bytes. createChar will fill the characters with the single byte defined in your character definition, plus whatever it finds in the 7 memory locations following your actual definition (which will probably contain some random data). This explains the "garbage" you see on the screen.
Possible solution
One solution would be to re-create each character you want your cursor to display under, on the fly. I.e. if you want your cursor to be displayed under the letter "A", you create a complete custom character which contains "A", plus a cursor underneath and you display it in place of the real "A" at this location. When you move the cursor, you replace the "custom" A with the real "A" again.
This will be cumbersome in code complexity as well as code size (you'd have to create a complete character map for every character you wish to display), but should be a feasible solution.


text:
Receive SMS using Arduino Nano and Quectel EC25
I'm trying to use an Arduino Nano to communicate with a Quectel EC25 module from this Raspberry Pi 4G HAT. I'm using Arduino's pins 8 and 7 to communicate with RX and TX from the Quectel module. I'm able to establish communication and send AT commands.
The problem is that when I start to listen for incoming SMS, the available method does not change status, even if an SMS is received. There is the code I using:
#include <SoftwareSerial.h>

#define DEBUG Serial
SoftwareSerial EC25(8,7); // RX, TX - 9600 baud rate

#define AT_RESPONSE_LEN 100
#define TIMEOUT 1000

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

  sendATComm("ATE1","OK\r\n");
  sendATComm("AT","OK\r\n");
  sendATComm("AT+IPR?","OK\r\n");
  sendATComm("AT+CGSN","OK\r\n");

  sendATComm("AT+CNMI=2,1","OK\r\n");
  DEBUG.println("listennig");

}

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

  if (EC25.available()){
    DEBUG.println("Available");
  }

}

// function for sending at command.
const char* sendATComm(const char *command, const char *desired_reponse)
{
  uint32_t timer;
  char response[AT_RESPONSE_LEN]; // module response for AT commands.

  memset(response, 0 , AT_RESPONSE_LEN);
  EC25.flush();

  sendATCommOnce(command);

  timer = millis();
   while(true){
    if(millis()-timer > TIMEOUT){
      sendATCommOnce(command);
      timer = millis();
    }
    char c;
    int i = 0;

    while(EC25.available()){
      c = EC25.read();
      DEBUG.write(c);
      response[i++]=c;
      delay(2);
      }
      if(strstr(response, desired_reponse)){
        return response;
        memset(response, 0 , strlen(response));
        break;
      }
  }
}

// send at comamand to module
void sendATCommOnce(const char *comm)
{
  EC25.print(comm);
  EC25.print("\r");
}

That gives the following output:
ATE1

OK
AT

OK
AT+IPR?

+IPR: 9600

OK
AT+CGSN

860548040717545

OK
AT+CNMI=2,1

OK
listennig

I also tried this example by changing the default RX and TX pins but does not work at all.


text:
How to properly pass struct as argument?
This is my first question! i'm sorry if i'm doing something wrong.
I'm trying to write a code that blinks some leds, but i cant quite work out how to use structs as arguments.
This is the code:
void setup(){
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  //digitalWrite(2,HIGH); //debugging

}

struct Timer {
  unsigned long DutyCycle;
  unsigned long LastTime;
};

void SwitchPin(int pinn, bool ledstate,Timer timer) {
  if (millis() - timer.LastTime >= timer.DutyCycle) {
    if (ledstate == LOW) {
      ledstate = HIGH;
    } else {
      ledstate = LOW;
    }
    digitalWrite(pinn, ledstate);
  }
}

void loop()
{

}

When i try to verify it says:
exit status 1
'Timer' has not been declared

among other rubish.
I'm very new to programming in general, so probably i'm doing something very wrong without noticing it.
I would be very glad if you can explain exactly what im doing wrong, so i know what to do in the future.

BTW (regarding your question) : void SwitchPin(int pinn, bool ledstate, const Timer& timer) were a better signature for your function.

I just tried compiling your code - it compiled with no errors.

i have same problem, what you do for it.


text:
DC Motor doesn't turn and a beep sound is made, also there is a burning smell
I was trying to drive a single dc motor with L293D Shield and Arduino Uno
#include <AFMotor.h>
#include <SoftwareSerial.h>

AF_DCMotor motorLeft(3);
AF_DCMotor motorRight(2);

unsigned char opMode = 0;

void setup()
{

}

void loop()
{
motorLeft.setSpeed(30);
motorLeft.run(FORWARD);
delay(5000);
motorLeft.setSpeed(0);
motorLeft.run(RELEASE);
delay(5000);
}

When I turned the power on, a beep sound was made continously. As I was trying to figure out where the sound comes from, I smelled something burning and turned the power off.
I am giving 6V (Four 1.5V  batteries in series) as external power. Burning smell doesn't come from batteries, that's for sure.
The smell comes from arduino or shield or both. But I think it is the the left LM293D driver.
What did I do wrong? Any idea?

Please show a schematic, or at least a wiring diagram. This doesn't sound like a code problem.

@JRobert The shield is not supported by fritzing so it is a little bit hard for me to create a schematic. But it is pretty simple. 6V is connected to EXT_PWR of the shield (Of course there is a switch in between), and DC motors are wired to M2 and M3. The polarity doesn't matter here as far as I know. There is nothing else. I have checked the polarity of the battery via multimeter. It is correct.

What happens if you power up the system with the motor(s) disconnected? With motor(s) connected but 6v disconnected? You need to partition the system some way until you can narrow down the source of the short-circuit. Obviously, keep the powered-on time as short as you can to limit any (more ):  damage while you're testing.

I did two things: I increased PWM from 30 to 255 and I took the PWRJMP jumper out. Now my card works totally fine. However, now I have to get power from both USB and batteries. Since I am trying to build a robot at the end, it is a problem. I am afraid to try with the PWRJMP on.

Alright, I finally realized that RPM value was too low. It has to be at least 150 for my case.


text:
Lilygo TTGO T-Beam Guru Meditation Error
I have recently purchased a lilygo ttgo t-beam (868Mhz version) on which I try to run the "DeviceInfo" example code provided by TheThingsNetwork. When executing ttn.ShowStatus(); I see in the Serial Monitor an error stating that "core 1 panic'ed" and the device keeps rebooting eternally.
I am new to this but I think I have not missed any steps. I have included the "TheThingsNetwork" library successfully (the sketch compiles when I include it) and I have added some Additional Boards Manager URLs to help Arduino IDE find my board.
So far,
I have added these links to the Additional Boards Manager URLs:
http://downloads.sodaq.net/package_sodaq_index.json,
http://downloads.sodaq.net/package_sodaq_samd_index.json,
https://dl.espressif.com/dl/package_esp32_index.json,
https://raw.githubusercontent.com/Lauszus/Sanguino/master/package_lauszus_sanguino_index.json,
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
And I select T-BEAM board.
My sketch is this:
#include <TheThingsNetwork.h>

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan TTN_FP_EU868

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);
}

void loop()
{
  debugSerial.println("Device Information");
  debugSerial.println();
  ttn.showStatus();
  debugSerial.println();
  debugSerial.println("Use the EUI to register the device for OTAA");
  debugSerial.println("-------------------------------------------");
  debugSerial.println();

  delay(10000);
}

and this is the error message I get on debugSerial:

In my understanding this is either a problem with the board I select (TBeam) or a possible but on TheThingsNetwork library.
I would appreciate some help to run this script successfully so I can register my device on TheThingsNetworkor, or at least debug further this problem.
Thank you in advance.

LoadProhibited usually means that you're trying to read data from an uninitialized pointer. Maybe there's a step you missed, like ttn.begin() or something?

For this device you can't get the EUI that way (I can't tell you why). What can you do is to go to TTN > Register new device > Device EUI (Press the button for generating the automatic key).
This is just a temporary fix. The correct way to get the EUI is by generating it from the MAC address. You can find some examples online. I did not succed in doing it, but the automatically generated EUI works. Please let me know if you succed in working with ttgo t-beam because I did not :) and I would like to know more!


text:
SPIFFS image does not fit in flash (offset 108MB)
I'm trying to upload an empty SPIFFS image to my ESP32's flash memory via the ESP32 sketch data uploader but I'm getting the following error:
[SPIFFS] data   : /path/to/my/data
[SPIFFS] start  : 108068864
[SPIFFS] size   : 1596
[SPIFFS] page   : 256
[SPIFFS] block  : 4096
[SPIFFS] upload : /tmp/arduino_build_145856/firmware.spiffs.bin
[SPIFFS] address: 108068864
[SPIFFS] port   : /dev/ttyACM1
[SPIFFS] speed  : 921600
[SPIFFS] mode   : dio
[SPIFFS] freq   : 80m

esptool.py v2.8-dev
Serial port /dev/ttyACM1
Connecting....
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz
MAC: 84:0d:8e:18:a8:b4
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Configuring flash size...
Auto-detected Flash size: 8MB

A fatal error occurred: File /tmp/arduino_build_145856/firmware.spiffs.bin (length 1634304) at offset 108068864 will not fit in 8388608 bytes of flash. Use --flash-size argument, or change flashing address.
SPIFFS Upload failed!

I have chosen the correct flash-size (8MB) and the default partition scheme which worked before and I have also compiled/uploaded a version for 4MB flash size and the corresponding default partition scheme, but the data uploader still wants to write at the illegal address. I also erased the flash before uploading - no effect.
Why does it want to write to an offset of 108MB ?! Is there a bug in the data uploader? To odd things out I'd like to have a look at the partition scheme, but I can't find the directory where those are located (I'm on linux).
Has anyone experienced this before?
EDIT: this is the partition table I read back from the ESP32:
# Espressif ESP32 Partition Table
# Name, Type, SubType, Offset, Size, Flags
nvs,data,nvs,0x9000,20K,
otadata,data,ota,0xe000,8K,
app0,app,ota_0,0x10000,3264K,
app1,app,ota_1,0x340000,3264K,
eeprom,data,153,0x670000,4K,
spiffs,data,spiffs,0x671000,1596K,

EDIT 2: I found that the partition table has to be stored at address 0x9000 on newer devices (while it was 0x8000 on older ones). Could this be the root of the problem? The program I uploaded worked fine, though (except for SPIFFS features).
Where can I configure the partition table's offset when using the arduino IDE?

It's interesting that 108068864 is 0x6710000 whereas the partition table is for 0x671000. It's uploading at exactly a factor of 10 out. Something somewhere is calculating or obtaining a completely wrong value. What version of the ESP32 core are you using?

Looking at your partition table it must be a bit old, since the eeprom partition is obsolete now. EEPROM data is stored in nvs these days.

Oh, and the location of the partition table is controlled by the bootloader, not the age of the device.


text:
Stream esp-32 camera to RMTP server like YouTube
I am doing research for a project in which I need to play with camera streams. After multiple hit and trails and googling I am not getting even close to the solution for streaming ESP-32 Camera stream to my own RMTP server directly.
Already tried solutions:
1) I have tried re-streaming of ESP-32-cam with Raspberry pi, that works well but not something I am looking for
2) ESP-32-cam: Record and FTP transfer with time triggers (Not tried but believed that it is not a good approach).
Please note: I am not looking at the solution in which ESP-32 cam acts as stream server and browser can connect to it like : https://www.hackster.io/BnBe_Club/9-rtsp-video-streamer-using-the-esp32-cam-board-8832b4
I have already tried it and it works well but not for the usecase which involves streaming to RTMP server without restreaming.
On google, I found a similar thread : https://forum.arduino.cc/index.php?topic=634605.0
The guy with solution is not interested in sharing it.
may be some modification required in below code MAY BE
ref: https://github.com/espressif/esp32-camera
static esp_err_t stream_handler(httpd_req_t *req){
  camera_fb_t * fb = NULL;
  esp_err_t res = ESP_OK;
  size_t _jpg_buf_len = 0;
  uint8_t * _jpg_buf = NULL;
  char * part_buf[64];

  res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  if(res != ESP_OK){
    return res;
  }

  while(true){
    fb = esp_camera_fb_get();
    if (!fb) {
      Serial.println("Camera capture failed");
      res = ESP_FAIL;
    } else {
      if(fb->width > 400){
        if(fb->format != PIXFORMAT_JPEG){
          bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
          esp_camera_fb_return(fb);
          fb = NULL;
          if(!jpeg_converted){
            Serial.println("JPEG compression failed");
            res = ESP_FAIL;
          }
        } else {
          _jpg_buf_len = fb->len;
          _jpg_buf = fb->buf;
        }
      }
    }
    if(res == ESP_OK){
      size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
      res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
    }
    if(res == ESP_OK){
      res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
    }
    if(res == ESP_OK){
      res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
    }
    if(fb){
      esp_camera_fb_return(fb);
      fb = NULL;
      _jpg_buf = NULL;
    } else if(_jpg_buf){
      free(_jpg_buf);
      _jpg_buf = NULL;
    }
    if(res != ESP_OK){
      break;
    }
    //Serial.printf("MJPG: %uB\n",(uint32_t)(_jpg_buf_len));
  }
  return res;
}


text:
Hooking Up 8 ohm Speaker to Arduino
Is this a correct way to connect an 8 ohm beaker to an Arduino?
https://www.c-sharpcorner.com/article/audio-play-using-sd-card-module-and-arduino/

You probably need a small op-amp like an LM741 to drive an 8ohm speaker from an Arduino https://www.electronics-tutorials.ws/opamp/opamp_1.html

To effectively drive a speaker from an Arduino you need an amplifier. The good ol' LM386 is a common choice for this (readily available and cheap, though not recommended for battery based projects).
While it is possible to drive a speaker directly it's not recommended. Not only is it very quiet, but also it can damage the IO pin. Not only from excess current draw (peak current at 5V through 8Ω [nominal] is 626mA,  more than 15x the maximum the pin can supply, which not only stresses the pin but also distorts the output waveform) but a speaker is also an inductive load which has all the associated issues of back-EMF and such.

I have also seen 1 transistor designs which isolate the speaker from the processor's I/O pin.  Should we include these in the answer - or is there a reason to avoid this solution?

No, no reason why not. A transistor is just acting as an amplifier. I just mentioned the lm386 as an example.

You had to put a resistor in serial with the speaker, Max current from the pin is 40 mA if put 8 ohm speaker on the pin it can't drive the speaker. Try a speaker with higher impedans.

it can drive the speaker and it works, but it stresses the pin that is why there should be a resistor. to limit the current. (downvote is not my).


text:
595 Shift Register Not Working Properly
I followed the tutorial on controlling 8 LEDs using a SIPO SN74HC595N shift register on both Adafruit and Last Minute Engineer. I used a Sparkfun Pro Micro (Arduino Leonardo equivalent).
The problem is the LEDs are not lighting up in the way that I'm expecting it do it. Both guides said each LED will light up one after another. After all 8 are lit, all of them will turn off. Here is my result. Other LEDs will either dim up or down as the target LED turn on. I used the code provided from the guide and only changed the pinout number. The resistor values are the same for each color so it can't be the resistor. Anyone have any idea what's going on here?
/*
Test code for 74HC595N SIPO shift register. Used with Pro Micro
*/

int latchPin = 16;
int clockPin = 15;
int dataPin = 14;
int outputEnablePin = 10;

byte leds = 0;    // Variable to hold the pattern of which LEDs are currently turned on or off

void setup()
{
  // Set all the pins of 74HC595 as OUTPUT
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(outputEnablePin, OUTPUT);
  outputEnablePin = LOW;
}

/*
 * loop() - this function runs over and over again
 */
void loop()
{
  leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++) // Turn all the LEDs ON one by one.
  {
    bitSet(leds, i);    // Set the bit that controls that LED in the variable 'leds'
    updateShiftRegister();
    delay(500);
  }
}

/*
 * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
 */
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

Schematics:

The resistor values are the same for each color so it can't be the resistor. What makes you think that? The current through the LED is dictated by the resistor value and the LED's forward voltage. The LED's forward voltage is dictated by the colour. Thus you need to size the resistor correctly for each colour of LED.

That said, the fact that some turn part way on when they shouldn't really is a concern.

Is your pro micro a 3.3V or a 5V one?

The Pro Micro is 5V. What I meant by the resistors is there is two led of the same color and there is 4 different colors. I calculate the resistors value based on their given forward voltage and current for each color. The resistor value is the same for the pair of leds with the same color.

It would really help if you add a schematic of how you actually built the circuit, instead of me trying to debug your circuit from a low resolution, animated GIF. Your code looks fine at first glance, btw.

The GND of the 74HC595 is connected to the right power rail (blue line) on your breadboard. But this rail isn't connect to the GND of the Arduino.

I was making the schematic for StarCat and just found that GND error! Stupid me! I connected it to ground and now the dimming LEDs are gone! However, I still have problems with the LED. The LEDs are not lighting up in the pattern that the code designed them to.

@Agriculex, Glad to be of help ;-) You could write an answer to your own question.

I just found out solution to the pattern issue. The guides didn't say it (at least not clearly enough) that pin 10 (SRCLR with the line/bar on top) needs to be connected to 5V.

@Agriculex - Please answer your own question then accept that answer in 48 hours.

StackExchange is not a forum. You don't edit the question's title with "Solved" if you have an answer. Instead you write an answer and (later, when you're allowed to) you mark it. Please correct that. People coming here don't look for "Solved", they look for marked answers.

Did that just now. I'm still new to how StackExchange works opps.

The dimming problem was found to be the shift register IC not connected to Ground (dumb me).
However, there is still problem with LED's on and off pattern. Sometimes two LEDs turn on at the same time and all previous LEDS turning off before the last or second last LED is turned on. It turns out Pin 10 (SRCLR Bar) needs to be pulled to high to solve that pattern discrepancy.

Yes. You can't leave important pins, like SRCLR, floating. Signals that matter must be intentionally set. True with any chip.


text:
PWM supplying led breaks down at near to zero threshold
I use timer1, mode 8, on both pin 9 and 10 at 1 kHz my PWM signal breaks down when I turn the potentiometer just above where I set the zero at, no matter where I set the zero at.  I power the Arduino atmega328p with Vin and disconnect from the PC.  I have potentiometer to A0 and pin out 9 or 10 connected to the oscilloscope.  I have code and picture below.
The problem with my code is that I can't get TCNT1 or TCNT2 to start where I set it anywhere else but zero.
#include <avr/io.h>
#include <avr/interrupt.h>
//#include <SPI.h>
//ISR(TIM1_COMPA);
//ISR(TIM1_CAPT);

int analogInPin = PC0;
int analogOutPin9 = PB1;
int analogOutPin10 = PB2;
int analogOutPin3 = PD3;
int analogOutPin11 = PB3;
//int analogInPin = A0;
//int analogOutPin9 = 9;
//int analogOutPin10 = 10;

int sensorValueTimer1;
int sensorValueTimer2;

void sens(int &sensorValueTimer1, int &sensorValueTimer2){
   sensorValueTimer1 = (((long)analogRead(analogInPin)*1000)/1023);
   if (sensorValueTimer1 < 35){  //to stop flickering at low end
     sensorValueTimer1 = 0;
     }
        sensorValueTimer2 = (((long)analogRead(analogInPin)*255)/1023);
   if (sensorValueTimer2 < 0){  //to stop flickering at low end
     sensorValueTimer2 = 0;
     }
}

void updateOCRnx(){
  sens(sensorValueTimer1,sensorValueTimer2);
  int x = sensorValueTimer1;
  int y = sensorValueTimer2;
  OCR1A = x;
  OCR1B = x;
  OCR2A = y;
  OCR2B = y;
}

void setup() {
  Serial.begin(9600);
  //===============mode 5 pin 3,11==================//
  /*
  //TCCR2A = 0;
  //TCCR2B = 0;
  TCCR2A |= (1<<COM2A1);
  TCCR2A |= (1<<COM2A0);
  TCCR2A |= (1<<COM2B1);
  TCCR2A |= (1<<COM2B0);
  TCCR2A |= (1<<WGM21);
  TCCR2A |= (1<<WGM20);
  TCCR2B &= ~(1<<WGM22);
  TCCR2B &= ~(1<<CS22);
  TCCR2B |= (1<<CS21);
  TCCR2B |= (1<<CS20);

  //TIMSK2 |= (1<<OCIE2A);
  //TIMSK2 |= (1<<OCIE2B);
  //TIMSK2 |= (1<<TOIE2);
  //ASSR &= ~(1<<TCN2UB);
  //TIFR2 |= (1<<OCF2A);
  //TIFR2 |= (1<<TOV2);

  TCNT2 = 100;
 */
  //====================mode 5 pin 3,11=====================//
  //=====================mode 8 pin 9,10=====================//
  //TCCR1A = 0;

  TCCR1A |= (1<<COM1A1);
  TCCR1A &= ~(1<<COM1A0);
  TCCR1A |= (1<<COM1B1);
  TCCR1A &= ~(1<<COM1B0);
  TCCR1A &= ~(1<<WGM11);
  TCCR1A &= ~(1<<WGM10);
  TCCR1B |= (1<<WGM13);
  TCCR1B &= ~(1<<WGM12);
  TCCR1B |= (1<<CS11);
  TCCR1B &= ~(1<<CS12);
  TCCR1B &= ~(1<<CS10);

  //TCCR1B |= (1<<ICES1);

  //TCCR1C |= (FOC1A);
  //TCCR1C |= (FOC1B);

  ICR1=1000;  //1.333KH
  TCNT1=0;

  //TIMSK1 |= (1<<TOIE1);
  //TIMSK1 |= (1<<OCIE1A);
  //TIMSK1 |= (1<<OCIE1B);
  //TIMSK1 |= (1<<ICIE1);
  //TIFR1 |= (1<<TOV1);
  //TIFR1 |= (1<<OCF1A);
  //TIFR1 |= (1<<OCF1B);

  //EIMSK |= (1<<INT1);
  //EIFR |= (1<<INTF1);
  //EICRA &= ~(1<<ISC11);
  //EICRA &= ~(1<<ISC10);

  //PCMSK0 |= (1<<PCINT2);
  //PCICR |= (1<<PCIE0); //pin change interrupt 0 is enabled
  //PCIFR |= (1<<PCIF1); // triggers an interrupt request
  //=======================mode 8 pin 9,10=======================//

  sei();

  //pinMode(analogOutPin9,OUTPUT);
  //pinMode(10, INPUT);
  //pinMode(analogInPin, INPUT);

  //char data;

  DDRB |= (1<<analogInPin);
  DDRB |= (1<<analogOutPin9);
  DDRB |= (1<<analogOutPin10);
  DDRB |= (1<<analogOutPin11);
  DDRB |= (1<<analogOutPin3);
  //DDRB |= (1<<PB5);
  //DDRB &= ~(1<<PB4);

  //SPSR |= (1<<SPIF);

  //SPCR |= (1<<SPE);
  //SPCR |= (1<<MSTR);
  //SPSR &= ~(SPR1);
  //SPCR |= (1<<SPR0);
  //SPSR |= (1<<SPI2X);

  //SPDR = data;

}

void loop() {
  updateOCRnx();
  Serial.println(TCNT1);
  //delay(100);
  //int sensorValue = (((long)analogRead(analogInPin)*1000)/1023);
  //int sensorValue = analogRead(analogInPin);
  //analogWrite(analogOutPin9, sensorValue/4);
  //analogWrite(analogOutPin10, sensorValue/4);
  //Serial.println(analogOutPin9);
}

What is your oscilloscope Trigger Mode set to? Auto or Normal?

The trigger mode was set to auto, I set it to normal, I still see the square wave expand out a little bit for about  1/10 a second and repeats every half a second.  I see the same thing on the light fixture with CREE XPE2 LED.  It flickers about the same as the oscilloscope flickers when I have my MCIGICM 10K Ohm potentiometer at very near to where I set zero at.  My corals and my eyes are thank full for a direction.

The analogread pin is unstable. This fixed it,ResponsiveAnalogRead, from github

That's a vague explanation and IMHO not evident


text:
Making Cases for Projects
I've been messing around with arduinos and other microcontrollers for around a year now and I've always struggled to find ways to encase my projects. I've seen some people use custom PCBs and then 3D print a case for that.  How would one go about that? I am only a computer science student so I know nothing about electrical circuitry.
For example, lets say I have a UltraSonic Sensor that uses a Arduino nano to light an LED. How would I transfer that to a single PCB? And are there websites where I can order custom 3D printed cases for my projects?
Please let me know if you need me to make my question clearer. Thank you!

Your question has multiple layers:

The custom PCB: Breadboards are good for experimenting, but not for a finalized circuit. Depending on some factors you can decide between multiple options. One, that I myself often use, is soldering the parts onto a perfboard. That are cheap PCBs, where - depending on the type - you have a grid of single through-hole solder pads or connected groups of through-hole solder pads. I like to use these:

The pads are connected nearly like a breadboard, so it is easy to use with Arduinos and such. You can build your circuit on there by soldering the parts to it, and make the PCB the right size by cutting it into the needed size.
A more professional option is to buy real custom PCBs. You need to create the PCB layout on your PC (common programs are Eagle or Kicad, though there are many others). Then you can choose the PCB manufacturer of your trust and give them your layout files. They will manufacture the PCBs and send them to you. This options costs a bit money (though not a lot) and you will have to wait for the PCBs to arrive.
The casing: There are many options to choose from:

You can buy a generic case somewhere (hardware store, or the internet shop of your trust). Then you can work on it to fit your purpose (drilling holes for the LEDs, using screws or glue to fix your PCB, ...)
There are some standard cases to buy, though most of them most likely don't fit you good, since they are made for special industrial purposes.
You can create a custom 3D printed case. For this you first need to design the case on your PC (a common program is Fusion360, though I'm using FreeCAD). For the actual printing you can either use your own 3D printer, or you can again find a good 3D printing service, that you can give your design file (commonly in the stl format). They will print it for you for a bit of money. You will have to choose between different manufacturing methods, mainly FDM (putting lines of molten plastic onto each other layer after layer) or Resin printing (curing layers of fluid resin one after another). FDM is still cheaper. And you need to decide on the material (PLA is common, others are ABS or even metal (though the last is expensive). Also you need to design your case in a way, that it is good printable with the chosen method. You need to read more about 3D printing elsewhere (there are tons of material about it on the web).

One rule of this site is to not give product recommendations. That's not, what the site is for, and they are pretty fast outdated. Instead you need to do the research yourself.

You might want to look into JLCPCB, who have a good prototype offer. Though because of corona don't expect much currently


text:
TX, RX, ON, L LEDs were red at all time
Before seeing this error I did a project with my Uno board using a Bluetooth module.
After that, when I powered the board to upload another program, 4 LEDs (L, TX, RX, ON) went red without blinking.
So now, every time when I power up my Uno board, without any connection with any of the pins previously mentioned, the 4 LEDs are red coloured all the time.

are you able to upload something, like a "blink" sketch to board ?

There may be good reasons, that the LEDs are on. That's not directly an error. Are you still able to upload programs? What happens, if you upload the blink example?

When I tried uploade the blink example it's not uploading to the board,it says there a touble shooting problem.

Please give us the full error message (add it to your question by editing it)

If the LEDs are red then it's not a genuine Arduino. If it's not a genuine Arduino then all bets are off as to what happened.

If you can upload sketches, I don't think it is that big of a deal but if you can't, check the TX and RX pin tracks since if those tracks are shorted, they can keep the indicator lights on for ever due to the Serial code on the Arduino. To get further help, please tell me what happens if you try uploading code.


text:
Send RAW IR code with ATtiny85
I am looking for a ATtiny85 send RAW IR code using a ATtiny85.  I have it sending HEX code just fine, but just cannot find something for RAW. I have IRsend RAW IR running just fine on a NANO. Problem is will not compile on a ATtiny85. ATtiny85 does not have Timer2, and it seems most of the code written uses Timer2. ATtiny has only Timer 0 and 1, both 8 bits wide. I tried to port it over from NANO to ATtiny85 by fooling with the IRLib2, but just do not have enough experience to make it happen..HELP
Thanks
Darryl..

what does this mean? sending HEX code just fine

The IRremote library for Arduino does support of using different timer, all you need is correctly configure it of the board you use. As far as I can see is that it does support ATtiny85, all you need is to configure it correctly. You can run IRremoteInfo example sketch to confirm if you have the correct setup.

The definition of the timer to be used and how to generate the 38kHz clock for each MCU type is defined in boarddefs.cpp

When i say HEX, one of the IR Libs uses HEX instead of RAW  Example = 0x1CE318E7 (SANYO Mute .  Raw is a series of numbers representing Carrier on time and carrier off time


text:
How to change wifi credentials of multiple ESP8266 together
I need to change WiFi credentials of multiple ESP8266 in one go, without needing to change passwords for each of them individually. I know there is a WiFiManager library, which makes your ESP8266 access point when not connected to any network, but that will require me configure each of them individually.
How can I save the fatigue of changing their wifi credentials individually? All of them needs to connect to the same network, whose password is recently changed.

You could implement a "provisioning service". Kind of like WiFiManager but in reverse. If you can't connect to the real access point then connect to the provisioning access point, from which you can then obtain the credentials to connect to the real access point. Of course you just move your security weakness to the provisioning access point which can never have the details changed...

you can reconfigure your router, or whatever network mode you are using, with auto-login to the MAC addresses of your ESPs.
And then if you provide the MACs of the corresponding ESPs, and change your WiFi credentials, then you don't need to configure the ESPs individually. It will auto-connect itself.

Have your devices always try to download a config file from a webserver you control.  If the config file exists and has new wifi credentials then it can update itself and reset.  When you actually change the password for the AP all the devices will already have the new password.


text:
Check if the board is in sleep mode
I'm using seep sleep mode with UNO with a simple sketch that turning on an LED and then goes to sleep. as far as the ATmega328p datasheet in sleep mode part showing the wake up sources and deactivated clock sources in deep sleep mode and the I/O clock becomes deactivate so we expect when the board goes to sleep the LED should become off because of no clock. but it doesn't happen and LED keeps ON in sleep mode. what is the problem?7 and how can we even find out that the board is on sleep mode or not?

Why do you think, that the output will be turned off, when going to sleep? As of my understanding, the value of the pin cannot change in sleep, since the latch does not have a clock signal. But that doesn't mean, that the output is turned off.

use the LED to indicate sleep mode ... turn off led upon wakup

The IO doesn't require the clock to keep its current state. It only requires it to change state.
There is no real external signal provided by the chip to indicate if its in sleep mode or not. However you could monitor the current consumption of the chip and when it drops below a certain threshold you can assume that it is in sleep mode.

You could easily set the LED output LOW just before you call going_to_sleep(), and set it HIGH when going_to_sleep() returns. There would be two short periods where the LED signal would indicate sleeping but the processor is running:

between the LED going LOW and the processor actually entering sleep; and
between the processor waking and the LED going HIGH.

But at these times the processor could not respond to your external system anyway.


text:
L293D to change the direction current and amplify it - Temperature-Stabilizer
I have a question about my project. I'm going to make a temperature-stabilizer. To make this, I think I should use a TEC with a H-bridge and a LM35. First of all, I tried to make a H-bridge by myself, I have only used four NPN transistors and It didn't go well. Then I bought L293D motor driver - not the module one, tried it and it works well. But as datasheet says, it's output current is max 600mA. But this current doesn't make TEC work efficiently. So that, I need to amplify the current. But I don't want to buy high amp motor drivers, hardwares are to expensive in my city. Of course I'll if there's no another way.
Arduino will be used to get temperature values from LM35 and give the H-bridge voltage, control the current direction when necessary. I learned how to use transistors to amplify but if I'll change the direction, it won't work. But I don't know how to make this circuit.
The algorithm that I thought using is this:

The scheme that I thought using in this:

What should I do to solve my problem? Thank you for all.
Resources:

My Tec1-12706 Datasheet:
http://www.thermonamic.com/TEC1-12706-English.pdf
LM35 Datasheet - (I have LP package):
https://www.ti.com/lit/ds/symlink/lm35.pdf
L293D Datasheet: https://www.ti.com/lit/ds/symlink/l293.pdf
The transistor method to amplify:
https://www.youtube.com/watch?v=WZD9RZoMhVE

Amplifying the current is basically what the LM293D is doing. You need a more powerful H-bridge. There's not really any way around that.

Use LM298 which provide up to 2A.

I am interested on this as I have the same issue. What about using a FET or MOSFET to amplify the current that the LM293D provides?


text:
How can i read and write the data from a Delta plc-s series through Arduino UNO?
I am trying to communicate PLC with arduino through rs232 as well rs 485. But, I am not able to read and write data. I can observe the data in PLC through ladder logic but not in arduino. I am trying to implement the Modbus ASCII here but reading and writing both is not happening.
#include <EmSevenSegment.h>
#include<SoftwareSerial.h>

EmSevenSegment disp(4, 'C', 4, 3, 2);
SoftwareSerial debuggingSerial(0, 1); //RX,TX

[![enter image description here][1]][1]String readlineString = "";
String integerString = "";
String decimalString = "";
String outputString = "";
char startChar = 0x01;
char endChar = 0x01;
//char weight[10];

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

}

void loop() {
  Serial.print("!!!!!!!!!!11111111111\n");
  delay(1000);
  if (debuggingSerial.available())
  {
    Serial.print("!!!!!!!!!!2222222222\n");
    readlineString = debuggingSerial.readString();
    Serial.print(readlineString);
  }

  if (readlineString.length() > 0)
  {
    Serial.print("!!!!!!!!!!333333333333\n");
    integerString = readlineString.substring(10, 12);
    decimalString = readlineString.substring(13, 15);
    int number = (integerString + decimalString).toInt(); // 6789; //Number to be displayed
    disp.print(number); // Print the number
    Serial.print(readlineString);
    readlineString = "";
  }

}

Please find the image of rs232 connection:

Hi, please check the query once again. It is attached now. It is below arduino code.

what are the rs232 signal names of the pins that you connected?

the signal name are Rx(brown wire) and Tx(beside brown wire) and last pin is GND.

that describes three pins .... the picture shows three wires ... that is six pins .... please answer the question again

I am trying to read and write only. I don't think so, we need all the pins for reading and writing using modbus protocol.

You cannot use software serial on pin D0 and D1. Those two pins are for hardware serial (i.e. for your Serial.println())

it means that I can not read and write the value through these two pins