body:
I'm building a state machine using 6 flip-flopsD, and an G input coming from an infrared sensor. This circuit should count from 0-35.
The problem is that it always starts in state 111111. That is, after it passes through Flip-flop D A, B, C, D, E, F = 1;

Here's my code:

    #include "flipflopD.h"

    boolean a1,b1,c1,d1,e1,g1;//display 1
    boolean a2,b2,c2,d2,e2,f2,g2;//display 2
    boolean Aa=false;
    boolean Bb=false;
    boolean Cc=false;
    boolean Dd=false;
    boolean Ee=false;
    boolean Ff=false;
    boolean A=false;
    boolean B=false;
    boolean C=false;
    boolean D=false;
    boolean E=false;
    boolean F=false;
    boolean G=false;//receiver

    void setup() {

        //DISPLAYS
        pinMode(A0, OUTPUT);
        pinMode(2, OUTPUT);
        pinMode(3, OUTPUT);
        pinMode(4, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(6, OUTPUT);
        pinMode(7, OUTPUT);
        pinMode(8, OUTPUT);
        pinMode(9, OUTPUT);
        pinMode(10, OUTPUT);
        pinMode(11, OUTPUT);
        pinMode(12, OUTPUT);
        pinMode(13, OUTPUT);

        pinMode(A2, INPUT);// IR RECEIVER
    }

    void loop() {
        //  Counter
        G = digitalRead(A2);
        Aa = flipflopD((A||!B||!C||!D && !A||B||C||D||E||F||G), A, G);
        Bb = flipflopD((!A||B||!C||G && !A||B||F||!G && !A||B||E||!F && !A||B||D||!E && !A||B||C||!D && !A||!B||C||D||E||F||G), B, G);
        Cc = flipflopD((!A||C||!D && !A||C||!E && !A||C||!F && !A||C||!G && !A||!C||D||E||F||G), C,G);
        Dd = flipflopD((!A||D||!E && !A||D||!F && !A||D||!G && !A||!B||!C||D && !A||!D||E||F||G && !A||!B||C||!E||!F||!G), D, G);
        Ee = flipflopD((!A||E||!F && !A||E||!G && !A||!E||F||G && A||!B||!C||!D||E && !B||!C||!D||!E||F||G), E, G);
        Ff = flipflopD((!A||!F||G && !A||F||!G && !B||!C||!D||!F||G && !B||!C||!D||F||!G && A||!B||!C||!D||E||G), F, G);

        A=Aa;
        B=Bb;
        C=Cc;
        D=Dd;
        E=Ee;
        F=Ff;

        //   ABCDEF TO 7 Segments
        a1 = !A||B||D && !A||B||C & A||!B||!C||!D;
        b1 = !A||B && !A||C||E && !A||C||D && A||!B||!C||!D;
        c1 = !A||!B||C||E && !A||!B||C||D && !A||C||D||E && !A||B||!C||!D + A||!B||!C||!D;
        d1 = !A||B||D && !A||B||C && A||!B||!C||!D;
        e1 = !A||B||!C||D && !A||B||D||!E && !A||B||C||!D;
        g1 = !A||B||D && !A||B||C & A||!B||!C||!D;

        a2 = (!A||!C||E  &&  !A||!B||!D||!F  &&  !A||!B||D||F && !A||!B||C||!E && !A||C||D||!E && !A||B||!C||!F && !A||B||!D||F && !A||B||E||!F && !B||!C||!D||E||F && A||!B||!C||!D||!E);
        b2 = (!A||B||D && !B||!C||!D||!E && !B||!C||!D||!F && !A||!B||!E||!F && !A||!C||!D||F && !A||!C||!D||E && !A||!C||E||F && !A||!D||E||F && !A||!B||C||!E && !A||!B||C||!F && !A||C||!E||!F);
        c2 = (!A||F && !A||!D||!E && !A||C||E && !A||B||!D && !A||B||!E && !B||!C||!D||F && !A||!B||!C||D && A||!B||!C||!D||E);
        d2 = (!A||!B||!C||!D||!F && !A||!B||!C||E||!F && !B||!C||!D||E||F && !A||!C||D||!E||F && !A||!B||C||!D||!E && !A||!B||C||!E||!F && !A||C||!D||!E||!F && !A||!B||C||E||F && !A||C||!D||E||F && !A||C||D||E||!F && !A||B||!C||!E||F && !A||B||!D||E||!F && !A||B||!C||D||!E && !A||B||!C||D||F && !A||B||D||!E||F && A||!B||!C||!D||!E);
        e2 = (!A||!C||!D||!F && !A||!C||E||!F && !A||!D||E||!F && !A||B||D||!F && !B||!C||!D||!E||!F && !A||!B||C||!E||!F);
        f2 = (!A||!C||!E||!F && !A||C||!D||!E && !A||C||E||!F && !A||B||C||!E && !A||!B||!C||D||!E && !A||!B||!C||D||!F && !A||!B||C||D||E && !A||B||!C||!D||E && A||!B||!C||!D||E);
        g2 = (!A||C||!E && !A||!C||!D||E && !A||!C||E||!F && !A||!B||D||!E && !A||!B||C||D && !A||B||!D||!F && !A||B||!C||E && A||!B||!C||!D);

        // OUTPUTS

        //DISPLAY 2
        digitalWrite(A0,a2);
        digitalWrite(2,b2);
        digitalWrite(3,c2);
        digitalWrite(4,d2);
        digitalWrite(5,e2);
        digitalWrite(6,f2);
        digitalWrite(7,g2);

        //DISPLAY 1
        digitalWrite(8,a1);
        digitalWrite(9,b1);
        digitalWrite(10,c1);
        digitalWrite(11,d1);
        digitalWrite(12,e1);
        digitalWrite(13,g1);
    }

Here's my Flip-FlopD:

    boolean flipflopD(boolean D, boolean Q, boolean CLK){
      boolean Qo=false;
        if (CLK=true) {
          Qo=D;
        } else {
      Qo=Q;
      }
      return Qo;
    }

Can someone tell me what's wrong?

title: Arduino - Finite State Machine does not start in the initial state

Answers: 1

body:
One potential error source: In your D-Flip-Flop code, you have

    boolean flipflopD(boolean D, boolean Q, boolean CLK){
      boolean Qo=false;
        if (CLK=true) {
          Qo=D;
        } else {
      Qo=Q;
      }
      return Qo;
    }

You probably want to do a comparison with double `==` instead of an assignment with `=` in the line

    if(CLK=true)

This causes the `if` to always evaluate to `true` and set `Qo=D`.

Also, I am not really sure if this is what you want:

    a1 = !A||B||D && !A||B||C & A||!B||!C||!D;

First, you're mixing `&&` (logical-and) with the bitwise `&` here. Next, C++ [operator precedence][1] dictates that the `&& `has a higher priority than `||`. This looks like a conjunctive-normal-form of some boolean function, thus I would group the AND terms in parenthesis, like

    a1 = (!A||B||D) && (!A||B||C) && (A||!B||!C||!D);

In the `c1` expression you are also suddenly using the `+` operator in a chain of logical expressions, which looks wrong.

Overall I don't quite get how this should work. If you have an IR receiver connected to A2, from which you read the "CLK" input, it will get some 39kHz input wave when you point a IR remote at it and press a button. And you want that on each CLK rise/fall the Arduino reacts to it by calculating the output for a seven-segment display? Your Arduino Uno/Nano with its 16MHz will take some time to execute each of the statements in the loop, sequentally. So what you're doing is actually sampling the A2 input every now and then -- how often exactly, I don't know, maybe with a few kilohertz. Your Arduino might sample the input at the wrong time or not fast enough to react the way you expect. `digitalRead` and `digitalWrite` are notoriously slow, maybe try direct port access or an interrupt-based approach. Of course, calculating all these AND, OR and NOT expressions will take some processing time, too.

This sort of combinational logic is more suited for an FPGA implementation, not for an Arduino.

  [1]: https://en.wikipedia.org/wiki/Operators_in_C_and_C++#Operator_precedence


body:
I've often seen `cli()` and `sbi()` in Arduino code. I usually don't mind them as I know what they do (clear or set the bit given as second argument in the register of the microcontroller given as first). I've always thought that those functions where only a clear way to perform simple bit manipulation, which can be quite error-prone. Something like that:
`#define cli(reg,bit) (*reg &= ~(1 << bit) ` and `#define sbi(reg,bit) (*reg |= (1 << bit))`.

Then I found out that the actual implementation is as follows:

    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

It's quite like I used to think... but with two extra macros.
I looked for them in the Arduino libraries:

    #define _BV(bit) (1 << (bit))

and

    #define _SFR_BYTE(sfr) _MMIO_BYTE(_SFR_ADDR(sfr))

which contains

    #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

and

    #if _SFR_ASM_COMPAT
    #if (__SFR_OFFSET == 0x20)
    #define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)
    #elif !defined(__ASSEMBLER__)
    #define _SFR_ADDR(sfr) (_SFR_IO_REG_P(sfr) ? (_SFR_IO_ADDR(sfr) + 0x20) : _SFR_MEM_ADDR(sfr))
    #endif
    #else  /* !_SFR_ASM_COMPAT */
    #define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)

Further research took me to definitions I couldn't understand (for example because they are explained in comments using a lot of acronyms I don't know).
So I have the following questions:

* Why is `sfr` casted to `*(volatile uint8_t *)`?
* What do the acronyms used in that code mean? (`ASM`, `SFR`, `MMIO`)
* Under what circumstances is `__ASSEMBLER__` defined, and where (in which file)?
* Why can't we simply write `#define cli(reg,bit) (*reg &= ~(1 << bit) ` and `#define sbi(reg,bit) (*reg |= (1 << bit))`?

title: sbi() and cli() implementation

Answers: 2

body:
> Why is sfr casted to *(volatile uint8_t *)?

Because you want the *content* (the first `*`) of a memory address that you specify, and you need it volatile so it doesn't cache it. Oh, and it's an 8-bit value.

> What do the acronyms used in that code mean? (ASM, SFR, MMIO)

ASseMbly, Special Function Register and Memory Mapped Input/Output

* ASM means assembly language.
* A Special Function Register is something like DDRB.
* Memory Mapped IO is a way of interacting with peripherals by reading from and writing to locations in the normal memory address space.

> Under what circumstances is `__ASSEMBLER__` defined, and where (in which file)?

It is defined by the compiler when you are compiling an assembly file.

