body:
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?https://arduino.stackexchange.com/q/70885

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;
        }

      }

    }

title: the boxservo works contrary to the code

Answers: 1

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


body:
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?

title: Arduino Mega LED doesn't light as expected

Answers: 2

body: 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.

body:
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:

```C
for(int r=0; r<14; r++ ) {
  digitalWrite(LED[r],HIGH);
  delay(100);
}
```


body:
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

[![Display i2c data][1]][1]

This is the sniff from my code

[![Arduino i2c data][2]][2]

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);
    }

  [1]: https://i.stack.imgur.com/z58JB.png
  [2]: https://i.stack.imgur.com/kphgd.png

title: Problem with I2C

Answers: 0


body:
I am trying to make an HTTP request in two ways

1. Connecting sim900 to pc using TTL converter (without external power, only USB power)

2. 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

[![power from arduino][1]][1]

[![external power][2]][2]

  [1]: https://i.stack.imgur.com/MxvoQ.png
  [2]: https://i.stack.imgur.com/6WmFv.png

title: Sim900b(chinese sim900a) AT+HTTPACTION=(0/1)reboots the module

Answers: 0


body:
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);
      }

    }

 [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/q147O.png

title: Problem with if condition

Answers: 1

body:
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)


body:
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.

title: LCD write a line at bottom without lcd.setCursor and without deleting any char above already there?

Answers: 1

body:
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.


body:
I'm trying to use an `Arduino Nano` to communicate with a Quectel EC25 module from this [Raspberry Pi 4G HAT][1]. 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][2] by changing the default RX and TX pins but does not work at all.

  [1]: https://sixfab.com/product/raspberry-pi-base-hat-3g-4g-lte-minipcie-cards/
  [2]: https://www.arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

title: Receive SMS using Arduino Nano and Quectel EC25

Answers: 0


body:
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.

title: How to properly pass struct as argument?

Answers: 0


body:
I was trying to drive a single dc motor with L293D Shield and Arduino Uno

~~~c
#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?

title: DC Motor doesn't turn and a beep sound is made, also there is a burning smell

Answers: 1

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


body:
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:

[![enter image description here][1]][1]

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.

  [1]: https://i.stack.imgur.com/C1Qyx.png

title: Lilygo TTGO T-Beam Guru Meditation Error

Answers: 0


body:
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?

title: SPIFFS image does not fit in flash (offset 108MB)

Answers: 0


body:
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;
}
```

title: Stream esp-32 camera to RMTP server like YouTube

Answers: 0


body:
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/

title: Hooking Up 8 ohm Speaker to Arduino

Answers: 2

body: 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.

body:
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.


body:
I followed the tutorial on controlling 8 LEDs using a SIPO SN74HC595N shift register on both [Adafruit][1] and [Last Minute Engineer][2]. 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][3]. 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:**

[![enter image description here][5]][5]

  [1]: https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds/overview
  [2]: https://lastminuteengineers.com/74hc595-shift-register-arduino-tutorial/
  [3]: https://gph.is/g/Z2mPdPW
  [4]: https://gph.is/g/aXJBj6R
  [5]: https://i.stack.imgur.com/Vs1Kr.jpg

title: 595 Shift Register Not Working Properly

Answers: 1

body:
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.


body:
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);
    }

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/P6nEr.jpg

title: PWM supplying led breaks down at near to zero threshold

Answers: 1

body:
The analogread pin is unstable. This fixed it,ResponsiveAnalogRead, [from github][1]

  [1]: https://github.com/dxinteractive/ResponsiveAnalogRead


body:
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!

title: Making Cases for Projects

Answers: 1

body:
Your question has multiple layers:

1. **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:

    [![perfboard with conveniently connected pads][1]][1]

    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.

2. **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.

  [1]: https://i.stack.imgur.com/zoXc2.jpg


body:
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.

title: TX, RX, ON, L LEDs were red at all time

Answers: 1

body: 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.


body:
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..

title: Send RAW IR code with ATtiny85

Answers: 0


body:
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.

title: How to change wifi credentials of multiple ESP8266 together

Answers: 2

body: 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.

body:
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.


body:
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?[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/6GTrK.png
  [2]: https://i.stack.imgur.com/KLhEv.png

title: Check if the board is in sleep mode

Answers: 2

body:
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.

body:
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:

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

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


body:
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:**

[![Algorithm of Temperature Stabilizer for +-3*C degree][1]][1]

**The scheme that I thought using in this:**

[![The scheme that I thought using in this.][2]][2]

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

**Resources:**

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

  [1]: https://i.stack.imgur.com/fqb7c.png
  [2]: https://i.stack.imgur.com/aNoDu.png

title: L293D to change the direction current and amplify it - Temperature-Stabilizer

Answers: 1

body: 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?


body:
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:

 [![image rs232 conection][1]][1]

  [1]: https://i.stack.imgur.com/pYofM.jpg

title: How can i read and write the data from a Delta plc-s series through Arduino UNO?

Answers: 0


body:
I made my DAC code with DAC5311 and Arduino Uno.
I think it has no problem, but it doesn't work well. Just print 0.(I use an oscilloscope.)
I don't know where has the problem. Please give me any suggestion.

    #include <SPI.h>
    #include <math.h>
    #define pin_CS 10
    #define pin_MOSI 11
    #define pin_SCLK 13
    #define max_VOLT 5

    void setVoltage(float voltage){
      if (voltage < 0) voltage = 0;
      if (voltage > max_VOLT) voltage = max_VOLT;
      uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
      temp = temp << 6;
      uint8_t upper = temp >> 8;
      uint8_t lower = (temp & 0xff);
      digitalWrite(pin_CS, LOW);
      SPI.transfer(upper);
      SPI.transfer(lower);
      digitalWrite(pin_CS, HIGH);
    }

    void setup() {
      Serial.begin(9600);
      pinMode(pin_CS, OUTPUT);
      pinMode(pin_MOSI, OUTPUT);
      pinMode(pin_SCLK, OUTPUT);
      SPI.begin();
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      digitalWrite(pin_CS, HIGH);
    }

    void loop() {
      setVoltage(5);
      delay(10);
    }

title: Digital to Analog converter with DAC5311, Any suggestion?

Answers: 1

body:
Classical +/- 1 problem

If you do this calculation by hand `uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);`
you will get `temp=256` and this is a value you can not convert with a 8 bit DAC.

Try `uint16_t temp = int(voltage * (pow(2, 8)-1) / max_VOLT);` instead.

(or event better for a µC `uint16_t temp = (uint16_t) (voltage * (255 / max_VOLT));`)


body:
How can we get a timer interrupt at a specific time or date?

For example: I want to make a project with an Uno and I'm using sleep mode and the wake-up source is timer2, as per the ATMega328p datasheet.

I want to turn on an LED, for example every day at 3pm, and the chip is in sleep mode on other times of the day.

So, how can I set the timer?

I think I have to use CTC mode of timer2 and set the OCR amount but I'm not sure how to do it.

There's a project on [(Link)][1] this link on the Arduino site that is perfect for this project, but when I compile it, it gives me an error saying that it can't be compiled for the Uno.

[![enter image description here][2]][2]

  [1]: https://www.arduino.cc/en/Tutorial/SleepRTCAlarm
  [2]: https://i.stack.imgur.com/K2s1X.png

Answers: 0


body:
It's possible use external interrupts/attachInterrupt() with the ATtiny85 when I program with Arduino IDE?

If is possible, how many inputs (for external interrupts) the ATtiny85 have and which are they?
Someone have an example code?

title: How to use attachInterrupt() in ATtiny85 with Arduino IDE?

Answers: 1

body:
Pin PB2 is the only pin that has a real external interrupt.  This is `INT0`.

Whether you can use `attachInterrupt(0, ...)` or not is entirely down to whether it is implemented in the core that you are using.


body:
So i have this code that whenever i click a button a interrupt starts.
In this interrupt i want to do a get request to a webserver.

The thing is seperate the code, the interrupt code works and without an interrupt the http request also works.
But when i put this together it doesn't.

Does anybody have an idea why this doesn't work?

```
// Libraries
#include <ESP8266HTTPClient.h>
#include<ESP8266WiFi.h>