> Why can't we simply write `#define cli(reg,bit) (reg &= ~(1 << bit)` and `#define sbi(reg,bit) (reg |= (1 << bit))`?

Because `reg` is just an address. You need to convert that into a variable in memory that you can reliably access (hence the *volatile*). Further to that, not all chips use MMIO for all peripherals - some can be accessed by more efficient IO instructions. That said, in many cases yes you can just use simpler code. After all, things like `DDRB |= 0x04` works fine. It all depends on how the value to pass as `reg` is defined originally. By forcing a specific `volatile` cast you can ensure that whatever way it was defined (with or without volatile, etc) it will work.

body:
On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).

As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.

From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

* One would compile to the fastest and most efficient instruction(s) available for that particular IO address.

* One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f

* One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.

* One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant [which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f].


body:
I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/9yFJI.png)

<!-- End schematic -->

The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.

title: Getting the voltage of an 18650 battery with an Arduino

Answers: 1

body:
Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:

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

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

  [1]: https://i.stack.imgur.com/ANX1b.png
  [2]: https://i.stack.imgur.com/1zNkF.png


body:
i am working in arduino fingerprint sensor with adafruit. i am using two leds to check if fingerprint is valid. my problem is that i need three cases instead of two.
1 case: when fingerprint is valid. turn on green led and turn off red led.
2 case: when fingerprint is not valid. turn on red led and turn off green led. i put a finger but was a not valid finger.
3 case: when there is no finger detected, turn off both leds.
Is there a way to do that?

i am using adafruit library and fingerprint sensor, with fingerprint.ino and using pin 11 and 12 for output.

title: How can i check for valid fingerprint and no finger detected?

Answers: 1

body:
When there is no finger on the sensor, the function `Adafruit_Fingerprint.getImage()` from the Adafruit Fingerprint library returns the constant `FINGERPRINT_NOFINGER`. You can execute the function in a loop and setting the LED outputs in a `switch` statement according to the return value. Refer to the examples of the [Adafruit Fingerprint Sensor Library][1]. There you have directly the code for checking the sensor (since the full check for a valid fingerprint is longer than this one function call, you can use the `getFingerprintIDez()` function from the `fingerprint` example, or a variation of it).

  [1]: https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library


body:
I am trying to develop an Home automation system using Arduino and ESP8266 Module. But stuck at the very first step while checking is esp8266.available() available or not. This function always returns FALSE. Looking for solution. Thanks in advance.

**CONNECTION**

    Vcc -----> 3.3
    CH_PD ---> Vcc
    RX ------> 2 (Arduino pin)
    TX ------> 3 (Arduino pin)
    GND -----> GND (Arduino)

**CODE**

 #include <SoftwareSerial.h>
 #define DEBUG true
 SoftwareSerial esp8266(2,3);

 void setup(){
  Serial.begin(9600);   // Setting the baudrate to 9600
  esp8266.begin(9600);  // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
  pinMode(11,OUTPUT);   // Setting the pin 11 as the output pin.
  digitalWrite(11,LOW); // Making it low.
  pinMode(12,OUTPUT);   // Setting the pin 12 as the output pin..
  digitalWrite(12,LOW); // Making pin 12 low.
  pinMode(13,OUTPUT);   // Setting the pin 13 as the output pin.
  digitalWrite(13,LOW); // Making pin 13 low.
  sendData("AT+RST\r\n",2000,DEBUG);            //This command will reset module to default
  sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure the mode as access point
  sendData("AT+CIFSR\r\n",1000,DEBUG);          // This will get ip address and will show it
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the ESP8266 for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This will set the server on port 80
 }

 void loop(){
  if(esp8266.available()){  // ALWAYS FALSE
   // My codes
  }
 }

----------

**UPDATE**

At the very first run time, the function is returning TRUE and showing an error

    deprecated conversion from string constant to char wwrite strings arduino esp8266.find("+IPD,")
for line number

title: Why does the function esp8266.available() always returns FALSE?

Answers: 0


body:
I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:

Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.

Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.

If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).

Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.

Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?

Thanks!

EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

title: How to delay properly inside ISR

Answers: 1

body:
It's quite simple: You don't.

Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.

When the chosen time has passed the timer interrupt triggers, and you use *that* interrupt to turn on your output.


body:
I'm beginner here at arduino stuff. i just started learning arduino and i have this small homework where i NEEDED to connect 2 arduino using ethernet shield or module ONLY over a distance of 20 meters.

I don't have my modules yet but i want to atleast study it now while i'm waiting for it. I can't seem to see any tutorials about it nor anyone tried it. How can i do this? i hope you can help me and give some insights, links, etc reference. Thanks :)

EDIT:
I had in mind where these arduino will have their own identity, 1st arduino will be receiving only some data coming from 2nd arduino. The 2nd arduino will have sensors and read them then sends them to 1st arduino. Now, i like my 2nd arduino to have a power source coming from the 1st arduino to save power supply installation and since it'll be like a remote arduino. Thus has anyone has experience applying PoE on arduino?

title: Peer to Peer using Ethernet Module

Answers: 1

body:
You will need a [crossover cable][1] to connect two Ethernet shields peer to peer.

Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.

  [1]: https://en.wikipedia.org/wiki/Ethernet_crossover_cable


body:
I need to achieve that in every loop my Arduino do other thing. Say in first loop do one thing, in second do second thing and in third loop do third thing. And again. And while doing one thing, other things are dead.

Not sure what approach to use.
This is just my 50 cents:

    for(int x=0; x<2; x++)
      {
      switch (x) {
        case 0:
          //do something
          break;
        case 1:
          //do something
          break;
        case 2:
          //do something
          break;
      }
      delay(1);
    }

I tried this from above but it stuck at case 0

Any point or link to explanation would be nice.

title: Every loop other case

Answers: 2

body:
Your implementation is in principle correct. However, tradionally, you don't incrementally loop over all states from 0 to end using a `for` loop. The implementation is more flexible if it allows the state to go to any other state if it needs to. This would be a normal *finite state machine* (FSM).

    #include <Arduino.h>
    /* How many states are possible? */
    #define MAX_STATES 2
    /* global state variable */
    int currentState = 0;

    /* prototypes */
    void Action1();
    void Action2();

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

    void AdvanceStateByOne() {
     currentState = (currentState + 1) % MAX_STATES;
    }

    void loop() {
     //Execute the action dictated by the current state
     switch(currentState) {
      case 0:
       Action1();
       break;
      case 1:
       Action2();
       break;
      default: //Catch for un-implemented states
       break;
     }
     //Go to next state, incrementally.
     //This could also be modified in one of the functions above
     //Loop back to zero state after MAX_STATES using modulo operator
     AdvanceStateByOne();

     //for testing, introduce some delay
     delay(1000);
    }

    void Action1() {
     Serial.println("Action 1");
    }

    void Action2() {
     Serial.println("Action 2");
    }

This prints out "Action 1" and "Action 2" in a loop forever.

Now you could take this further and instead of using pure numbers for your states, you can use an `enum` representation of those to make the code clearer:

    enum state_t {
     STATE_DO_ACTION_1 = 0,
     STATE_DO_ACTION_2,
     STATES_END
    } ;

And then act on those accordingly. You can also use the C++ feature of a `enum class` to give you a nice notation like `State::SomeState1`.

body:
>     for(int x=0; x<2; x++)
      {
      switch (x) {
        case 0:
          //do something
          break;
        case 1:
          //do something
          break;
        case 2:
          //do something
          break;
      }
      delay(1);
    }

You will never do case 2, that's for sure, as you are incrementing to **less than** 2.


body:
Im working on a project where i have motor controller(arduino nano) being i2c slave. Its job is to get RF24 data and control motor and at same time send data to master about motor... Currently i have 2 ultrasonic sensors for distance sensing and if they are too close it will stop motor. I want to add 2-4 more but it adds a lot of delay because of

    pulseIn();

command. I want to use attiny as sensor reader and just dump current data when requested.

Is it possible for arduino nano to be i2c slave (hardware i2c) and at same time i2c master (software i2c/please library without using timers... im short on them) or there is way to dump data in less than 2ms via serial or some other protocol? SPI is already used for RF24 and i need RF24 to be up all the time.

title: What is best way to get data from sensors if arduino is slave?

Answers: 1

body:
On simultaneous master/slave: Yes and no. You can initiate the `Wire` library as slave and despite of than using `Wire.beginTransmission()` and it's siblings to send as a master. The library will configure the hardware as master only for the time it needs to send. But there are 2 problems:

 1. When you have multiple masters on the same bus, they have to continuously watch the bus, so that they are only starting a transmission, when the bus is free. The `Wire` library doesn't seem to do that.
 2. If two masters start their transmission at the same time, the data will be good, as long all transmitted bits are equal. For other cases the I2C protocol has a rule: When 2 masters start a transmission at the same time, the first one to write a `1` to the bus (HIGH value) has to immediately back of to slave mode. (This is because to write a `1` to the data line the pullup resistors are used. When another master tries to write `0` to the bus (LOW value on SDA) he wins against the pullups, effectively writing `0` to the port, and not `1`)

As mentioned on this [Github issue][1] there are some workaround, though I haven't tested them myself until now. All in all I2C multi-master may be to complex at this point.

As another option, you can use an extra line, connecting master and slaves (use the internal pullup on the masters side). Any slave can at any time write a `LOW` to this line, triggering the master to request data from all slaves (maybe via external interrupt or pin change interrupt).

Note: I don't know, for what purposes you used all your timers, but maybe there is a way to share one of them with other hardware, so that you don't have to use the blocking `pulseIn()` function. Or maybe you can tweak the timeout value of the function to a fitting value.

  [1]: https://github.com/arduino/Arduino/issues/1313


body:
My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.

I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)

Can someone shed some light as to how I do this?

The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.

Here is what I have.

Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.

    // Setting The Pin Numbers
    const int touchsensor = 2;                      // the number of the touchsensor pin
    const int buzzer =  4;                          // the number of the LED pin

    // variables:
    int touchsensorState = 0;                       // variable for reading the
    touchsensor status
    unsigned long timestamp = 0;
    unsigned long timeout = 1000;

    void setup() {

      pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
      pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
     }
    void loop() {

       touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

       if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
         digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
         timestamp = millis();                       // Timing button press
       }

       if(millis() - timestamp > timeout) {
       digitalWrite(buzzer, LOW);                  // buzzer will not sound:
       }
    }

title: Arduino - Push Button State Problem

Answers: 1

body:
you will need to implement a edge sensor. Add a `previousTouchsensorState` to the globals and replace the if where you check the sensor state with:

    if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
         // check if the touch sensor is pressed and wasn't the last time though the loop.
         // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
         digitalWrite(buzzer, HIGH); // buzzer will emit sound:
         timestamp = millis();       // Timing button press
    }
    previousTouchsensorState  = touchsensorState;


body:
Its my first time make arduino project. I make wemos d1  project using DHT11 temperature sensor and LCD 20x4 with i2c. **The temperature data will display in LCD and sending to the bot telegram.** **For sending to the bot telegram it works, but why the data cannot display to the LCD?** When I tried common charachter like "Hello World!" in the LCD it works. Can you help me? What should I do? Thanks before.

    #include "DHT.h"
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);
    #define DHTPIN D14
    #define DHTTYPE DHT11

    byte degree[8] = {
      0b00110,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000
    };

    DHT dht(D14, DHT11);

    void setup() {
      lcd.createChar(0, degree);
      Serial.begin(115200);
      Serial.println("DHT11 test!");
      lcd.begin (20, 4);
      dht.begin();
    }

    void loop() {
      delay(2000);
      float h = dht.readHumidity();
      float t = dht.readTemperature();

      lcd.setCursor(0, 0);
      lcd.print("Humi : ");
      lcd.print(h);
      lcd.print(" %");

      lcd.setCursor(0, 1);
      lcd.print("Temp : ");
      lcd.print(t);
      lcd.print(" C");
    }

title: DHT 11 sensors and i2c LCD to Wemos Wifi not Working

Answers: 1

body:
Constant `D14` is for Wemos D1 and other esp8266 dev boards mapped in arduino core to esp8266 io pin 4. Pin 4 is used as I2C SDA pin. The LCD uses I2C so pin 4 (D14) can't be used for the sensor.

from `pins_arduino.h` for Wemos D1 R1:

    #define PIN_WIRE_SDA (4)
    #define PIN_WIRE_SCL (5)

    static const uint8_t D14  = 4;
    static const uint8_t D15  = 5;

The origin of this confusing esp8266 io pin to Dx constants mapping is the big Wemos D1. There are esp8266 pins mapped to standard Uno pinout.

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

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


body:
https://i.stack.imgur.com/pbYn6.png

I need to know what the little "thing" that i marked in blue is and how it works.

Thanks.

picture taken here: https://www.sparkfun.com/products/13282

title: WS2812 HELP. Need name of Unkown component

Answers: 3

body:
It's a capacitor. Specifically a decoupling capacitor of somewhere around 100nF to 1uF.

It works by storing an electrical charge in two plates with a dielectric between them. That specific type is a Multi-Layer Ceramic Capacitor and looks to be 0603 in size.

body: It's a capacitor connected between 5V and GND and it smooths out voltage spikes for a cleaner power supply to the chip. A cleaner power supply means the circuitry in the chip can more easily pick out the data signal (i.e., the reference voltage is more constant, so the actual signal appears more stage.)

body:
It's most likely a decoupling capacitor meant to smooth out the voltage supply to the internal control chip.

This is standard practice to add to any chip. Power cables create a small bit of parasitic inductance in relation to the area between the lines. This inductance can induce voltage spikes when current draw changes significantly. A capacitor shrinks the effective area between the power lines.

This is also why the general advice for decoupling capacitors is to put them as close to the chip as physically possible.


body:
I am trying to make a lightbulb fade to dark and back to light, for which I found the following tutorial online:
[http://bildr.org/2012/03/rfp30n06le-arduino/][1]

Unfortunately, the tutorial makes use of a 60V light source while my intention is to use the system on 220V. Would it be enough to solve my problem to replace the 60V MOSFET in the system with one of 220V?
What would otherwise be a solution?

Thank you very much for your help!

  [1]: http://bildr.org/2012/03/rfp30n06le-arduino/

title: Fade out lightbulb 220V

Answers: 2

body:
Absolutely not. Not under any circumstances.

Dimming AC is a considerably harder task, and doing it with 220VAC can be deadly.

To do it you need:

* A zero-crossing detection circuit
* A TRIAC driver circuit
* A suitable TRIAC to do the switching
* Software that will use the zero crossing information to time the switch-on of the TRIAC to a certain point in the waveform.

And most importantly:

**Good knowledge of working with mains electricity - without which you will probably kill yourself or those around you.**

body:
You can buy 220V dimmer modules controllable with 5V PWM from Arduino. [Here is one][1] controllable with [this PWM digital potentiometer module.][2]

I use Kemo 4000VA regulator module with that M150 digital pot module controlled with Arduino PWM for heater regulation.

[![enter image description here][3]][3]

  [1]: https://www.kemo-electronic.de/en/Transformer-Dimmer/Controller/Modules/M012-Power-Control-110-240-V-AC-1200-VA.php
  [2]: https://www.kemo-electronic.de/en/Transformer-Dimmer/Converter/M150-DC-pulse-converter.php
  [3]: https://i.stack.imgur.com/YoVjt.jpg


body:
I am working on a autonomous fire extinguisher.i have run out of pins.I have the following question in my mind while working on my project

Is it necessary that the DO pin in a flame sensor must be in a PWM digital pin in Arduino.i have this doubt since when I connected it to non PWM pin it didn't worked.

Secondly it is possible for me to use the analog pin in Arduino for the DO pin of the flame sensor or trigger/echo pins of the ultrasonic sensor.

Thanks.

title: How do I use digital pin on sensor to analog on arduino uno

Answers: 2

body:
PWM stands for Puls Width Modulation and is only available when the Digital Pin is in OUTPUT mode.

And **YES**, you can connect the flame sensor's D0 to any digital pin on the Arduino.

And yes it is possible to connect the flame sensor's D0 to a analog pin, but why not use the A0 from the flame sensor and connect it toi a analog pin on the Arduino?

body:
You can use the analog pins (A0-A5, but not A6 and A7) also as digital pins. So you can set one of them as digital input, connecting it with the D0 pin of your fire sensor. You can read this pin with `digitalRead(pin)`.

Regarding your problem with PWM:
There is no "PWM input" on an Arduino Nano (because PWM hardware in a microcontroller means pulse with modulated output). The example code of your sensor uses an analog input (ADC: Analog Digital Converter) (with usage of `analogRead()`). If you want to use this functionality you have to connect the A0 pin of your sensor to one of A0-A7 and reading it with `analogRead()` to get the fires intensity/distance.


body:
I am using the code below to interface the Arduino nano and android cell phone to enable serial communication through the USB port. I downloaded the filter library from GitHub https://github.com/JonHub/Filters

I am getting an error saying thet the library is not found.
I would really appreciate some suggestions on this.

Here is my code:

     //This code is for arduino communicating to android phone through USb serial port.
     //For arduino nano

     #include <Filters.h>   //implements digital filters which mimic the analog filter, keep track of variable statistics in realtime

    char data_read; //character datatype takes up to 1 byte of memory
    unsigned int analog_out;
    unsigned long time;
    float filterFrequency = 10.0;
    FilterOnePole lowpassFilter( LOWPASS, filterFrequency );//implements digital RC type filter; both highpass and lowpass

     void setup()
     {
      Serial.begin(115200); //open the serial port and set the baud rate for communication
      // create a one pole (RC) lowpass filter

     }
     void loop()
     {
     }

     void serialEvent() { //Used when data is unavailable yet
     if (Serial.available()) //checks the number of bytes available for reading from the serial port
     {
    data_read = Serial.read();

    if (data_read == '0') {
      Serial.print("#");

      //Serial.print("10100");
      analog_out = lowpassFilter.input( analogRead(0) );
      Serial.print(analog_out + 10000);

      Serial.print(":");

      //Serial.print("20200");
      analog_out = lowpassFilter.input( analogRead(1) );
      Serial.print(analog_out + 20000);

      Serial.print(":");

      //Serial.print("30300");
      analog_out = lowpassFilter.input( analogRead(2) );
      Serial.print(analog_out + 30000);

      Serial.print("p");
    }
    /*if(data_read == '0' || data_read == '1' || data_read == '2' || data_read == '3' || data_read == '4' || data_read == '5'){
      analog_out = lowpassFilter.input( analogRead( data_read-48 ) );
      Serial.print((analog_out)+(data_read-48)*10000);
      Serial.print(":");
      }else if(data_read =='p'){
      Serial.print("p");
      }*/
       }
     }

Here is my error message:

      Arduino: 1.8.5 (Windows 10), Board: "Arduino Nano, ATmega328P"

      C:\Users\daphn\Documents\Arduino\Analog_Serial_out\Analog_Serial_out.ino:4:129: fatal error: Filters.h: No such file or directory

      #include <Filters.h>   //implements digital filters which mimic the analog filter, keep track of variable statistics in realtime

                                                                                ^

      compilation terminated.

      exit status 1
      Error compiling for board Arduino Nano.

      This report would have more information with
      "Show verbose output during compilation"
       option enabled in File -> Preferences.

title: File include error while using Arduino Nano

Answers: 2

body:
You have to put the folder with the library files in the folder `libraries` under your sketchbook folder. Then the IDE should be able to find them.

I think there is also a possibility to save them in the same folder as your `.ino` file, but it I don't know how exactly you have to do this.

body:
Here is your definitive answer.

You have to do the #include like the following (with double-quotes, not < > brackets)

```#include "Filters.h"```

This will make Arduino compiler look in the project folder.

Using < > brackets tells the compiler that it is in the standard library area.

I just tested this with the following script.

    #include "mytest.h"
    void setup() {
      // put your setup code here, to run once:

    }

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

    }

The ```mytest.h``` file is blank (has no text in it).

It wouldn't work until I included it using the double-quotes method.


body:
I have code that changes a bool only time in the setup(), and in my loop() I have

    if (setupBool) {
    // ...
    } else {
    // ...
    }

Is checking the bool every loop slower than having a while(true) with the same code?

And what about checking it in every loop in a while(true)?

Is there any reason I shouldn't do those?

title: Is checking an if statement every loop/while iteration inefficient?

Answers: 2

body:
Of course an if statement cost time, although very little. However, it changes (although once), so if you need to vary depending on the value, you have to use the if statement.

A while(true) also cost a little time (a little bit less), but less than 1 us, same as the if statement. You can do perfectly do an if statement within the while(true), but remember, the loop itself is behaving like a while(true) already.

However, I wouldn't concern at all about optimizing performance, unless:

- You know beforehand you will need the fastest code possible
- You have already performance issues