char ssid[] = "";
char pass[] = "";

int ledpin = 5; // D1(gpio5)
int button = 4; //D2(gpio4)
int buttonState=0;

ICACHE_RAM_ATTR void ISR() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();

  if (interrupt_time - last_interrupt_time > 200)
  {
      Serial.println("Drukknop ingedruk");
      Serial.println("Sending message to server");
       if (WiFi.status()==WL_CONNECTED)
      {
        HTTPClient http;
        String url="<httpurl>";
        http.begin(url);
        http.addHeader("Content-Type","text/plain");
        int httpCode=http.GET();
        Serial.println(httpCode);
        String payload=http.getString();
        Serial.println("While sending I received this from server : "+payload);
        http.end();
      }
      else
      {
        Serial.println("Internet Problem!");
      }
  }
  last_interrupt_time = interrupt_time;
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,pass);

  while(WiFi.status() !=WL_CONNECTED)
  {
    delay(500);
    Serial.println("Waiting for connection");
  }

  Serial.println("Connected...");
  delay(1000);
  if (WiFi.status() ==WL_CONNECTED)
  {
    Serial.println("Wi-Fi Connected!");
  }
  delay(5000);
  Serial.println("ok");
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), ISR, RISING);

}
void loop() {

}
```

title: Http request in interrupt esp8266 not working

Answers: 1

body: Doing something as complex as a HTTP request in an interrupt is a very very silly idea. Instead set a flag in the interrupt routine and examine that in the main `loop()` function to perform your HTTP request.


body:
Okay, guys. I have this 3 cameras(middle from the iPhone 6s, 2 at the side I found, and I think there are from modern phone). **I need some information how to connect Arduino Uno to them.** I know c/c++, assembler, but noob in microcontrollers, if this knowledge can come useful.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Dkf1O.jpg

title: How to connect naked camera from mobile phone to Arduino Uno

Answers: 1

body:
You need either a memory extension for your UNO - projects like Arducam did this way back 2016 and then used an OV2640 module. If you want to develop something yourself these are the steps (hurdles) to take:

 - Get a datasheet of the camera
 - Design a circuit including
   - plug for Camera and a
   - memory module (min 512Kb)
 - Attach it to the UNO
 - Write a library/function module (see datasheet for details) and
 - bring it to life

My tip save ca. two years of your life and get for 6-8$ an ESP32cam<br>
This will cost you enough of your time, but be much more rewarding


body:
I have this snippet of code:

     if (Serial.available())
     {
        /***** DEFINE MEASUREMENT MODE *****/
        String input = Serial.readString();
        if (input[0] == 'r' && interrupts_enabled == false)
        {
          if (input[1] == 'f')
          {
            full_mode = true;
            sensor_coord = 0;
          } else
            sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

          select_sensor();

          pulse_counter = 0;
          TIMER1_clear();

          interrupts_enabled = true;
        } //first if ends here
        else if (input[0] == 'C' || input[0] == 'c')
        {
          interrupts_enabled = false;  //If the user types 'C' OR 'c', stop the measurement
        }
     }

So when i send `'rf'` to the arduino, a measurement to all my sensors starts hapening indefinetely.
(There is another mode as well, typing `'r 0'` will start an infinite measurement on the first sensor.)
When all the eight sensors, are measured, it will start from the beggining.

I wanted to be able to stop this operation when i typed a command in the serial.
This is why i addded the  `else if (input[0] == 'C' || input[0] == 'c')` portion.

So that, when the infinite measurement occurs and i press `'C'`, it is supposed to stop.

But it didn't work.
Not only that, but if i am in full mode and i then press another serial command, such as previously mentioned `'r 0'`. , nothing happens as well.

So what i am asking is:
Is there a way to stop an operation triggered frmo serial that is underway?
And by stopping it, i mean from serial as well.
Perhaps, when an operation is uderway taht is triggered from serial, it cannot be stopped until the operation is finished?
Maybe it has to do something with when i have already typed 'rf' and sometime later i type `'C'`, maybe that `'C'` is no longer on position `input[0]` of the serial buffer?

EDIT: This is the full code:

    /***** CONSTANTS *****/
    const int BAUD_RATE = 9600;
    const int INTERRUPT_PIN = 3;
    const int S0_PIN = 4;
    const int S1_PIN = 5;
    const int S2_PIN = 6;
    const int OE_BAR_PIN = 22;
    const int NUM_OF_SENSORS = 8;

    /***** ANALOG CIRCUIT CONSTANTS *****/
    const double CAPACITOR_VALUE = 400; //pF
    const double GAIN_VALUE = 3.5222672065;
    const double R_BIAS_VALUE = 98.7; //kΩ

    /***** GLOBAL VARIABLES *****/
    int number_of_samples = 500;
    int sensor_coord;
    boolean full_mode = false;

    unsigned long overflows = 0;
    unsigned long ticks = 0;
    double period = 0;

    //variables for determining if a resistance cannot be measured !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    unsigned long timestamp = 0;
    unsigned long measurement_timeout = 5000;  //5 seconds is the timeout time
    boolean sensor_corruption[8]; //each element of the array is the sensor info. If false, resistance is working. If it's true, resistance is open.
    boolean ISR_unavailable = false; //this flag is raised, when the ISR does not run, because no signal comes from the circuit, because resistance is open circuit

    //variables that get changed inside the ISR - thus are declared volatile!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    volatile int pulse_counter = 0;
    volatile boolean interrupts_enabled = false;
    volatile boolean measurement_finished = false;

    void setup()
    {
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

      digitalWrite(OE_BAR_PIN, HIGH);
      pinMode(OE_BAR_PIN, OUTPUT);
      pinMode(S0_PIN, OUTPUT);
      pinMode(S1_PIN, OUTPUT);
      pinMode(S2_PIN, OUTPUT);

      TIMER1_init();

      Serial.begin(BAUD_RATE);
      while (! Serial);

      //Initializing all array elements to false!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      for (int i=0; i<=7; i++)
      {
        sensor_corruption[i] = false; // false means it's working ok. true means it's open-circuit (or cannot be read anyway)
      }
    }

    void loop()
    {

      //CODE FOR SERIAL INTERFACE (RESISTANCE SELECTION)
      if (Serial.available())
      {
        /***** DEFINE MEASUREMENT MODE *****/
        String input = Serial.readString();
        if (input[0] == 'r' && interrupts_enabled == false)
        {
          if (input[1] == 'f')
          {
            full_mode = true;
            sensor_coord = 0;
          } else
            sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

          select_sensor();

          pulse_counter = 0;
          TIMER1_clear();

          interrupts_enabled = true;
        } //first if ends here
        else if (input[0] == 'C' || input[0] == 'c') //not sure if it's case sensitive, but just to make sure i added both capitals and lower-case
        {
          interrupts_enabled = false;  //If the user types 'C' OR 'c', stop the measurement
        }
      } //Serial.available portion ends here

      //no_interrupts area-------
      // TIMEOUT CODE HERE. TO DETERMINE IF A RESISTANCE IS OPEN CIRCUITED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      if(interrupts_enabled && millis() - timestamp > measurement_timeout)
      {
        sensor_corruption[sensor_coord] = true; //label the resistance (indicated by sensor_coord) as true in the boolean array. this means it's open circuited (no signal from circuit)
        measurement_finished = true; ///we set this to true, so we can enter the next block of code
        ISR_unavailable = true; //small flag in order to not do calculations (some lines below) in case of an open circuit
      }
      //-------------------------

      if (measurement_finished)
      {

        if (!ISR_unavailable) //only make these calcs, if the ISR_unavailable is false. in other words if the ISR runs (so resistance is read)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        {
            ticks = (overflows * 65536) + TCNT1;
            period = (ticks * 0.0625) / (number_of_samples - 1);

            //RESET THE SENSOR CORRUPTION TO FALSE HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!
            sensor_corruption[sensor_coord] = false;
            // if the res goes from open-circuited to working, this will restore the array so it's not labelled as open-circuited anymore
            // THE PROBLEM IS: THE FIRST MEASUREMENT AFTER IT GOES FROM OPEN -> CLOSED IS CORRUPTED. IT'S ALWAYS TO HIGH
            // MAYBE IT'S CAUSED BY THE FRICTION OF WIRES????
        }

          TIMER1_print_results();
          ISR_unavailable = false; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! reset ISR_unavailable for the next measurement
          if (full_mode)
          {
            sensor_coord++;
            select_sensor();
            //pulse_counter = 0;
            //TIMER1_clear();
            //interrupts_enabled = true; //necessary in full mode. useless if res is open-circuit, as this value never changed. but it doesn't hurt

            if (sensor_coord == NUM_OF_SENSORS)
            {

              sensor_coord = 0; //back from the beginning !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              // full_mode = false; //no i want to continue having full mode
              // interrupts_enabled = false; //no, i want to continue having interrupts

              //after i measure all 8 resistances, the interrupt_enabled will be false. so code will be stuck in my no_interrupts area
              //this means the no_interrupts() area should run only when interrupts_enabled is true

              //remove the full mode line and reset sensor coord
            }

            /* We only enter the block of code we are now, when a measurement has happened (or when the no_interrupts
            area fired).
            We know that a measurement happened because the 'measurement_finished' variable is set by the interrupt
            (or set by the no_interrupts area, in order to enter the block we are now).
            But we ONLY want to enter the block we are now, when a measurement is finished, in order to process it.
            So now, that we did process it, in the end of this block, we have to reset the value.
            So we set measurement_finished to false, in order to not enter the block we are now, unless a new
            measurement has occured (or the no_interrupts area fired).
             */
            //measurement_finished = false;
            //timestamp = millis();  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //if i measure 1 resistance. here, interrupts_enabled will be false. this means no interupts.
            //this means my no_interrupts code will run. so it will always print. so no_interrupts area should run only whe interrupts_enabled is true
          }

          //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
           pulse_counter = 0;
           TIMER1_clear();
           interrupts_enabled = true;
           measurement_finished = false;
           timestamp = millis();  // refresh timer !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      }
     } //loop ends

    /***** INTERRUPT ROUTINES *****/

    void count_time_of_k_pulses()
    {
      if (interrupts_enabled)
      {
        pulse_counter++;

        if (pulse_counter == 1)
          TIMER1_start();

        if (pulse_counter == number_of_samples)
        {
          TIMER1_stop();

          measurement_finished = true;
          interrupts_enabled = false;
        }
      }
    }

    ISR (TIMER1_OVF_vect)
    {
      overflows++;
    }

    /***** FUNCTION FOR SENSOR SELECTION *****/

    void select_sensor()
    {
      digitalWrite(OE_BAR_PIN, HIGH);
      digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
      digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
      digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
      digitalWrite(OE_BAR_PIN, LOW);
    }

    /***** TIMER1 FUNCTIONS (MODIFIED) *****/

    void TIMER1_init()
    {
      TCCR1A  = 0;
      TCCR1B  = 0;
      TIMSK1 |= (1 << TOIE1);
    }

    void TIMER1_start()
    {
       TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    }

    void TIMER1_stop()
    {
      TCCR1B  = 0;
    }

    void TIMER1_clear()
    {
      TCNT1     = 0;
      overflows = 0;
    }

    void TIMER1_print_results()
    {
      Serial.println("----------------------------------------");
      Serial.print("SENSOR COORDINATE         = ");
      Serial.println(sensor_coord);

      //Added the if-else statement, to cover the possibility of open circuited resistance !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      if (sensor_corruption[sensor_coord])
      {
        Serial.println("This resistance is open circuited!!!");
      }
      else
      {
        Serial.print("NUMBER OF PULSES MEASURED = ");
        Serial.println(pulse_counter);

        Serial.print("TIMER1 VALUE              = ");
        Serial.println(TCNT1);

        Serial.print("TIMER1 OVERFLOWS          = ");
        Serial.println(overflows);

        Serial.print("TICKS                     = ");
        Serial.println(ticks);

        Serial.print("MEASURED PERIOD           = ");
        Serial.print(period);
        Serial.println(" US");

        Serial.print("MEASURED RESISTANCE       = ");
        double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
        Serial.print(resistanse);
        Serial.println(" kΩ");

        Serial.println("----------------------------------------");
      }
    }

title: Sending serial data to arduino, while an operation triggered from serial data is underway

Answers: 0


body:
Question is about using ADC AD7606 paired with Arduino (Arduino Mega).
I can’t reach the stated speed of this bundle, the question is also whether it is possible or not. ADC output mode is 16-bit parallel. The physical connection corresponds to that in the examples using Mitov's Visuino. The sensor that sends data to the ADC is AC102-1a, connected via the recommended power supply circuit.

Compiled program code (provided below) that outputs the result of receiving data from one ADC port to the serial port monitor (disabled during speed testing, so as not to slow down the speed of output to the port). Also it has the ability to estimate the speed of the program, as a number of passes of the loop cycle per second.

There were some ways to increase the speed of the Arduino, replacing the standard functions digitalRead, digitalWrite, etc.

The speed of the program, without taking into account the full connection with the ADC (when disabling the waiting BUSY) reaches 150,000+ iterations per second, but if we providing full communication with the ADC (according to the scheme found in the examples of programs with this ADC – the sequence of setting levels on pins READ, BUSY, RESET, etc.), the speed falls to 1700 iterations per second.

This speed is achieved when over-sampling is enabled. If you turn it off, the speed becomes 40000 iterations per second, while increasing the amount of noise in the received signal.

The question is, where is the error in the binding of the ADC command sequence, why is the speed so low, and whether it is possible to achieve an increase in the speed of work, ideally reaching the stated 200k operations per second for this ADC.
<!-- language-all: lang-cpp -->

    #define RESET_PIN 4
    byte pin4mask = (1 << 5);
    #define RESET_SET_OUTPUT      DDRG  |=  pin4mask // Pin 4 OUTPUT
    #define RESET_SET_INPUT       DDRG  &= ~pin4mask // Pin 4 INPUT
    #define RESET_WRITE_HIGH      PORTG |=  pin4mask // Pin 4 to HIGH
    #define RESET_WRITE_LOW       PORTG &= ~pin4mask // Pin 4 to LOW

    #define CHIP_SELECT_PIN 3
    byte pin3mask = (1 << 5);
    #define CHIP_SELECT_SET_OUTPUT      DDRE  |=  pin3mask // Pin 3 OUTPUT
    #define CHIP_SELECT_SET_INPUT       DDRE  &= ~pin3mask // Pin 3 INPUT
    #define CHIP_SELECT_WRITE_HIGH      PORTE |=  pin3mask // Pin 3 to HIGH
    #define CHIP_SELECT_WRITE_LOW       PORTE &= ~pin3mask // Pin 3 to LOW

    #define READ_PIN 2
    byte pin2mask = (1 << 4);
    #define READ_SET_OUTPUT      DDRE  |=  pin2mask // Pin 2 OUTPUT
    #define READ_SET_INPUT       DDRE  &= ~pin2mask // Pin 2 INPUT
    #define READ_WRITE_HIGH      PORTE |=  pin2mask // Pin 2 to HIGH
    #define READ_WRITE_LOW       PORTE &= ~pin2mask // Pin 2 to LOW

    #define START_PIN 6
    byte pin6mask = (1 << 3);
    #define START_SET_OUTPUT      DDRH  |=  pin6mask // Pin 6 OUTPUT
    #define START_SET_INPUT       DDRH  &= ~pin6mask // Pin 6 INPUT
    #define START_WRITE_HIGH      PORTH |=  pin6mask // Pin 6 to HIGH
    #define START_WRITE_LOW       PORTH &= ~pin6mask // Pin 6 to LOW

    #define BUSY_PIN 7
    byte pin7mask = (1 << 4);
    #define BUSY_SET_OUTPUT      DDRH  |=  pin7mask // Pin 7 OUTPUT
    #define BUSY_SET_INPUT       DDRH  &= ~pin7mask // Pin 7 INPUT
    #define BUSY_WRITE_HIGH      PORTH |=  pin7mask // Pin 7 to HIGH
    #define BUSY_WRITE_LOW       PORTH &= ~pin7mask // Pin 7 to LOW
    #define BUSY_READ            bitRead(PINH, 4)

    //PIN 14
    byte pin14mask = (1 << 1);
    #define DB1_SET_INPUT       DDRJ  &= ~pin14mask // Pin D14 to INPUT
    #define DB1_READ            bitRead(PINJ, 1)

    //PIN 15
    byte pin15mask = (1 << 0);
    #define DB2_SET_INPUT       DDRJ  &= ~pin15mask // Pin D15 to INPUT
    #define DB2_READ            bitRead(PINJ, 0)

    //PIN 16
    byte pin16mask = (1 << 1);
    #define DB3_SET_INPUT       DDRH  &= ~pin16mask // Pin D16 to INPUT
    #define DB3_READ            bitRead(PINH, 1)

    //PIN 17
    byte pin17mask = (1 << 0);
    #define DB4_SET_INPUT       DDRH  &= ~pin17mask // Pin D17 to INPUT
    #define DB4_READ            bitRead(PINH, 0)

    //PIN 18
    byte pin18mask = (1 << 3);
    #define DB5_SET_INPUT       DDRD  &= ~pin18mask // Pin D18 to INPUT
    #define DB5_READ            bitRead(PIND, 3)

    //PIN 19
    byte pin19mask = (1 << 2);
    #define DB6_SET_INPUT       DDRD  &= ~pin19mask // Pin D19 to INPUT
    #define DB6_READ            bitRead(PIND, 2)

    //PIN 20
    byte pin20mask = (1 << 1);
    #define DB7_SET_INPUT       DDRD  &= ~pin20mask // Pin D20 to INPUT
    #define DB7_READ            bitRead(PIND, 1)

    //PIN 21
    byte pin21mask = (1 << 0);
    #define DB8_SET_INPUT       DDRD  &= ~pin21mask // Pin D21 to INPUT
    #define DB8_READ            bitRead(PIND, 0)

    //PIN 22
    byte pin22mask = (1 << 0);
    #define DB9_SET_INPUT       DDRA  &= ~pin22mask // Pin D22 to INPUT
    #define DB9_READ            bitRead(PINA, 0)

    //PIN 23
    byte pin23mask = (1 << 1);
    #define DB10_SET_INPUT       DDRA  &= ~pin23mask // Pin D23 to INPUT
    #define DB10_READ            bitRead(PINA, 1)

    //PIN 24
    byte pin24mask = (1 << 2);
    #define DB11_SET_INPUT       DDRA  &= ~pin24mask // Pin D24 to INPUT
    #define DB11_READ            bitRead(PINA, 2)

    //PIN 25
    byte pin25mask = (1 << 3);
    #define DB12_SET_INPUT       DDRA  &= ~pin25mask // Pin D25 to INPUT
    #define DB12_READ            bitRead(PINA, 3)

    //PIN 26
    byte pin26mask = (1 << 4);
    #define DB13_SET_INPUT       DDRA  &= ~pin26mask // Pin D26 to INPUT
    #define DB13_READ            bitRead(PINA, 4)

    //PIN 27
    byte pin27mask = (1 << 5);
    #define DB14_SET_INPUT       DDRA  &= ~pin27mask // Устанавливаем пин D27 в режим INPUT
    #define DB14_READ            bitRead(PINA, 5)

    //PIN 28
    byte pin28mask = (1 << 6);
    #define DB15_SET_INPUT       DDRA  &= ~pin28mask // Устанавливаем пин D28 в режим INPUT
    #define DB15_READ            bitRead(PINA, 6)

    //PIN 29
    byte pin29mask = (1 << 7);
    #define DB16_SET_INPUT       DDRA  &= ~pin29mask // Устанавливаем пин D29 в режим INPUT
    #define DB16_READ            bitRead(PINA, 7)

    #define OS2 10
    #define OS1 9
    #define OS0 8
    #define RANGE_PIN 11

    const long interval = 1000;

    unsigned long previousMillis = 0;
    unsigned long counter01 = 0;

    void setup() {
      Serial.begin(9600);
      DB1_SET_INPUT;
      DB2_SET_INPUT;
      DB3_SET_INPUT;
      DB4_SET_INPUT;
      DB5_SET_INPUT;
      DB6_SET_INPUT;
      DB7_SET_INPUT;
      DB8_SET_INPUT;
      DB9_SET_INPUT;
      DB10_SET_INPUT;
      DB11_SET_INPUT;
      DB12_SET_INPUT;
      DB13_SET_INPUT;
      DB14_SET_INPUT;
      DB15_SET_INPUT;
      DB16_SET_INPUT;

      RESET_SET_OUTPUT;
      CHIP_SELECT_SET_OUTPUT;
      READ_SET_OUTPUT;
      START_SET_OUTPUT;
      pinMode (RANGE_PIN, OUTPUT);
      BUSY_SET_INPUT;

      RESET_WRITE_HIGH;
      delayMicroseconds(10);
      RESET_WRITE_LOW;

      CHIP_SELECT_WRITE_HIGH;
      READ_WRITE_HIGH;
      START_WRITE_HIGH;

      //Setting Oversampling Pins to Zero.
      digitalWrite(OS2, HIGH);
      digitalWrite(OS1, HIGH);
      digitalWrite(OS0, HIGH);

      digitalWrite(RANGE_PIN, HIGH);
    }

    void loop() {

      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        Serial.println( counter01 );
        counter01 = 0;
      }
      counter01 = counter01 + 1;

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

      RESET_WRITE_HIGH;
      delayMicroseconds(1);
      RESET_WRITE_LOW;
      START_WRITE_LOW;
      START_WRITE_HIGH;

      while (BUSY_READ != LOW);
      CHIP_SELECT_WRITE_LOW;

      for (int AChannel = 0; AChannel < 1; ++AChannel)
      {
        READ_WRITE_LOW;
        uint16_t AResult = 0;
        if(DB1_READ == HIGH)
        { AResult |= ( 1 << 0 );}
        if(DB2_READ == HIGH)
        { AResult |= ( 1 << 1 );}
        if(DB3_READ == HIGH)
        { AResult |= ( 1 << 2 );}
        if(DB4_READ == HIGH)
        { AResult |= ( 1 << 3 );}
        if(DB5_READ == HIGH)
        { AResult |= ( 1 << 4 );}
        if(DB6_READ == HIGH)
        { AResult |= ( 1 << 5 );}
        if(DB7_READ == HIGH)
        { AResult |= ( 1 << 6 );}
        if(DB8_READ == HIGH)
        { AResult |= ( 1 << 7 );}
        if(DB9_READ == HIGH)
        { AResult |= ( 1 << 8 );}
        if(DB10_READ == HIGH)
        { AResult |= ( 1 << 9 );}
        if(DB11_READ == HIGH)
        { AResult |= ( 1 << 10 );}
        if(DB12_READ == HIGH)
        { AResult |= ( 1 << 11 );}
        if(DB13_READ == HIGH)
        { AResult |= ( 1 << 12 );}
        if(DB14_READ == HIGH)
        { AResult |= ( 1 << 13 );}
        if(DB15_READ == HIGH)
        { AResult |= ( 1 << 14 );}
        if(DB16_READ == HIGH)
        { AResult |= ( 1 << 15 );}

        READ_WRITE_HIGH;

        float AValue = float( int16_t( AResult ));
        if ( ! AChannel )
        {
          //Serial.println( AValue );
        }
      }
      CHIP_SELECT_WRITE_HIGH;
    }

title: Problem connecting Arduino and ADC AD7606

Answers: 0


body:
I am having a problem with the analog readings on my Due. On pin A4 and A5 I am measuring voltages:

    double vcc = 3.288  // taken on pin 75 (ADVREF) ;
    analogReadResolution(12);
    result = analogRead(A4) * (vcc / 4095);   // result = 0.47+- 0.01      actual reading = 0.429
    result = analogRead(A5) * (vcc / 4095);   // result = 0.49+- 0.01      actual reading = 0.555

As you may see I could not simply offset the value because both have very different offset: one is positive and the other is negative. The reading is off by 0.05v, which is inaccurate for a 12-bit ADC that offers 0.000805v resolution, almost a 1000x inaccuracy.

Is there any way to calibrate `analogRead` further without using additional external components on the pin?

title: How to calibrate Arduino DUE analog readings?

Answers: 0


body:
I was wondering is there a way to calculate SpO2 using a pulse sensor?
I calculated BPM and stress before with pulse sensor and now I want to calculate SpO2.

Link to Pulse sensor [manual][1]

  [1]: https://www.generationrobots.com/media/DetecteurDePoulsAmplifie/PulseSensorAmpedGettingStartedGuide.pdf

title: Calculating SpO2 using pulse sensor

Answers: 1

body:
For measuring oxygen saturation (SpO2) with a pulse sensor, you need to use the fact, that hemoglobin, that carries oxygen, will reflect in different light wave lengths, as hemoglobin, which doesn't carry oxygen. But that also means, that you need to use light in at least 2 different wavelengths. Common are one red (about 660nm)(though green may also work) and infrared (about 940nm). When lighted sequentially with both LEDs, you can measure the refection of both parts and calculate the ratio between them (SpO2).

But your sensor only has 1 LED, which is green. So you cannot measure SpO2 with this sensor. You need one fitting the above description.


body:
I have started learning about Arduino and am well versed in Java and Python. In an Arduino program, I need a character input via Serial to be stored in a String variable. From my previous programming experience, I knew that a code like the one below would give an error as char can't be converted into String like this.

```
void loop() {
  if(Serial.available()) {
     String s=(char)Serial.read();
  }
}
```

As expected, the above code gives an error on compiling. But when I first defined `s` and then assigned its value in a separate step in `void loop()`, I got no error.

```
void loop() {
  if(Serial.available()) {
     String s;
     s=(char)Serial.read();
  }
}
```

The above code yields no error despite the fact that it is almost similar to the first code. What I suspect is that it has something to do with String being a class. Can one tell what is going on?

title: char to String conversion in Arduino program

Answers: 4

body:
I don't have much experience with Arduino's `String` type, however, most people (including myself) don't advise to use it. Because the Arduino only has 1 KB of SRAM and the `String` type has its own hidden memory allocation, you might run out of memory without you know it, resulting in crashing/frozen programs without a clue what is happening.

Instead use character arrays (like `char str[10]`) where you know exactly what is reserved.

However, to answer your question, what I expect since `String` is a class, there is a (copy) constructor in that class that takes a `char` and converts it into a `String`.

body:
this isn't an arduino specific error what you're trying to do is declare and initialize the variable in one statement which is causing the problem. As you've figured it out already. Declaring the variable first
```
String s;