Always prefer readability/maintainability about performance.

body:
The actual full structure of the loop function is like this:

* while(true)
   * Call loop()
      * if (condition)
         * Run your code
      * else
         * Run your other code
   * Check for serial data

By putting a `while(true)` inside your `if` you:

* Remove the overhead of calling `loop()` every time
* Remove the overhead of checking for serial data (that is what the `SerialEvent` system is all about)
* Remove the overhead of checking the `if` every iteration.

So the executing part of your code now looks like:

* while(true)
   * Run your code.

If your code needs to run in a tight loop it can provide some speed improvements, yes, but at the cost of:

* No SerialEvent processing (normal Serial works, but the SerialEvent system breaks)
* Harder to "get out" of the loop to do something else (although `break` can help with that).
* On ESP8266 boards the watchdog will time out unless you manually `yield()` regularly.

Would I suggest doing it? Well, there are times when it can be beneficial, but those times are few and far between. If you don't *need* to do it then, in general, don't do it.


body:
will i be able to connect up all these parts to an arduino Nano
i noticed i will need to connect to the nanos v5 to the 2 joysticks and potentiometer slider if i share the voltage will it still function as intended
[![enter image description here][1]][1]
**Parts**

x1 = USB Arduino Nano V3.0 ATMEGA328P CH340G 5V 16M Micro-Controller Arduino

x2 = 3D Analog Joystick for Sony PSP 1000 Consol
+5v (possible 10kOhm resistance)

x1 = Electronic slider 10K potentiometer Slider Module for Arduino
Voltage: 3.3V or 5V / Resistance: 10K

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

title: Arduino Nano joystick x2 / potentiometer

Answers: 1

body:
Yes, this should work. The potentiometer slider will source about 5mA and each joystick axis about 50mA. In total this gives you 205mA. Here it is important, that your power source can provide enough current. If you are using an USB port from your computer, this would result in 500mA maximum that can be drawn from the bus. Since this is shared with the Arduino you can externally use about 400mA

For more information about current ratings refer to [this question][1]

EDIT: Since your previous resistance values were not correct, I edit my answer.

When all potentiometers have 10kOhm resistance (and this seems to be more likely the right values), each one draws about 5mA from the 5V pin (You can calculate this with Ohm's Law `U = R * I`, which gives you `I = U / R`. So you have to divide the voltage by the resistance.). So you aren't getting anywhere near the problematic currents. These potentiometers are designed this way. They don't want to draw a high amount of power, but only setting a certain voltage to the output pin.

  [1]: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins


body:
I try to use this code, but it shows that I need to define again the last void turn_mer (int direction) function. How can I fix this?

    #include <Servo.h> //create servo object to control a servo.
    Servo myservo;

    //pin configuration.
    const byte servoPin = 2; const byte motorLeft = 5; const byte motorRight = 6;
    const byte echoPin = 12; const byte trigPin = 13; const byte echoPin2 = 8; const byte trigPin2 = 9; // LET OP DE HOOFDLETTERS: echopin en echoPin
    //delay determines how long the MER turns, increase to make the turning angle larger.
    const int turnDelay = 500;
    //standard angle for looking straight ahead, compensate for construction errors.
    const int standardAngle = 90;
    //angle in degrees that controls the direction in which the sensor looks.
    const int viewAngle = 40;
    //delay to let servo turn, not optimized; for smaller angles smaller delay could be used.
    const int servoDelay = 250;
    //object distance in cm at which the MER decides to look around and turn another way.
    const int lineOfSight = 40;
    //pwm duty cycle of the motor, use a value from 0 (no movement) to 255 (full speed).
    const int motorSpeed = 90;

    //const int lineDownSight = 35;
    void setup() //setup pin configuration and initialize the sensor position.

    { delay(3000); //delay to give us some time to place the MER on the ground.
      myservo.attach(servoPin); //initialize the servo and look straight ahead.
      turn_servo(standardAngle);
      pinMode(motorLeft, OUTPUT); pinMode(motorRight, OUTPUT);
      pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); drive_mer();
    } //start the mer.
    void drive_mer() //this function lets the MER drive forward.
    {
      analogWrite(motorLeft, motorSpeed);
      analogWrite(motorRight, motorSpeed);
    }
    void stop_mer() //this function stops the mer.
    {
      digitalWrite(motorLeft, LOW);
      digitalWrite(motorRight, LOW);
    }
    void turn_servo(int angle)
    //turn servo to given angle, do not return until angle is reached.
    //if the servo is already at the correct angle, we don't have to do anything.
    { if (angle == myservo.read()) {
        return;
      }
      else {
        myservo.write(angle);
        delay(servoDelay);
      }
    }

    int look1() //looking function, returns distance in the observed direction as an integer.
    { int duration, distance;
      digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
      delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1; return distance;
    }
    //turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
    void turn_mer(int direction)

    { if (direction == 0) {
        digitalWrite(motorLeft, LOW);
        digitalWrite(motorRight, HIGH);
      }
      else {
        digitalWrite(motorLeft, HIGH);
        digitalWrite(motorRight, LOW);
      }
      delay(turnDelay); stop_mer();
    }//stop the engines when the MER has turned far enough.

    //this function turns the MER depending on the observed distances.
    void handle_measurements(int distanceLeft, int distanceStraight, int distanceRight)// int distanceDown

    { if (distanceLeft < lineOfSight and distanceStraight < lineOfSight and
          distanceRight < lineOfSight) {
        stop_mer();
      }

      else if (distanceLeft < lineOfSight) {
        turn_mer(1);
        drive_mer();
      }

      else if (distanceStraight < lineOfSight) {
        if (distanceRight > distanceLeft)
        {
          turn_mer(1);
        } else {
          turn_mer(0);
        } drive_mer();
      }

      else if (distanceRight < lineOfSight) {
        turn_mer(0);
        drive_mer();
      }
     //if (distanceDown > lineDownSight) {
      //  stop_mer();
      }

      void loop()
      { int distanceLeft, distanceStraight, distanceRight;

        turn_servo(standardAngle + viewAngle); distanceLeft = look1();
        turn_servo(standardAngle); distanceStraight = look1();
        turn_servo(standardAngle - viewAngle); distanceRight = look1();
           handle_measurements(distanceLeft, distanceStraight, distanceRight);}

    /*  void handle_measurements(lineDownSight)
       {(distanceDown > lineDownSight) {
        stop_mer();
      }*/
      //                                                                                sensor 2
      //______________________________________________________________________________________________________________________________________________________________________________________________________

     const int lineDownSight = 35;

      void handle_measurements (int distanceDown)

    {if (distanceDown > lineDownSight) {
        stop_mer();}}

      int look2() //looking function, returns distance in the observed direction as an integer.
      { int duration, distance;
        digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
        delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
        distance = (duration / 2) / 29.1; return distance;
      }
      //turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
    void turn_mer (int direction)

    {handle_measurements(distanceDown)}

title: Error in code (define a function)

Answers: 1

body:
But the main problem is that in C, you can only define a function with the same name once.

Halfway you defined the function turn_mer already, and again at the end.

Also, you are missing an end colon in:

    {handle_measurements(distanceDown)}

It's better to align your code like:

    {
        handle_measurements(distanceDown);
    }


body:
I'm going to use this for Arduino Pro Mini (5v version) to communicate with ESP32 via UART so I need level shifting. I found this circuit which uses NPN transistor and I'm also going to use it. This is the circuit I'm going to use...

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/MECV9.png)

<!-- End schematic -->

Are the resistors' value appropriate or do I have to change the collector resistor?

title: NPN transistors level shifter

Answers: 0


body:
Trying to do serial communication between 2 Arduino Unos.

Code:

<!-- language: lang-c++ -->

    #include <SoftwareSerial.h>

    int ledPin = 13;
    int board;   // 1 = Uno. 2 = Mega.
    int on_off;  // 1 = On. 0 = Off.
    int buzzerPin = 9;
    int Ack_tx = 2; //Acknowledgement tx.
    int rec;

    void setup()
    {
      Serial.begin(9600);      // start serial communication at 9600bps
      Serial1.begin(9600);     // start serial1 communication at 9600bps

      pinMode(ledPin, OUTPUT);
      pinMode(buzzerPin, OUTPUT);

      Serial.flush();
      Serial1.flush();

    } // End Setup

    void loop()
    {

      Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
      //  if(!Serial){ board = Serial.read();}
      while(Serial.available()==0) { // Wait for User to Input Data
      }
      board = Serial.parseInt();  //Read the data the user has input

      Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
      while (Serial.available()==0) { // Wait for User to Input Data
      }
      on_off = Serial.parseInt();

      Serial.println();

      switch (board) {

      case 0:  //Mega board
        if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
        else digitalWrite(ledPin, LOW);              //Select Uno LED Off
        break;  //End Case

      case 1:  //Uno board
        //Serial.println("Off to Uno...");
        //Send on_off info to Uno
        Serial1.write(on_off/256); //Send the Quotient or "how many times" value
        Serial1.write(on_off%6); //Send the Modulo or Remainder.
        delay(50); //Wait for the serial port.

        while(Serial1.available()<2) //Wait for 2 bytes to arrive
         {
          //do nothing
         } //End While

      byte b1=Serial1.read();  //Read Upper byte
      byte b2=Serial1.read();  //Read Lower byte
      rec=(b1*256)+b2;

        if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
        break;
      } //End Switch Case

    }

Error:

<!-- language: lang-none -->

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

    sketch_mar06a:13: error: 'Serial1' was not declared in this scope

       Serial1.begin(9600);     // start serial1 communication at 9600bps

       ^

    C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

    sketch_mar06a:51: error: 'Serial1' was not declared in this scope

         Serial1.write(on_off/256); //Send the Quotient or "how many times" value

         ^

    Multiple libraries were found for "SoftwareSerial.h"
     Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
     Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
    exit status 1
    'Serial1' was not declared in this scope

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

This is a very basic problem I know, but nothing on the internet is helping.

Answers: 2

body: The Uno has no `Serial1`. It only has one serial port, called `Serial`. To use `Serial1` you will need a bigger board such as a Mega2560, or define it as a `SoftwareSerial` port and use two other IO pins of your choice for it, though at lower baud rates than `Serial` can run at.

body:
You import the `SoftwareSerial` library but you however never instance an object of the `SoftwareSerial` class.

You just need to add the line

     SoftwareSerial Serial1(10, 11); // RX, TX

after including the library header (taken from [here][1])

This now creates an object `Serial1` on which the operations down there should work the same as with a real hardware serial (API-wise).

Side note: Careful with the wiring. You are using this `Serial1` emulated UART to communicate between the boards, so if you're using above pin numbers (D10 = RX, D11 =TX) then you must connected D10 (Board1) -> D11 (Board2), D11 (Board1) -> D10 (Board2), i.e. RX->TX, TX->RX.

  [1]: https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


body:
I am following [this tutorial][1] of a very basic serial communication between 2 arduino unos.

I have made the connections as given and connected the arduino unos to 2 separate laptops via USB.

Code1:

    char mystr[3] = "Hello"; //String data

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial.begin(9600);
    }

    void loop() {
      Serial.write(mystr,5); //Write the serial data
      delay(1000);
    }

Code 2:

    char mystr[5]; //Initialized variable to store recieved data

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial.begin(9600);
    }

    void loop() {
      Serial.readBytes(mystr,5); //Read the serial data and store in var
      delay(1000);
    }

Error on arduino following code 1:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    Sketch uses 1602 bytes (4%) of program storage space. Maximum is 32256 bytes.
    Global variables use 188 bytes (9%) of dynamic memory, leaving 1860 bytes for local variables. Maximum is 2048 bytes.
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
    An error occurred while uploading the sketch

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Arduino running code 2 is stuck on the uploading and does not fininsh uploading.

The solutions on the internet only talk of the scenarios where the arduino is having trouble communication with the computer and so the solutions given are:

check com port

check that correct board is selected

do not insert the arduinos in usb 3

press reset button

None of these is my problem as I have checked them all. The arduinos themselves are working fine. I have a very strong feeling that there is a problem with the pins 0 and 1, i.e. with serial comm.

Please help.

  [1]: https://create.arduino.cc/projecthub/harshmangukiya/serial-communication-between-two-arduino-boards-d423e9

title: Trouble uploading sketch / error in sketch

Answers: 1

body:
I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.

Break this connection before upload and then it should work. You can reconnect them after upload.

If you want to avoid this you can use different pins with software serials for communication.

Also consider using Serial.available() on the reading end to see if there is data to be read.


body:
I've been trying to use a KY-022 to read IR signals. However no output is being produced and the LED on the board is constantly on.

Board: Arduino Uno R3

I followed the procedure found [here][1].

The code:

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void setup() {
      Serial.begin(9600);
      // In case the interrupt driver crashes on setup, give a clue
      // to the user what's going on.
      Serial.println("Enabling IRin");
      irrecv.enableIRIn(); // Start the receiver
      Serial.println("Enabled IRin");
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      delay(100);
    }

The output:

    Enabling IRin
    Enabled IRin

The LED is constantly on, it should come on when there's a signal received. However this is not shown in the output. :/ I don't know what to do.

Pictures:

[![Board!][2]][2]
[![Board-upside-down, top-row corresponding to Signal!][3]][3]
[![Setup][4]][4]

  [1]: https://arduinomodules.info/ky-022-infrared-receiver-module/
  [2]: https://i.stack.imgur.com/Mxkt2.jpg
  [3]: https://i.stack.imgur.com/o4XLf.jpg
  [4]: https://i.stack.imgur.com/4alhh.jpg

title: KY-022 IR receiver, LED always on, no output

Answers: 2

body:
The first thing to look at is the circuit board. Are they using the resistor and LED to indicate the board is receiving power? The data sheet has a schematic showing several passive components in the "3. ApplicationCircuit" section. Here is a copy of the schematic I have used that worked with the IRremote library (Version 0.1 July, 2009 - Copyright 2009 Ken Shirriff).

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

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

body:
This happened to me when I "fried" my IR receiver.

Everything was fine and working until I accidentally reversed ground and +5v when putting my project back together after a tear down.
After correcting the wiring, the LED stayed on, and no reading was coming out.

Did you ever get any pins wrong?

This video show the correct wiring.
https://www.youtube.com/watch?v=iFpAqG90zY0


body:
I am trying to get the ESP8266 work with Arduino AT commands. I am using the due. How do I get the ESP8266 to respond with anything other than ERROR?

Here is the current serial output:

    AT
    ERROR

Here is my code:

<!-- language: lang-C -->

    void setup() {
        Serial.begin(9600);
        Serial3.begin(115200); //Manufacture said this is the correct baud rate
    }

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

        if ( Serial.available() )  {  Serial3.write( Serial.read() );  }
    }
Here are my pin connections:

    RX3  -> ESP TX
    TX3  -> ESP RX
    GND  -> GND
    3.3V -> CH_PD + VCC

title: Only getting error from ESP8266 AT commands

Answers: 1

body:
The AT firmware responded with ERROR because it received data, but timed out waiting for the CR/LF line ending.

AT commands must be terminated with Carriage Return '\r' and Line Feed '\n' control bytes/characters.


body:
    while(condition){
        Object object = new Object();
    }

So my question is, will each iteration would create a different object in different memory location or it will overwrite the once created object every iteration.

title: Is a variable declaration inside a loop static declaration or dynamic?

Answers: 2

body:
It will be created every iteration.

Assuming, you are not using it to add to a list (e.g. to use in later loops), what you better can do is make it in a global, you also don't need to use 'new', thus:

    Object object;

Also, if you do not delete/remove the object at the end of each while condition (with the *delete* keyword), you will lose the memory (and this is a memory leak). Also, you run the risk of memory shortage (the Uno has only a few KB of memory).

What I also miss in your code is the pointer (*, because the *new* keyword creates a pointer), and also Obj and Object are inconsistent types (they should be equal), so:

    Object* object = new Object();

If you only need the object within the condition and it can be removed in the next while, than you don't need to use new, so just declare it as a vaiable

    Object object;

This also has the benefit that the (local) variable will be destroyed at the end of scope (which is at the end of the while).

body:
**Dynamic** object creation is using operator `new`. Operator `new` creates object on *heap* and the object exits until you delete it with operator `delete`.

`Object object` creates object on *stack*. It will be removed from stack when the variable goes out of scope on the end of the block.

**Some classes have copy constructors. If your `Object object = new Object()` compiles, then the class Object has copy constructor. The code creates an object on stack, then creates an object on heap and then copies it's content into object on stack. The object on heap stays and you have no pointer to it to delete it. The program soon crashes on low memory.**

**Static** variables have keyword static. If you would have `static Object* object = new Object()`, then the pointer is created on global level and the object on heap is created and assigned only ones.

EDIT:
I tested this. Class String has a copy constructor, but the Arduino compiler doesn't allow `String s = new String(a)`. It can be misleaded with `String s = *(new String(a))` (`a` is some variable).


body:
I am working with the LED strip **WS2812b** and **FastLED** library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color *(say green)* and the last one receives another one *(say blue)*.

The problem is that by putting the color *(blue)* on the last LED, the other two (currently only in *green*) also take a portion of *blue*, preventing it from being a pure (*green*) color. It happens with any combination of color.

I leave the piece of my code referring to the LED strip:

<!-- language: lang-c++ -->

    #include "FastLED.h"
    #define NUM_LEDS 3
    #define DATA_PIN 2

    //Variables declaration...
    ....

    void setup() {
      FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
    .....

      }

    void loop() {
      ReadMySerial();       //This function take data from serial port and set the color for the leds
      FastLED.setBrightness(brigth);

      for (int pinNo = 0; pinNo <= 2; pinNo++){
        leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
        FastLED.show();
          if (digitalRead(pinNo+3) == HIGH){
            leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
               FastLED.show();
                }
            }

      }

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

- `FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)`
- `FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)`
- `FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)`

without any success...

Can anyone point me in the rigth direction?

Edit: actually, the first LED of the strip is flashing, not in the way of the **Blinking** example, but I can see a little flashing.

title: Not getting pure color while using the FastLED with WS2812b

Answers: 1

body:
I can see what the problem is, I put `FastLED.show();` where it should not, that's also why I saw the flash ... fix it and here's the result:

    void loop() {
      ReadMySerial();       //This function take data from serial port and set the color for the leds
      FastLED.setBrightness(brigth);

      for (int pinNo = 0; pinNo <= 2; pinNo++){
        leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
        FastLED.show();
        if (digitalRead(pinNo+3) == HIGH){
          leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
        }
      }

      FastLED.show(); //NOW IS IN THE RIGHT POSITION
    }


body:
The basic plan is to have a Attiny85 pass information from a 433Mhz RF module to another chip/Arduino via I2C using VirtualWire and Wire libraries. I have been able to make this system work on their own using Arudino Nano's to debug, but the Attiny85 (A85) seems unable to grab the data from the RF 433 Mhz.

So have spent a few days doing some more research, and basically putting each component separate, to make sure what is being sent is correct.

 1. 433 Mhz transmitter is working by sending a 9 digit number, using VirtualWire.h.
 2. Nano with a 433 Mhz receiver is receiving 9 digit
    number, VirtualWire.h.
 3. Attiny85 is sending either a no data, or the 9 digit number, to another Nano using Wire.h.
 4. The Nano is getting only No Data, so the I2C is working between A85 and Nano.

Attiny85, on Pin 1 (pin 6 on chip) is not getting any data from the 433 Mhz, which works on (2). I connect the GND of the 433 RX to the chip.

Here is the **Receiver** code:

    #include <VirtualWire.h>
    #include <Wire.h>
    void setup() {
      pinMode(A3, OUTPUT);
      Wire.begin(); // join i2c bus (address optional for master)
      vw_set_ptt_inverted(true); // Required for DR3100
      vw_setup(4000);   // Bits per sec
      vw_set_rx_pin(1);
      vw_rx_start();       // Start the receiver PLL running
    }
    void loop() {
      uint8_t buf[15];
      uint8_t buflen = 15;
      if (vw_get_message(buf, &buflen)) // Non-blocking
        {
          digitalWrite(A3, LOW);
          Wire.beginTransmission(8); // transmit to device #8
          for (int i = 0; i < buflen; i++) {
            Wire.write(buf[i]);
          }
          Wire.endTransmission();    // stop transmitting
        } else {
          digitalWrite(A3, HIGH);
          Wire.beginTransmission(8); // transmit to device #8
          Wire.write("no DATA");
          Wire.endTransmission();    // stop transmitting
         }
    }