```
and initializing it another statement does the job for you
```
s=blabla
```

Hope this helps. PS, try posting the error that you get during build process next time :)

**EDIT**:
 I think this needs more explanation. Basically why you cant declare and initialize at the same time in this case is because Serial.read is a synchronous request. Declaring an object requires acquiring the space for it, running any constructors and whatsoever, and doing while Serial.read() is an IO blocking operation. You could declare and initialize a String class variable given it was a string constant but not with anything like get_input or Serial.read

**EDIT 2**:
Further here's what I've found for you.

http://www.cplusplus.com/reference/string/string/string/

Apparently the  String class has a copy constructor which means when declaring the variable you initialize at the same time it uses the copy constructor, and which requires ADDRESS to a valid string(know that you can use a constant because C++ deals with all strings as the address to their first char). In your case the constructor raised an error because you pointed it to an undefined(Serial.read() ).
```
String mystring=Serial.read(); //error, uses copy constructor
```
However this would work
```
String mystring="hey juliet!" ; //uses the copy contructor which takes address to a char

```
Doing the same thing in two different lines works for the same reasons, it uses a different constructor

```
String mystring; //uses empty string constructor - okay so far
mystring=Serial.read(); // uses the overloaded = operator  --okay

```

body:
You misunderstand `Serial.read()`: it does not return a `String` or sth. like a char array, but an integer, representing only the last byte in the input buffer that hasn't been read.

What you probably want to do is to interpret those incoming bytes as `char`s and accumulate those in a `String`.

E.g. like this:

    String s="";
    while(Serial.available()) {
      // as long as there are bytes in the buffer
      s+=(char)Serial.read(); // interpret int as char and append character to s
    }

As using `String` can easily lead to crashes you should avoid dynamic memory allocation by using a fixed-size char arrays:

    #define MAX_LEN 64
    char s[MAX_LEN];
    uint8_t i;
    while (serial.available() && i<MAX_LEN) {
      s[i]=(char) Serial.read();
      i++;
    }

Note: once you are that far you still have to handle, when you want the data to be ready to process (e.g. detecting a `\n` and setting a flag appropriately).

body:
This will fix the problem:
`void loop() {
  if(Serial.available()) {
     String s=(char*)Serial.read();
  }
}`
This is because in C: Strings are defined as an array of characters.
You cannot assign a primitive to an array...

I guess the casting into pointer can be implicit as in your second example..


body:
I am very very new to ESP Programming.

I am trying to store Strings into EEPROM of ESP8266.
I am storing the string into eeprom successfully but while reading it from EEPROM extra character 'd' is coming into the picture. I assumed it is a character to end the string but it does being used into the String url and the further code of connecting to server is throwing error due to wrong URL.
My question is how to resolve this issue.

    void writeString(int addr, String data)
    {

       uint8_t size = data.length();
       for (uint8_t i = 0; i < size; i++) {
          EEPROM.write(addr + i, data.charAt(i));
       }
       EEPROM.write(addr + size, '\0');
       EEPROM.commit();

    }

    String read_String(int addr)
    {

      String result = "";
      uint8_t count = 0;
      while (true) {
         char byte = EEPROM.read(addr + count);
         if (byte == '\0') {
           break;
         }
         else {
           result.concat(byte);
         }
      count++;
      }

     result = result.substring(0, (result.length()));
     return result;

    }

**Function Calling Snippet:**

    //Writting to EEPROM
    String inputMessage1 = "myurl.co.in";
    writeString(10, inputMessage1);

    //READING from EEPROM
    String hostStr = read_String(10);
    Serial.print( "Connecting to Server... "+hostStr);

**OUTPUT**

    Connecting to Server... myurl.co.ind

title: ESP8266 EEPROM Reading extra character

Answers: 0


body:
I wonder if can use the Arduino Nano SPI-pins(MOSI,MISO & SCK) as I/O pins in a sketch? and still be able to program over ISP?

Of course I will physical disconnect the Arduino from any other hardware before programming.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/z4yAP.png

title: Arduino Nano use SPI pins as I/O pins? and still be able to do ISP?

Answers: 1

body:
Yes, you can use SPI in your sketch just as you like. The programming over ISP is triggered by resetting the microcontroller. That means, that when trying to program over ISP your sketch (which configures the SPI hardware for use) doesn't run. The programming is starting at a stage, before the sketch runs, thus the sketch cannot interfere.

By the way: The same is correct for programming over Serial, though for a different reason. Programming over Serial is done by the bootloader, which runs before your sketch.


body:
I am stuck reading A1335 sensor through SPI. I have asked on the Aduino forum under the "Networking.." topic but no one is helping.
[Link to other forum post][1]
I have changed the code so many times now that I am completely confused. Noob at understanding the data sheet, my problem mite have something to do with timing. Noob at SPI , I think my arduino-SPI code is where I went wrong.
Almost certain my wiring is good.
latest code:
```
/* ******************************************************************************
 *  SPI read 3x A1335 rotation sensor chips with UNO and display on serial monitor
 *  Slave select pins 10 >ss1, 9 >ss2, 8 >ss3
 */