Here is the **Transmitter** code:

    #include <VirtualWire.h>
    int xPin = A7;
    int yPin = A6;
    int buttonPin = 2;

    int xPosition = 0;
    int yPosition = 0;
    int buttonState = 0;
    const char *controller;
    void setup() {
      Serial.begin(9600);
      pinMode(12,OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(yPin, INPUT);
      pinMode(xPin, INPUT);
      pinMode(buttonPin, INPUT_PULLUP);
      vw_set_ptt_inverted(true); //
      vw_set_tx_pin(12);
      vw_setup(4000);// speed of data transfer Kbps
    }

    void loop(){
       xPosition = analogRead(xPin);
       yPosition = analogRead(yPin);
       buttonState = digitalRead(buttonPin);
    if(xPosition > 0 || yPosition > 0) {
      String Data = (xPosition + yPosition);
      controller = Data;
      vw_send((uint8_t *)controller, strlen(controller));
      vw_wait_tx(); // Wait until the whole message is gone

    } else {
      digitalWrite(13, 0);
      digitalWrite(4, 1);
      controller = "#s0_0";
      vw_send((uint8_t *)controller, strlen(controller));
      vw_wait_tx(); // Wait until the whole message is gone
    }

    Serial.println(controller);

    }

So basically the A85 is not getting past if (vw_get_message(buf, &buflen)) { on pin 1. But does when using the Nano on pin D2, from the same transmitter, but not at the same-time of-course.

Am I using the wrong Pin on the A85? Chip pin 5 and 7 are used for the I2C so it only leaves analog pins so not sure they would work either. I also tried 8 Mhz and 1 Mhz when loading the A85.

I  have tried different Cores as suggested from Google, different versions of VirtualWire and clocked the Attiny 1Mhz, 8Mhz and 16Mhz. None of have worked.

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

Not sure what else I am missing?

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

title: Attiny85 not able to understand data from 433Mhz using VirtualWire.h

Answers: 1

body:
Have you tried using the <a href="http://www.airspayce.com/mikem/arduino/RadioHead">Radiohead </a> library? I know you said you tried different versions of Virtual Wire. The RH_ASK class works on a 328p and a nano for sure and they claim a simple Rx program can run on a ATTiny85. They have documentation under RH_ASK regarding the changes you need make to the library.
Another possible fix is to edit the Virtual Wire library files, they might have variables like "Max_payload" (Radiohead does) whose size can be decreased.
I haven't actually read the Virtual wire library, but I am sure Radiohead should fix your problems.

If this doesn't work, do you have an oscilloscope? Maybe we can try debugging it like that.

Edit: Maybe try commenting out the `vw_set_ptt_inverted` line first. I don't think you are using the DR3100. Might not make a difference because you haven't actually set a pin for ptt.
Next thing you can try is just connecting the data pin of the Tx to the Rx. You should be able to check if the module is actually connected to the ATTiny with this.


body:
I have a digital temperature sensor which gives digital output in the form of current pulses. The number of pulses corresponds to a particular temperature.

I have converted the current pulses to voltage pulses using transistor as a level shifter. I want to count the number of pulses for a time interval of 50ms each time.

Please help me with the algo and the code.

title: How to count the voltage pulses of a digital temperature sensor using Arduino Mega Atmega2560?

Answers: 1

body:
There are function called [pulseIn][1] which probably need exactly what you want.

Just set a variable with the current 'time' ([millis][2], start counting until the current time reaches 50 ms later.

So something like (not checked):

    unsigned long timer = millis();
    unsigned pulses = 0;
    while (timer + 50 < millis())
    {
      pulseIn(PIN, LOW);
      pulses++;
    }

PIN is a constant or variable that defines the pin number to check, LOW is to check low pulses, you also can use high, and optionally you can add a timeout. For example, you can use the timeout to check the last timeout is within the 50 ms region. Or to be more precise, check if the pulse was within the same 50 ms:

    unsigned long timer = millis();
    unsigned pulses = 0;
    while (timer + 50 < millis())
    {
      pulseIn(PIN, LOW);
      if (timer + 50 < millis())
      {
        pulses++;
      }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/
  [2]: http:// millis()


body: I recently bought an ESP-WROOM-32 module and I want it to talk to my Pro Mini via I2C. Do I have to pull-up the lines to the 3.3v side (ESP32)? Since the Pro Mini runs at 5v, I think it's a bad idea to pull-up the lines from that side.

title: Arduino Pro Mini (5v) I2C pullups

Answers: 0


body:
the wiki here says http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

    0 Low
    1 High
    x floating
    MODE                 GPIO15  GPIO0  GPIO2
    SDIO (BootSDCard)      1      x       x
    UART (UploadCode)      0      0       x or 1
    FLASH (NormalRunning)  0      1       x or 1

Can connecting my GPIO 2 to a servo Signal Wire cause it to go LOW? because some how my ESP8266 doen't boot when I have a servo hooked up to it.
I tried to change it to RX (which is GPIO3 on ESP8266) and everything seems to work fine. But I wanna know the reason why GPIO2 didn't work.

Thank you.

p/s:http://www.goodluckbuy.com/ld-1501mg-metal-gear-digital-servo-17kg-for-rc-robot.html this is the servo, if it matters. Also GPIO-2 works when I use another servo of different type instead (I don't know its name though)

title: ESP8266(01) doesn't work when servo connected to GPIO-2

Answers: 1

body:
It's what Juraj said.

> add external pull-up to io 2 -Juraj

sovled it


body:
I tried to imitate [lagsilva's clock projects][1] using Arduino Uno and made the circuitry, then I've tried to upload the main source code of the author but noticed that it didn't work, so I've edited the sketch and modified some of the details. When uploading it to the board, it seemed fine but there was nothing on the board and the project. Here are the codes:

Lagsilva's:

    /*  4-Stroke Digital Clock With Two MAX72XX LED Matrix & RTC
                  V1.1 - 02.Feb.2018
                   Author: LAGSILVA */

         #include <LedControl.h>                   // Library for LED Matrix - MAX72XX
    #include <Wire.h>                         // Library for DS3231 - Pins of Arduino UNO: A4 (SDA), A5 (SCL)
    #include <DS3231.h>                    // Library for Real Time Clock
    // Global Variables
    byte hh, mm;                              // Hour, Minute
    byte uH, uM, dH, dM;                      // Units Hour, Units Minute, Teens Hour, Teens Minute
    byte p = 0;                               // Plot Mode (Position of Digits: Up/Down)
    int RPM = 0, lastRPM = 0, pinRPM = 0;     // RPM, Last value of RPM, Analog Pin for RPM
    byte seq = 1;                             // Start Fire sequence

    /*
      Pin numbers do Arduino para conexao com o MAX72XX (matriz de LED com controlador MAX72XX)
      pin 7 is connected to the DataIn (DIN)
      pin 6 is connected to LOAD (CS)
      pin 5 is connected to the CLK (CLK)
    */

    LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, int CS, int numDevices)

    // Array of Digits - (0 to 9) - Size 5x3

    byte num[10][3] = {

      {0xF8, 0x88, 0xF8}, // 0
      {0x00, 0xF8, 0x40}, // 1
      {0xE8, 0xA8, 0xB8}, // 2
      {0xF8, 0xA8, 0x88}, // 3
      {0x78, 0x20, 0xE0}, // 4
      {0xB8, 0xA8, 0xE8}, // 5
      {0xB8, 0xA8, 0xF8}, // 6
      {0xC0, 0xB8, 0x80}, // 7
      {0xF8, 0xA8, 0xF8}, // 8
      {0xF8, 0xA0, 0xE0}, // 9

    };

    void setup() {

      setSyncProvider(RTC.get);    // Function to read RTC (Real Time Clock)
      //setSyncInterval(3600);                // Set the number of seconds between re-sync
      //setTime(14, 59, 00, 03, 02, 2018);    // Set the Time and Date
      //RTC.set(now());                       // Set the RTC time

      // Setup of Display "0"
      lc.shutdown(0, false);                // Wakeup Display "0"
      lc.setIntensity(0, 4);                // Set the Brightness of Display (0 to 15)
      lc.clearDisplay(0);                   // Clear Display "0"

      // Setup of Display "1"
      lc.shutdown(1, false);                // Wakeup Display "1"
      lc.setIntensity(1, 4);                // Set the Brightness of Display (0 to 15)
      lc.clearDisplay(1);                   // Clear Display "1"

    }

    void loop() {

      hh = (11);
      mm = (14);

      uH = hh % 10;
      dH = hh / 10;

      uM = mm % 10;
      dM = mm / 10;

      // Plot Hours

      for (byte k = 0; k < 3; k++) {

        lc.setRow(0, k + 5, num[dH][k] >> (p + 2));
        lc.setRow(0, k + 1, num[uH][k] >> (3 - p));

      }

      // Plot Minutes

      for (byte k = 0; k < 3; k++) {

        lc.setRow(1, k + 4, num[dM][k] >> (3 - p));
        lc.setRow(1, k , num[uM][k] >> (p + 2));

      }

      // Plot Fire Sequence: 1-3-4-2 (4 cyl: 1-3-4-2 or 1-2-4-3 or 1-4-3-2)

      if (seq == 1) {                               // Fire Cyl #1
        lc.setLed(0, 6, 0, true);
      }

      if (seq == 2) {                               // Fire Cyl #3
        lc.setLed(1, 5, 0, true);
      }

      if (seq == 3) {                               // Fire Cyl #4
        lc.setLed(1, 1, 0, true);
      }

      if (seq == 4) {                               // Fire Cyl #2
        lc.setLed(0, 2, 0, true);
      }

      seq = seq % 4 + 1;

      // RPM reading

      RPM = analogRead(pinRPM);                     // Potentiometer reading

      RPM = map(RPM, 0, 1023, 1, 9);

      if (RPM <= 8) {
        lc.setLed(1, 7, 8 - RPM, true);
        lc.setLed(0, 0, 8 - RPM, true);
        delay(300 / RPM);                           // Speed setup by potentiometer (100 - 800 RPM)

        if (lastRPM != RPM) {
          lc.setRow(0, 0, 0);
          lc.setRow(1, 7, 0);
          lastRPM = RPM;
        }

      }

      p = !p;                                       // Switch the position of digits (Up x Down)

    }

My modification was this:

    #include <Wire.h>
    #include <DS3231.h>
    #include <LedControl.h>
    // Global Variables
    byte hh, mm;                              // Hour, Minute
    byte uH, uM, dH, dM;                      // Units Hour, Units Minute, Teens Hour, Teens Minute
    byte p = 0;                               // Plot Mode (Position of Digits: Up/Down)
    int RPM = 0, lastRPM = 0, pinRPM = 0;     // RPM, Last value of RPM, Analog Pin for RPM
    byte seq = 1;                             // Start Fire sequence

    LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, int CS, int numDevices)

    // Array of Digits - (0 to 9) - Size 5x3

    byte num[10][3] = {

      {0xF8, 0x88, 0xF8}, // 0
      {0x00, 0xF8, 0x40}, // 1
      {0xE8, 0xA8, 0xB8}, // 2
      {0xF8, 0xA8, 0x88}, // 3
      {0x78, 0x20, 0xE0}, // 4
      {0xB8, 0xA8, 0xE8}, // 5
      {0xB8, 0xA8, 0xF8}, // 6
      {0xC0, 0xB8, 0x80}, // 7
      {0xF8, 0xA8, 0xF8}, // 8
      {0xF8, 0xA0, 0xE0}, // 9

    };

    void setup() {

      //setSyncInterval(3600);                // Set the number of seconds between re-sync
      //setTime(19, 07, 59, 06, 03, 2018);    // Set the Time and Date
      //DS3231.set(now());                       // Set the RTC time

      // Setup of Display "0"
      lc.shutdown(0, false);                // Wakeup Display "0"
      lc.setIntensity(0, 4);                // Set the Brightness of Display (0 to 15)
      lc.clearDisplay(0);                   // Clear Display "0"

      // Setup of Display "1"
      lc.shutdown(1, false);                // Wakeup Display "1"
      lc.setIntensity(1, 4);                // Set the Brightness of Display (0 to 15)
      lc.clearDisplay(1);                   // Clear Display "1"

    }

    void loop() {

      hh = (21);
      mm = (32);

      uH = hh % 10;
      dH = hh / 10;

      uM = mm % 10;
      dM = mm / 10;

      // Plot Hours

      for (byte k = 0; k < 3; k++) {

        lc.setRow(0, k + 5, num[dH][k] >> (p + 2));
        lc.setRow(0, k + 1, num[uH][k] >> (3 - p));

      }

      // Plot Minutes

      for (byte k = 0; k < 3; k++) {

        lc.setRow(1, k + 4, num[dM][k] >> (3 - p));
        lc.setRow(1, k , num[uM][k] >> (p + 2));

      }

      // Plot Fire Sequence: 1-3-4-2 (4 cyl: 1-3-4-2 or 1-2-4-3 or 1-4-3-2)

      if (seq == 1) {                               // Fire Cyl #1
        lc.setLed(0, 6, 0, true);
      }

      if (seq == 2) {                               // Fire Cyl #3
        lc.setLed(1, 5, 0, true);
      }

      if (seq == 3) {                               // Fire Cyl #4
        lc.setLed(1, 1, 0, true);
      }

      if (seq == 4) {                               // Fire Cyl #2
        lc.setLed(0, 2, 0, true);
      }

      seq = seq % 4 + 1;

      // RPM reading

      RPM = analogRead(pinRPM);                     // Potentiometer reading

      RPM = map(RPM, 0, 1023, 1, 9);

      if (RPM <= 8) {
        lc.setLed(1, 7, 8 - RPM, true);
        lc.setLed(0, 0, 8 - RPM, true);
        delay(300 / RPM);                           // Speed setup by potentiometer (100 - 800 RPM)

        if (lastRPM != RPM) {
          lc.setRow(0, 0, 0);
          lc.setRow(1, 7, 0);
          lastRPM = RPM;
        }

      }

      p = !p;                                       // Switch the position of digits (Up x Down)

    }

[![The schematic diagram][2]][2]

Anyone could help me please, thank you!

  [1]: https://www.hackster.io/lagsilva
  [2]: https://i.stack.imgur.com/bc4TU.png

title: What might be the errors of my codes?

Answers: 0


body:
I'm currently trying to fill out the constructor but I'm not sure what's what...
The constructor of the UTFT library goes as follows:

    UTFT(Model, SDA, SCL, CS, RST[, RS]);

Where the last bit is optional.

SDA meaning Serial Data, SCL serial clock, CS chip select, RST reset and RS register select.

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

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

This is the screen I'm trying to connect. As far as I understand:

SDI (MOSI) goes to SDA

SCK goes to SCL

CS  goes to CS

RST goes to Reset?

RS goes to D/C?

But it doesn't work. What am I missing...

Here's my full code:

    #include <UTFT.h>

    //Digital Pins:
    //53 = MOSI
    //52 = SCK,
    //10 = CS
    //6 = RS
    //7 = D/C
    UTFT myGLCD(ILI9341_S5P,53,52,10,6,7);

    void setup() {
        myGLCD.InitLCD(PORTRAIT);
        myGLCD.clrScr();

    }

    void loop() {
        myGLCD.fillScr(0,0,255);

    }

I did get the screen to work with the Adafruit_GFX library. I used 1k resistors between all of the data lines, including reset. When using the screen with the GFX library I connected reset to 3,3v.

title: Trying to get a ILI9341 TFT to work with UTFT library

Answers: 0


body:
I'm trying to power Arduino Nano with 7.4V LiPo battery and use it to run 2 DC motor using L293D. I have figured out how power it with the connection just like in the figure below(the diagram uses Uno and the battery is 9V but try to imagine it as Nano and 7.4V).[![figure][1]][1]  I also found another way to power it by connecting the red wire from battery to Vin on the Arduino instead of connecting it to the positive power rail.

So, my question is which is a safer way to power it and what is the difference and risk of one the way I mention.

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

title: What is a safe way to power arduino nano with 7.4V Lipo battery?

Answers: 1

body:
Connect it via the Vin pin. That way the 6-8.4 volt of the battery will go through the voltage regulator on the Nano, giving you a stable 5v.

What you show in your diagram is the wrong way of connecting the battery. The absolute maximum you can supply to the Arduino's 5V pin is 6 Volt. Atmel recommends no more than 5.5V. So your battery exceeds this when it's full.


body:
I'm using the **SIM800L** module but i've problems. I'm triying to connect it to the **Elegoo UNO** i've, but it restarts at all times. Also the led of signal strengh blink every second, so i dont get signal.

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

I also upload a video to Youtube to explain the problem, [this is the link.][2]

Thanks in advance!

  [1]: https://i.stack.imgur.com/5zlC2.jpg
  [2]: https://www.youtube.com/watch?v=0XL_CzWNUik

title: Arduino UNO reset using SIM800L

Answers: 2

body:
When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.

You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.

The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.

If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.

If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.

The usual required state for reset is LOW so the output must be HIGH for the device to work.

[Some tutorials and libraries][1] require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.

  [1]: https://cristiansteib.github.io/Sim800l

body:
Besides the RST pin situation that the others pointed out, you're not going to do much with the way you're powering the module. It might turn on, but you will never be able to register on the network.
You have to power the module with an external power source and common the ground.

Also, if the module you're using is the one on the image, you might need a logic level shifter to use the Tx-Rx connection.


body:
For a robotics project I am using an MCP23017 I/O Port Expander in order to have more pins available, and I am also using a PS2 controller for input. Both of these require pins 4 and 5 (because these are the data and clock pins). I was wondering if I can use a breadboard to simply connect these two pins to both devices in order to provide both of them with data and clock pins.

I am using an Arduino UNO and a playstation 2 controller with the following guide:
http://www.techmonkeybusiness.com/using-a-playstation-2-controller-with-your-arduino-project.html

title: Splitting SCL and SDA pins

Answers: 2

body:
An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.

But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function `ps2x.config_gamepad()`.  In it's parameters you can set the pins that the library will use.

body:
You are confusing pins here. In the library you mention there is a function call to set up the gamepad:

<!-- language: lang-c++ -->

     ps2x.config_gamepad(5,4,3,2, false, false);
     //setup pins and settings: GamePad(clock, command, attention, data, Pressures, Rumble)

That is **digital** pins 5, 4, 3 and 2.

I2C uses **analog** input pins A4 and A5 on the other side of your Uno board.


body:
I'm developing software side for 3 axes robot where are 360° continuous rotating servos used [Documentation here][1]

these servos have its own feedback system so it's possible to control it's position via pid system, when im using only one PID algorithm in clear sketch just for this pid everything working OK but when I want to use multiple PIDs there are problem with delays and every next function that is used in the sketch will result in bigger delays that make these servos flicking because it's executed in main function

 int pinFeedback = pin_comes_here;

 float tHigh = 0;
 float tLow = 0;
 int tCycle = 0;
 float dc = 0;
 float angle = 0;
 float dcMin = 2.9;
 float dcMax = 97.1;

 void setup() {
   pinMode(pinFeedback, INPUT);
 }

 void loop() {
  while(1) //From Parallax spec sheet
  {          //There is core of the problem
    tHigh = pulseIn(pinFeedback, HIGH);
    tLow = pulseIn(pinFeedback, LOW);
    tCycle = tHigh + tLow;
    if ( tCycle > 1000 && tCycle < 1200)
   {
     break; //valid tCycle;
   }
  }

   dc = (100 * tHigh) / tCycle; //From Parallax spec sheet, determine the percentage of the HIGH in the pulse

   angle = ((dc - dcMin) * 360) / (dcMax - dcMin + 1); //From Parallax spec sheet

   if (angle < 0)
   {
  angle = 0;
   }
   else if(angle > 359)
   {
  angle = 359;
   }

  //This is just angle calculation part, we have angle as output value from this algorithm so its possible to calculate error how much to left or right value from out target angle value and adjust servo position via standard servo library

 }

Reason why i need non blocking angle calculating is that because with everything this, i need to be able to control angles from firmata protocol and not just firmata but there can't be anything else done in sketch and i mentioned everything else causing bigger delays between reading signal, calculating angle, adjusting position, and every next function that could be placed in main loop.

So i came to the point that i need to use timer and interrupts like servo library uses by creating something like basic servo library wraper where i create PID class that inherit Servo class members for sake of accesing servo members from one object (attach, write) and two different approaches came to my mind

 1. This PID class could instead of waiting in while loop for pulseIn sacrifices another one Timer that could divide feedback signal period which is long 1,1millisecond (see documentation, heading: feedback signal) by checking if it's up or down every several microseconds and counting total signal uptime for period and then calculate angle and error and adjust position with inherited write() member for every object from one timer

 2. Using attachInterrupt that could behave similar like pulseIn but outside of main loop for every object(with same approach with PID class with inherted servo class)

  [1]: https://www.parallax.com/sites/default/files/downloads/900-00360-Feedback-360-HS-Servo-v1.2.pdf

title: What is better approach for non blocking pid algorithm?

Answers: 1

body:
The main issue you have is that `pulseIn()` is completely blocking - and your `while` loop doesn't help much either.

The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in *gated* mode. Actually you need two timers, but the Arduino already provides you `micros()` that will do for one of them.

Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.

That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses `micros()` to work out the time between successive falling edges (should be about 1100us).  A little bit of maths is needed to calculate the time from the count.

It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it.  On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.

Of course, it goes without saying that you need a gated timer for each servo you want to sense...


body:
I've been using the Arduino IDE for some time now, and I want to shift to coding for the bare AVR microcontroller. So I wanted to begin by porting required arduino libraries to C/C++.
I started with the Radiohead library, but I've noticed a lot of variables/tokens that are directly used without a definition for them. For example:

        // path :RadioHead/RH_ASK.cpp
    #if (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
     #ifdef RH_ASK_PTT_PIN
        RH_ASK_PTT_DDR  |=  (1<<RH_ASK_PTT_PIN);
        RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
        RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
     #else
        RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
        RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
     #endif
    #else
        // Set up digital IO pins for arduino
        pinMode(_txPin, OUTPUT);
        pinMode(_rxPin, INPUT);
        pinMode(_pttPin, OUTPUT);
    #endif
None of the tokens in this snippet like "RH_ASK_PTT_PIN" or  "RH_ASK_TX_PIN" were mentioned anywhere in the code before or any other file that was included.

I understand what the code does, but how does the compiler know what these tokens mean? I tried to compile this code using Atmel Studio but it gives me an error (As it should):
`"RH_ASK_PTT_PIN" not declared in this scope`
So how does this library work with the Arduino IDE?

Link to the library : https://github.com/PaulStoffregen/RadioHead

Also can someone suggest tags for this post? Its my first post here.

title: Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library)

Answers: 1

body:
They're not defined. If you notice that whole block is wrapped in a `#ifdef` which will be false unless you're on some specific platform, where the platform defines those macros.

Everything else uses the last little bit:

    pinMode(_txPin, OUTPUT);
    pinMode(_rxPin, INPUT);
    pinMode(_pttPin, OUTPUT);

You only need to care about that bit - nothing else is of any concern unless you're using a "RH_PLATFORM_GENERIC_AVR8" (whatever that is).


body:
I can't understand how to connect my arduino pro mini https://www.amazon.in/gp/product/B071ZCHW5P/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

To my HC-05 Bluetooth module https://www.ebay.in/itm/HC05-Wireless-Bluetooth-RF-Transceiver-Module-Serial-TTL/182970488321?ssPageName=STRK:MEBIDX:IT&_trksid=p2057872.m2749.l2649

There is a guide to connect them given here : http://www.instructables.com/id/Bluetooth-Serial-Adapter-for-Pro-Mini/

I am trying to follow this guide but it is for 5V version and involves shorting the diode on the pro mini plus a divider circuit.

Here is the circuit:[![enter image description here][1]][1]

Apparently, there is an obvious difference in the circuit according to my components.

Please help me connect them correctly.

Thanks :)

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

title: Is there a bridge needed to connect Pro Mini 3.3v to HC-05 (level 3.3v)?

Answers: 0


body:
I have a joystick, an I2C 16x2 character display, and an Arduino. I want to move the joystick and get an on-screen character (specifically, the letter h) to move in the direction that I pushed the joystick. Here is the Arduino code.

    #include <LiquidCrystal_I2C.h>
    int xVal;
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    int yVal;

    int blockPos[]= {8, 0};
    int blockPosBack[]= {8, 0};

    int ycal;
    int xcal;
    void setup() {

        lcd.begin();
        lcd.clear();
        lcd.backlight();
    Serial.begin(9600);

    pinMode(A0, INPUT);

    pinMode(A2, INPUT);
    lcd.setCursor(blockPos[0], blockPos[1]);
    //lcd.print("h");

    ycal = 500;
    xcal = 514;
    }

    void loop() {

    xVal = analogRead(A0);

    yVal = analogRead(A2);

    Serial.print(" Y is...");

    Serial.print(yVal);

    Serial.print(" X is...");

    Serial.println(xVal);

    blockPosBack[0] = blockPos[0];
    blockPosBack[1] = blockPos[1];

    if(xVal < (xcal - 150)){
      if(blockPos[0] > 0){
        blockPos[0] - 1;
        }
      }

      if(xVal > (xcal + 150)){
      if(blockPos[0] < 15){
        blockPos[0] + 1;
        }
      }

      if(yVal < (ycal - 150)){
      if(blockPos[1] > 0){
        blockPos[1] -1;
        }
      }

      if(yVal > (ycal + 150)){
      if(blockPos[1] < 1){
        blockPos[0] +1;
        }
      }
    if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
      lcd.clear();}
      lcd.setCursor(blockPos[0], blockPos[1]);
      lcd.print("h");
    }