#include <SPI.h>

  // set slave pins and variables
  const int ss1 = 10;
  const int ss2 = 9;
  const int ss3 = 8;
  uint16_t Ang_ss1 = 0;
  uint16_t Ang_ss2 = 0;
  uint16_t Ang_ss3 = 0;

/*SPI settings here and not declared globaly for attaching different
  spi devices with difrent settings. Call transaction,begin with new
  settings*/

SPISettings settingsA(10000000,MSBFIRST,SPI_MODE3); //mode and 10mHz from manual, MSBfirst is a guess

void setup() {
   //set slave pins High and as outputs

  pinMode (ss1,OUTPUT);
  digitalWrite (ss1,HIGH);
  pinMode (ss2,OUTPUT);
  digitalWrite (ss2,HIGH);
  pinMode (ss3,OUTPUT);
  digitalWrite (ss3,HIGH);

  //set up register once and receive data in loop
  SPI.begin();
  Serial.begin(9600); //in different post it's said Serial.begin must be before SPI.begi......true or false
  SPI.beginTransaction(settingsA);
  digitalWrite (ss1,LOW);
  SPI.transfer(0x20);
  SPI.transfer(0);
  digitalWrite(ss1,HIGH);
  SPI.endTransaction();

}

void loop() {

SPI.beginTransaction(settingsA);

//select sensor 1 to 3 and read registers 0x20 and 0x21 after I get First 1 working

digitalWrite (ss1,LOW);      // sensor one read and store two bite data in ANG_ss1
//Ang_ss1 = SPI.transfer(0x20); //0x20 and 0x21 angle register
Ang_ss1 = SPI.transfer(0); // receive data 0x20 high byte
Ang_ss1 = <<8;
Ang_ss1 |= SPI.transfer(0);//receive low byte
digitalWrite(ss1,HIGH);

SPI.endTransaction();

//De-bug code: display values from sensors
Serial.print(Ang_ss1,BIN);              //Serial.print Ang_ss1 in binary
Serial.println(" ss1     ");
Ang_ss1 = <<4;  //firs 4 bytes are not part of angle
Ang_ss1 = >>4;
Serial.print(Ang_ss1);Serial.println(" ss1 shifted");

Serial.print(Ang_ss1 * 360/4096 );  // formula from programming manual for sensor removed brackets from '(360/4096)'
Serial.println(" DEG   ");

delay (1000);                       // to read serial monitor for debugging
}
```
The relevant data sheet and programming manual is linked in **link** up top. There's only 3 relevant pages in programming manual, page 21-23.
Also a video of output to serial monitor and garble I got on my oscilloscope.
Will only be back home tomorrow to test latest code on oscilloscope.

new [Video][2] of whats going on. New code uploaded but same problems.
Reminder data sheet and such in link at start of post.

Progress: seems uno 5V out not enough for three sensors. I am getting better results with just one. here is a [video][3] Still need help with code please

Confirmed can only run 1x SPI and when using I2C it becomes buggy with 2x sensors but one works a treat.
new [Video][4]
And code:
```
/* ******************************************************************************
 *  SPI read 3x A1335 rotation sensor chips with UNO and display on serial monitor
 *  Slave select pins 10 >ss1, 9 >ss2, 8 >ss3, UNO: SCL 13, Miso 12, mosi 11.
 *                                                  pink     yelo       orange
 **********************************************************************************/