The problem is, I get a message saying that "expected ')' before '!' token". How do I solve this, and how do I change the code to make it functional?

Edit: I learnt that '!' is not the same as 'not equal to', which is '!='. I tried this, but now the h just sits at the initial position but doesn't move when I move the joystick. What do I have to change in the code to make it work?

title: What do I have to change to make this code functional?

Answers: 3

body:
!! is not a valid logical operator, you probably meant || for locical OR?

Did you verify that the condition to change the blockpos value is actually fulfilled? Means are you sure one of your if blocks is actually executed?

body:
Like stated in my comment, to have proper condition for clearing the display, the condition you should want to meet are:

`if ( (newX != previousX) OR (newY != previousY)) {
    clearLCD()
}`

EDIT: Or else, what you're saying is that you're only clearing the display when you have changed both X and Y _at the same time_

And to adress your problem with the 'h' not moving, you need to change the lines
`blockPos[0] - 1;` etc

into

`blockPos[0] = blockPos[0] -1;`

or

`blockPos[0]--;`

or else, you're not really assigning the new value to the variable containing the position to use in the display.

body:
First of all you should have edited the code way better, if you want help and want us to understand you must edit it properly.

    if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
      lcd.clear();}
      lcd.setCursor(blockPos[0], blockPos[1]);
      lcd.print("h");
    }