#include <SPI.h>

  const int ss1 = 10; const int ss2 = 9; const int ss3 = 8;          //slave select pins
  uint16_t Ang_ss1 = 0;  uint16_t Ang_ss2 = 0; uint16_t Ang_ss3 = 0; //store 16bit register
  float Chip1; float Chip2; float Chip3;                             //after math valaue with commas( deg out of 360)

  SPISettings settingsA(10000000,MSBFIRST,SPI_MODE3);               //Spi settings

void setup() {

  pinMode (ss1,OUTPUT);                       //set slave pins High and as outputs
  digitalWrite (ss1,HIGH);
  pinMode (ss2,OUTPUT);
  digitalWrite (ss2,HIGH);
  pinMode (ss3,OUTPUT);
  digitalWrite (ss3,HIGH);

  Serial.begin(9600);
  SPI.begin();

}

void loop() {

SPI.beginTransaction(settingsA);

//select sensor 1 and read 0x20 and 0x21 registers

digitalWrite (ss1,LOW);                          // sensor one read and store two bite data in ANG_ss1
Ang_ss1 = SPI.transfer(0x20);                              //0x20 and 0x21 angle register
Ang_ss1 = Ang_ss1 <<8;
Ang_ss1 |= SPI.transfer(0);                               //receive low byte 0x21
digitalWrite(ss1,HIGH);

SPI.endTransaction();

Ang_ss1 = Ang_ss1 <<4;                                    //first 4 bytes are not part of angle
Ang_ss1 = Ang_ss1 >>4;
Chip1 = (float) Ang_ss1 / 16;                             // change binary to desimal
Chip1 = (float)Ang_ss1 /4096.0 * 360.0;                  //  formula in manual is n*(360/4096)

Serial.print(Chip1);
Serial.println(" DEG   ");

//delay (2000);                       // to read serial monitor for debugging

}
```

  [1]: https://forum.arduino.cc/index.php?topic=671666.0
  [2]: https://youtu.be/Pfc9XWMC2xc
  [3]: https://www.youtube.com/watch?v=cinWOV9JqD0
  [4]: https://studio.youtube.com/video/lwUd1JU6t8A/edit

title: Whats wrong with my SPI code using uno?

Answers: 0