I took some time to understand that lcd.setCursor and lcd.print wansn't part of the if. When you are using 2 different sensors or components, you must try them separatly first, and when you got them both working fine that's when you use them together.
[https://www.arduino.cc/en/Tutorial/JoyStick][1]

  [1]: http://www.arduino.cc/en/Tutorial/JoyStick

This is an example pretty much more simple than yours, so i just think you must try lcd first, and when you understand how lcd works, and how joystick works, you can easly interact them.


body:
I'm currently drawing black boxes over old content before displaying constantly refreshing content on my display, so for instance to display temperature:

    if (sensorTemp != nowTemp){
        nowTemp = sensorTemp;
        tft.fillRect(0,52,88,21,ILI9341_BLACK);
        return nowTemp;
    }

If I don't do this the display will just overlay content until it becomes a white blob.

However, this solution leaves me with a black flickering on the display and I can't control exactly what is refreshed where. So for instance when I want to display the current time or date it has to refresh the date all the time, even though nothing changed.

    void loop() {
      tft.setTextSize(2);
      tft.setCursor(0,0);
      tft.print(rtc.getDateStr());
      tft.fillRect(144,0,199,15,ILI9341_BLACK); //Black box drawn over 'old' time data
      tft.setCursor(144,0);
      tft.print(rtc.getTimeStr());  //Draw new time
      tft.setCursor(0,52);
      tft.print(tempCall());  //call function to check on temperature and draw new data if necessary
    }

Is there a more elegant solution to this problem?

title: Elegant solution for refreshing TFT display content?

Answers: 4

body:
The Adafruit GFX library has two functions for setting the text colour:

    setTextColor(uint16_t c)
    setTextColor(uint16_t c, uint16_t bg)

The first sets both the foreground and background to the same colour, and the second to two different colours.  You may ask why you would want the foreground and background to be the same - well, the library handles that situation as a special case: it makes the background transparent.

By setting the foreground and background to different colours you force the library to draw that background colour in over whatever is already on the screen.

    tft.setTextColor(ILI93481_WHITE, ILI9341_BLACK);

With that any background pixels in the text string will be coloured black and the text itself white.  As long as the string you are printing is the same length as the text that is already there it will be replaced completely.

body:
If you look in the "Adafruit_GFX.cpp" you will see the following.

    void Adafruit_GFX::setTextColor(uint16_t c) {
     // For 'transparent' background, we'll set the bg
     // to the same as fg instead of using a flag
     textcolor = textbgcolor = c;
    }

    void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
     textcolor   = c;
     textbgcolor = b;
    }

If you only want to Draw the Character with a transparent background meaning you only write the character setTextColor in the prescribed pixels changing none of the surrounding pixels in the character block defined by x, y, setTextSize.

    TFT.setTextColor(GREEN); //With Transparent Text Background not updating surrounding pixels.

If you want to Draw the Character with your background color, replace app pixels in the character block defined by x, y, setTextSize with your chosen text color and your background to be the same as your chosen background. This will overwrite all pixels with old character that are no longer used with the background color all at the same time preventing mess of pixels, and character flashing.

    TFT.setTextColor(GREEN, BLACK); //With Text Background Color updating surrounding pixels.

body:
Hmm the solution is how the code is written...no fancy stuff...the KIWI way

    //in setup function add tft.fillScreen(ST7735_GREEN);

    void loop(){

      int lightIntensity = myBH1750.getLux();
      tft.setTextSize(3);
      tft.setCursor(10,10);
      tft.setTextColor(ST7735_RED);
      tft.print(lightIntensity);
      delay(3000);
      tft.setTextColor(ST7735_GREEN);
      tft.setCursor(10,10);
      tft.print(lightIntensity);
      tft.setCursor(10,50);
      tft.setTextColor(ST7735_BLUE);
      tft.print("LUX");
    }

body:
This code works well and accounts for values of different length.

    void textValue() {
      float newValue = @your input@;
      int numChars = String(newValue).length(); // Get the number of characters
      int valueWidth = numChars * 6 * 2.5;

      if (valueWidth != previousValue) {
        tft.fillRect(0, 55, previousValue, 30, ST77XX_BLACK);
        previousValue = valueWidth;
      }
      tft.setCursor(3,60);
      tft.setTextColor(ST77XX_WHITE, ST77XX_BLACK);
      tft.setTextSize(2.5);
      tft.print(newValue);
    }