# Question
Title: sensitive distance detection using 2 HC-05 module/ 2 arduino unos
Hi I am doing a project in which I use 2 HC-05 modules and 2 arduino unos driving them. 1 bluetooth module is master and the other is slave. Master module is stationary while slave is moving. If the distance between these 2 modules is less than 1.5 meter, master device turns on a led. If the distance is more than 1.5 meter, the led will not be turned on. This is the basic idea and it works but not as I wanted. I present the code

master device code:

```
#include <SoftwareSerial.h>
//master device code
SoftwareSerial BTSerial(5, 6); // RX | TX
#define LED 4
unsigned long timer = 0;
unsigned long timeDifference = 0;
char data;

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(9600);
  pinMode(LED, OUTPUT);
  delay(5000);
}

void loop()
{
  BTSerial.write('A');
  timer = millis();
  while(!BTSerial.available()){}
  data = BTSerial.read();
  if(data =='B'){
    timeDifference = millis()-timer;
  }
  Serial.println(timeDifference);

  if(timeDifference < 280){
    digitalWrite(LED,HIGH);
  }else{
    digitalWrite(LED,LOW);
  }
  delay(500);

}

```

slave device code:

```
#include <SoftwareSerial.h>
//slave device code
SoftwareSerial BTSerial(5, 6); // RX | TX

char data;

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

void loop()
{
  while(!BTSerial.available()){}
  data = BTSerial.read();
  if(data =='A'){
    BTSerial.write('B');
  }

}

```

So what happens here is that master device sends a char and starts timer. Slave receives the char and send another char to master device. When master device receives char, it stops timer and looks at how much time passed. The problem is that when I put those bluetooth devices together, the time difference is like 280ms. When I move away in the room with slave device, it is still like same. It is not sensitive. What can I do to make this more sensitive? I am waiting for your opinions

# Answer
The approach you're using will not work. You're trying to use speed of light time measurement to gauge distance. There are a whole host of problems with that. First, the clock on the Arduino is not fast enough (high enough resolution). You need accurate, sub-nanosecond time resolution for that (see this video: https://www.youtube.com/watch?v=9eyFDBPk4Yw). Second, BLE is a packet protocol. The overhead and variability of sending packets will totally swamp the **tiny** difference in round-trip time due to speed of light delay.

The usual way to gauge distance with BLE is to measure signal strength. That is also error-prone, but you can at least get rough "immediate", "near", "middle" and "far" distance measurements.

Alternately you could use and ultrasonic range sensor.
> 1 votes

# Answer
In addition to the concerns above, your code won't work the way you want it to. You are initializing timer every loop so the time difference will always be 0. Instead, you should only write `A` from master device when it receives the response `B` and only then reset `timer`.

```
void loop()
{
  while(!BTSerial.available()){}
  data = BTSerial.read();
  if(data =='B'){
    timeDifference = millis()-timer;
    timer = millis();
    BTSerial.write('A');
  }
  Serial.println(timeDifference);

  if(timeDifference < 280){
    digitalWrite(LED,HIGH);
  }else{
    digitalWrite(LED,LOW);
  }
  delay(500);
}

```
> 0 votes

# Answer
Your approach is never going to work no matter how hard you try; it's like trying to use a hammer to bake bread! If you need accurate time-of-flight distance measurements, use a sensor designed to do that, like the ST Micro VL53L0X time-of-flight IR LIDAR module.
> 0 votes

---
Tags: bluetooth, hc-05
---


# Question
Title: I want to make two arduino to communicate over different wifi. Is that possible?
I want to make any 2 Arduino module from different places to communicate over wifi. I really need to know if it possible? If yes, advice me more about it. I want send data from sensor module from one Arduino to another and vice versa. That's the basic idea. Do I need a third party services such as cloud services to make it happen? Or simply can send ovee wifi with the help of Ip adress. Sorry, I have less knowledge on this. Help me out. Thank you in advance.

# Answer
> 1 votes
If they are on the same (wifi) network; then yes.

If you are on a different network, it would be more difficult. You would have to setup port forwarding on your router. Then you would have to somehow know the public IP address of the other router. These addresses can change from time to time with certain ISPs. I wouldn't advice doing this.

Instead I'd go with an third party service. For example Adafruits offers an MQTT server. I'd probably use this even if they are on the same network.

---
Tags: arduino-uno, wifi, communication, network
---


# Question
Title: Why is my transistor switched output so low?
Help needed! I am using an Arduino Nano and a general purpose npn (2n2222a) transistor to provide a 12v signal to a low current 12vdc load in an automobile. The Arudino code is set to pulse D2 at bootup/startup for .5 second. The PWM output setting was 255 (since switched to digitalWrite). However, the switched output measures only 4.5v (expected close to 12v). What am i doing wrong? Applying 12v+ directly to the black box works. The purpose is to simulate a temporary button push in the car so an auto function is enabled.

# Answer
> 10 votes
The problem is that you are using an NPN transistor as a high side switch.

The voltage at the emitter of the transistor will always be about 0.7V below the voltage at the base. The "high" output from the Arduino is 5V. The emitter will be at about 4.3V.

Have a look at the Wikipedia "emitter follower" page. The emitter follower is also called a common collector circuit. That explains the "problem" in more detail. It is only a problem in so far as it is not the correct solution for your task.

You need to use a "common emitter" circuit.

This usage is commonly called a "low side switch."

That would look like this:

simulate this circuit – Schematic created using CircuitLab

If your black box really needs its input pulled up to 12V, then you would do something like this:

simulate this circuit

The resistor values and transistor part numbers are place holders. The values of resistors you will need depends on the transistors you use. The transistor selection will depend on how much current you need to deliver to the black box.

I see in a comment that your black box only needs a few milliamperes. In that case, the shown transistors should work just fine. The resistor values may be a little too high, but I think they'll be OK.

---

A couple of additional points:

1. The Arduino has PWM outputs, not PCM.
2. The output voltage for your black box will be pulsing if you use any PWM value lower than 255. Your black box probably won't like that, and your voltmeter won't read a correct voltage.

You should use D2 as a digital output rather than PWM. Just turn it on or off rather than fiddling with the PWM duty cycle. Use "digitalWrite" instead of "analogWrite" on pin D2.

# Answer
> 3 votes
The 2N2222 is an *NPN* device. Skipping all of the physics involved, that means that (in your application) it will ***sink*** current as a *low-side switch*, but not ***source*** current as a *high-side switch*.

If you want a *high-side switch*, you should find a *PNP* transistor. In this case your Nano pin will **sink** current from the transistor's base terminal.

I would recommend you stick with the 2N2222, but make two changes:

1. Connect your "black box" between the positive terminal (+) of your 12V supply, and the **collector** terminal of the 2N2222.
2. Reduce the size of your base resistor from 10Kohms to 1Kohms

# Answer
> 2 votes
What I have thought about is using an opto-coupler

Connect the Arduino pin output to pin 1 through 330 ohms resistor, pin 2 to ground of Arduino, connect pin 4 to Vcc of 12 V and finally connect pin 3 to the black box load.

Try this configuration

Since black box only needs few milliamps as you said May be the transistor is not ***saturated*** since base current has to go through the black box load opto-coupler s have ***no base current instead they use photons***

Here is the circuit diagram

5 V supply looks like the Arduino pin D2 and lamp is the black box load. This is 4N35 example

# Answer
> 1 votes
ok, so i chose the 2 transistor high side circuit as i had the needed pnp transistor laying around. Works great, thanks everyone for your help. The trace (5v/div) shows the Arduino signal at 5v and the circuit output at 12v - perfect!

---
Tags: voltage
---


# Question
Title: Measure audio frequency through pulse duration
Hello dear StackExchange users,

i want to develop an Infrared blaster which i can plug into the headphone jack of a phone or console of choice. In order to communicate what frequency to modulate the diode with and how long to send pulses, i simply generate tones for the Arduino to read and interpret.

My problem is that i can't reliably measure the frequency with it. In order to measure the frequency i use an Analog Comparator Interrupt and trigger at falling edge, thus getting always the interrupt after a full pulse occured. I called micros() at every interrupt in order to get the pulse duration, but it was too imprecise. Then i tried using Timer0 with a prescaler of 8 to measure the frequency, but it only counts to 255.

Now i switched over to Timer1 because of it's bigger TCNT register. However for some reason it already overflows at 255 even though i didn't set the OCR1 registers.

This is my current code. Please note that the actual frequency calculation happens in the main loop to not mess with the measurements gained in the ISR.

```
const int setFrequencySound = 1000;
const int receiveDataSound = 2000;
const int receiveDataEndSound = 3000;

const int readyMode = 0;
const int setFrequencyMode = 1;
const int receiveDataMode = 2;
const int sendDataMode = 3;

volatile unsigned long timeBefore;
volatile unsigned long timeNow;
volatile unsigned long delta;
volatile float audioFrequencyBefore;
volatile float audioFrequency;

volatile float irFrequency;
volatile int irData[100];
volatile int irDataIndex;

volatile int mode = 0;

ISR (ANALOG_COMP_vect)
{
timeNow = TCNT1;
Serial.print (timeNow);
Serial.println (" TCNT1");
//TCNT1 = 0; //reset timer register
}

void setup ()
{
Serial.begin (115200);
Serial.println ("Started.");
ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
      | bit (ACIE)    // Analog Comparator Interrupt Enable
      | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)

TCCR1B |= (0 << CS12) | (1 << CS11) | (0 >> CS10); //Activate timer and set prescaler to 8
TCNT1 = 0; //Reset timer register
}  // end of setup

void loop ()
{
//Calculate frequency by using the period duration
//determined through the timestamps captured in
//ISR method.
//delta = timeNow - timeBefore;
audioFrequency = 1000000000.0 / (float(timeNow) * 2.0);

if (millis() % 1000 == 0)
{
  Serial.print (audioFrequency, 5);
  Serial.print (" Hz, ");
  Serial.print (timeNow);
  Serial.println (" TCNT0");
}

//Do not process the same frequency multiple times
if (audioFrequency != audioFrequencyBefore)
{
  switch (mode)
  {
    case readyMode:
      if (audioFrequency == setFrequencySound)
      {
        mode = 1;

        Serial.println ("Start setting IR frequency.");
      }
      else if (audioFrequency == receiveDataSound)
      {
        mode = 2;

        Serial.println ("Start receiving IR data.");
      }
      break;
    case setFrequencyMode:
      irFrequency = audioFrequency + 25000;

      Serial.print ("IR frequency set to ");
      Serial.print (irFrequency, 10);
      Serial.println (" Hz.");

      mode = readyMode;
      break;
    case receiveDataMode:
      if (audioFrequency == receiveDataEndSound)
      {
        Serial.println ("Stop receiving IR data.");

        mode = readyMode;
        irDataIndex = 0;
      }
      else
      {
        irData[irDataIndex] = audioFrequency;

        irDataIndex++;

        Serial.print ("IR pulse received: ");
        Serial.print (irData[irDataIndex]);
        Serial.println (" microsecs.");
      }
      break;
    case sendDataMode:
      Serial.println ("Sending IR data...");
      break;
  }
}

audioFrequencyBefore = audioFrequency;

}  // end of loop

```

# Answer
> 5 votes
Timer 1 overflows at 255 because that's how it has been configured by the Arduino core, as it is intended to provide 8-bit PWM. If you want to use the timer in normal mode, you should undo the Arduino's initialization by setting `TCCR1A` to zero.

Two comments on the ISR:

```
ISR (ANALOG_COMP_vect)
  {
    timeNow = TCNT1;
    Serial.print (timeNow);
    Serial.println (" TCNT1");
    //TCNT1 = 0; //reset timer register
  }

```

First, as has been stated in a previous comment, you should not print from within an ISR. Also, if you want consistent timing, you should never reset the timer. Just keep it freely running and use time differences to get the signal period. Do not worry about the timer overflowing: if you do the computation with unsigned 16-bit integers (`uint16_t`), you will be immune to the overflows. If you reset the timer you will likely loose some ticks, as you can not read it and reset it in the same clock cycle.

Lastly, I recommend you read about the “input capture” capability of Timer 1. This is a feature of the timer designed for solving the exact kind of problem you have here: the timer will automatically record a timestamp on an external event. You can have this triggered by a rising or falling edge on input pin 8, or by the analog comparator if you prefer. This method gives you zero jitter, which cannot be achieved with code, even running within an interrupt.

---

**Edit**: Answering an extra question in the comment.

> Could i connect the audio wire \[...\] directly to pin 8 and use the input capture functionality?

It depends on the shape of the signal that comes out of this wire. First, you have to make sure the signal always stays between the electric potentials of GND and Vcc (i.e. 0 – 5 V), otherwise you risk damaging the Arduino.

Note that if the signal comes from a high impedance source, it can safely go somewhat beyond this range, as the Arduino has all of its inputs protected by diodes. You just have to limit the current in the diodes to less than 1 mA. In other words, for each kΩ of output impedance, you can extend the (unloaded) acceptable voltage range by 1 V on each side. If the source is low impedance, you can make it high impedance simply by adding a 10 kΩ resistor in series.

Second point is, you have to make sure the signal has a large enough voltage span to make the digital input switch between LOW and HIGH. According to the datasheet of the ATmega328P, when powered at 5 V the input thresholds are typically around 2.1 V for switching LOW and 2.6 V for switching HIGH. The difference between those thresholds provides some hysteresis, which can help cancelling noise. Note that those are typical values. If you want *guaranteed* switching, the signal should go below 1.5 V to get a guaranteed LOW reading (this is VIL) and above 3 V to get a guaranteed HIGH reading (VIH).

Note also that, if the input thresholds of the digital pin do not fit your needs, you can use the analog comparator as a trigger for the input capture.

---
Tags: arduino-nano, timers, frequency
---


# Question
Title: L239D motor driver not able to drive motors
I am making a line follower robot. The issue is trying to make the motors run.

The L239D module has 4 input pins (to control two motors), 4 output pins (to drive motors), and 6 power pins (5V, 5V, GND, GND, 9/12V, and 9/12V).

I have used one 5V pin to connect it to an Arduino's 5V supply and one of the 9/12V pins to two 9V batteries in series.

The motors are barely running and when the robot is on the ground it is not able to move. I even tried three 9V batteries in series to get the voltage up to 27V but it doesn't help.

# Answer
9 V batteries, assuming you mean the little PP3-size ones, can't supply the current needed for driving robot motors; they are intended for low-current applications.

Putting them in series will give you a higher voltage, not more current, and the higher voltage could damage something else in the circuit.

*Assuming you connected everything correctly, including ground:* you need bigger batteries. Even 6 AAs in series would be much better than using a 9V battery for getting your robot to move.
> 1 votes

# Answer
On your next try use a different H-Bridge, one with MOSFET outputs, you can have a voltage drop across the L239D of 2.4V. Measure the voltage at the motor and at your batteries you will see what I am getting at. You might want to try connecting the motors directly to the battery first to see if it will do what you want.
> 0 votes

# Answer
I guess using 9 Volt battery in parallel will do your work because if the motor is moving as you quoted above means it is getting the voltage but not enough current to drive it, please connect the 9 volt battery in parallel and it will work for you
> 0 votes

---
Tags: arduino-uno, arduino-motor-shield, robotics
---


# Question
Title: Arduino if, else if conditions being overlooked
Hi Im very new to coding and I'm struggling to fix a problem. I want the user to input a yes or no answer to a question and based on the answer I want the right text to show on the serial monitor and a LCD as well as the right LED light to light up. However it seems like the if and else if statements are ignored and no matter what the user input is the last else statement is the only thing that shows up.

My second problem is with the switchLead. The LED that shows the condition of the switchLead does not turn off when the switchLead is open.

This is just school work so it has to be basic. Please let me know where I made a mistake! Also this is my first post so let me know how I could make this more clear. Thanks!

```
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

String input;                   // Declate string variable to hold user input

const int whiteLead = 2;
const int switchLED = 13;
const int RED1 = 9;
const int YELLOW1 = 8;
const int GREEN1 = 7;

int switchLead = 0;

void setup() {
  Serial.begin(9600);          // Serial transmission activated baud rate 9600 bits per sec
  lcd.begin(16,2);             // Initialise I2C LCD 16 columns with 2 rows
  lcd.backlight();

pinMode(whiteLead,INPUT);
pinMode(switchLED,OUTPUT);
pinMode(RED1,OUTPUT);
pinMode(YELLOW1,OUTPUT);
pinMode(GREEN1,OUTPUT);

switchLead = digitalRead(whiteLead);       // Read the state of the switchLead value
if (switchLead == HIGH) {                  // Begin if; if whiteLead is open do;
  digitalWrite(switchLED, LOW);
  digitalWrite(RED1,LOW);
  digitalWrite(YELLOW1,LOW);
  digitalWrite(GREEN1,LOW);

}                                          // End if
else {                                     // Begin else; Check if the switchLead is closed, turn LED ON
  digitalWrite(switchLED, HIGH);           // Turn switch LED ON
}                                          // End else
}                                          // End void setup

void loop() {                               // Void loop begins
  Serial.println("Is the room in use? ");   //Prompt user to input answer
  while (Serial.available()==0) {}          // Wait for user input
  input = Serial.readString();              // Read user input and store it in variable input

   if (input == "Yes") {               // Begin if: if user input is yes

    lcd.setCursor(0,0);
    lcd.print("In use");
    Serial.print("The room is ");
    Serial.println("in use");
    digitalWrite(switchLED,HIGH);
    digitalWrite(RED1,HIGH);
    digitalWrite(GREEN1,LOW);
    digitalWrite(YELLOW1,LOW);
  }
  else if (input == "No") {

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Empty");
    Serial.print("The room is: ");
    Serial.println("empty");
    digitalWrite(switchLED,HIGH);
    digitalWrite(GREEN1,HIGH);
    digitalWrite(RED1,LOW);
    digitalWrite(YELLOW1,LOW);
  }
    else {                                // Begin else

    lcd.clear();                        // Clear LCD display
    lcd.setCursor(0,0);                 // Set LCD cursor to column 0, row 0
    lcd.print("Preparing");             // Print message enclosed in brackets on LCD
    Serial.print("The room is ");       // Print message enclosed in brackets to computer monitor
    Serial.println("being prepared");   // Print message enclosed in brackets to computer monitor
    digitalWrite(YELLOW1,HIGH);         // Turn YELLOW1 ON
    digitalWrite(GREEN1,LOW);           // Turn GREEN1 OFF
    digitalWrite(RED1,LOW);             // Turn RED1 OFF
  }                                     // End else
}                                       // End void loop

```

# Answer
Try to use this command

```
input = Serial.readStringUntil('\n');

```

Instead of `input = Serial.readString();`

and also use `while (Serial.available() > 0)`

Instead of `while (Serial.available()==0)`

and where you used `int switchLead = 0;`

Try to use `bool switchLead;`

I hope these changes in the code will help you
> 1 votes

---
Tags: arduino-uno, led, lcd
---


# Question
Title: 3.5 inch TFT LCD connection diagram with mega r3
Forum post

I would like to ask if someone has this shield fully working.

My biggest problem is the touch screen that i couldn't manage to make it work.

Here is the code i am using:

```
// ic: ili9327
#define LCD_RD   A0
#define LCD_WR   A1
#define LCD_RS   A2
#define LCD_CS   A3
#define LCD_REST A4

void Lcd_Writ_Bus(char VH)
{
 unsigned char i,temp,data;
 data=VH;
 for(i=8;i<=9;i++)
 {
   temp=(data&0x01);
   if(temp)
     digitalWrite(i,HIGH);
   else
     digitalWrite(i,LOW);
   data=data>>1;
 }
 for(i=2;i<=7;i++)
 {
   temp=(data&0x01);
   if(temp)
     digitalWrite(i,HIGH);
   else
     digitalWrite(i,LOW);
   data=data>>1;
 }

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

void Lcd_Write_Com(char VH)
{
 digitalWrite(LCD_RS,LOW);
 Lcd_Writ_Bus(VH);
}

void Lcd_Write_Data(char VH)
{
 digitalWrite(LCD_RS,HIGH);
 Lcd_Writ_Bus(VH);
}

void Lcd_Write_Com_Data(int com,int dat)
{
 Lcd_Write_Com(com);
 Lcd_Write_Data(dat);
}

void Address_set(unsigned int x1,unsigned int y1,unsigned int x2,unsigned int y2)
{
 Lcd_Write_Com(0x2a); // Set_column_address 4 parameters
 Lcd_Write_Data(x1>>8);
 Lcd_Write_Data(x1);
 Lcd_Write_Data(x2>>8);
 Lcd_Write_Data(x2);

 Lcd_Write_Com(0x2b); // Set_page_address 4 parameters
 Lcd_Write_Data(y1>>8);
 Lcd_Write_Data(y1);
 Lcd_Write_Data(y2>>8);
 Lcd_Write_Data(y2);

 Lcd_Write_Com(0x2c); // Write_memory_start
}

void Lcd_Init(void)
{
 digitalWrite(LCD_REST,HIGH);
 delay(5);
 digitalWrite(LCD_REST,LOW);
 delay(15);
 digitalWrite(LCD_REST,HIGH);
 delay(15);

 digitalWrite(LCD_CS,HIGH);
 digitalWrite(LCD_WR,HIGH);
 digitalWrite(LCD_CS,LOW);  //CS

 Lcd_Write_Com(0xE9);
 Lcd_Write_Data(0x20);

 Lcd_Write_Com(0x11); //Exit Sleep
 delay(100);

 Lcd_Write_Com(0xD1);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x71);
 Lcd_Write_Data(0x19);

 Lcd_Write_Com(0xD0);
 Lcd_Write_Data(0x07);
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x08);

 Lcd_Write_Com(0x36);
 Lcd_Write_Data(0x48);

 Lcd_Write_Com(0x3A);
 Lcd_Write_Data(0x05);

 Lcd_Write_Com(0xC1);
 Lcd_Write_Data(0x10);
 Lcd_Write_Data(0x10);
 Lcd_Write_Data(0x02);
 Lcd_Write_Data(0x02);

 Lcd_Write_Com(0xC0); //Set Default Gamma
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x35);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x02);

 Lcd_Write_Com(0xC5); //Set frame rate
 Lcd_Write_Data(0x04);

 Lcd_Write_Com(0xD2); //power setting
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x44);

 Lcd_Write_Com(0xC8); //Set Gamma
 Lcd_Write_Data(0x04);
 Lcd_Write_Data(0x67);
 Lcd_Write_Data(0x35);
 Lcd_Write_Data(0x04);
 Lcd_Write_Data(0x08);
 Lcd_Write_Data(0x06);
 Lcd_Write_Data(0x24);
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x37);
 Lcd_Write_Data(0x40);
 Lcd_Write_Data(0x03);
 Lcd_Write_Data(0x10);
 Lcd_Write_Data(0x08);
 Lcd_Write_Data(0x80);
 Lcd_Write_Data(0x00);

 Lcd_Write_Com(0x2A);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0xeF);

 Lcd_Write_Com(0x2B);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x01);
 //  Lcd_Write_Data(0x3F);
 Lcd_Write_Data(0x8F); // on internet

 Lcd_Write_Com(0x29); //display on

 Lcd_Write_Com(0x2C); //display on

 digitalWrite(LCD_CS,HIGH);
}

void H_line(unsigned int x, unsigned int y, unsigned int l, unsigned int c)
{
 unsigned int i,j;
 Lcd_Write_Com(0x02c); //write_memory_start
 digitalWrite(LCD_RS,HIGH);
 digitalWrite(LCD_CS,LOW);
 l=l+x;
 Address_set(x,y,l,y);
 j=l*2;
 for(i=1;i<=j;i++)
 {
   Lcd_Write_Data(c);
 }
 digitalWrite(LCD_CS,HIGH);
}

void V_line(unsigned int x, unsigned int y, unsigned int l, unsigned int c)
{
 unsigned int i,j;
 Lcd_Write_Com(0x02c); //write_memory_start
 digitalWrite(LCD_RS,HIGH);
 digitalWrite(LCD_CS,LOW);
 l=l+y;
 Address_set(x,y,x,l);
 j=l*2;
 for(i=1;i<=j;i++)
 {
   Lcd_Write_Data(c);
 }
 digitalWrite(LCD_CS,HIGH);
}

void Rect(unsigned int x,unsigned int y,unsigned int w,unsigned int h,unsigned int c)
{
 H_line(x  , y  , w, c);
 H_line(x  , y+h, w, c);
 V_line(x  , y  , h, c);
 V_line(x+w, y  , h, c);
}

void Rectf(unsigned int x,unsigned int y,unsigned int w,unsigned int h,unsigned int c)
{
 unsigned int i;
 for(i=0;i<h;i++)
 {
   H_line(x  , y  , w, c);
   H_line(x  , y+i, w, c);
 }
}

void LCD_Clear(unsigned int j)
{
 unsigned int i,m;
 Lcd_Write_Com(0x02c); //write_memory_start
 digitalWrite(LCD_RS,HIGH);
 digitalWrite(LCD_CS,LOW);
 Address_set(0,0,479,399);

 for(i=0;i<480;i++)
   for(m=0;m<400;m++)
   {
     Lcd_Write_Data(j);
   }
 digitalWrite(LCD_CS,HIGH);
}

void setup()
{
 for(int p=2;p<10;p++)
 {
   pinMode(p,OUTPUT);
 }
 pinMode(A0,OUTPUT);
 pinMode(A1,OUTPUT);
 pinMode(A2,OUTPUT);
 pinMode(A3,OUTPUT);
 pinMode(A4,OUTPUT);
 digitalWrite(A0, HIGH);
 digitalWrite(A1, HIGH);
 digitalWrite(A2, HIGH);
 digitalWrite(A3, HIGH);
 digitalWrite(A4, HIGH);
 Lcd_Init();
 LCD_Clear(0x00);
}

void loop()
{

 for(int i=0;i<1000;i++)
 {
   Rect(random(300),random(300),random(300),random(300),random(65535)); // rectangle at x, y, with, hight, color
 }
 LCD_Clear(0x00);
}

```

Here are some pictures:

1 http://imageshack.com/a/img908/7546/YEctM8.jpg 3 http://imageshack.com/a/img537/5378/GIWz2x.jpg

Any suggestions?

# Answer
Try to use MCUFriend kbv library I used this library for a 3.5 inch display and the driver on it was ILI9486 this library includes all the function and I have tested the touch also this library works good for it also
> 0 votes

---
Tags: arduino-mega, lcd
---


title: WS2812B Reset time

text:
# Question
Title: WS2812B Reset time
i am trying to implement the ws2812b with an atmega8,but i didn't understand a thing very well. if i pull low for \>50 us, it says it resets, but what does that mean? it resets the current LED all data to 0 and latches the next data to the next led?

# Answer
It's the "communication" reset. You pull the data pin low for 50uS or more to start a new batch of communication.

It's illustrated in the datasheet here:

As you can see, between each batch of bits being sent the reset code is set. This is so that the first chip knows to start receiving again and not pass any data on until it's had all 24 of its bits.
> 1 votes

---
Tags: ws2812, atmega
---


title: esp32 voltage divider readings off

text:
# Question
Title: esp32 voltage divider readings off
Trying to read from a voltage divider circuit using two 240 Ohm resistors. Getting a reading of 6.0, when it should be 1.65. Circuit is powered by a bench 3.3V and both the Huzzah32 and circuit are grounded. Using USB for the Huzzah32. Any thoughts?

```
  void setup()
{
  Serial.begin(9600);
}
void loop()
{
  int sensorValue = analogRead(A9);
  float voltage = sensorValue * (3.3 / 1023.0);
  Serial.println(voltage);
  delay(1000);
}

```

# Answer
> 1 votes
First, ESP32 ADC is 12-bit, not 10-bit. therefore the formula should be:

```
float voltage = sensorValue * (3.3 / 4096.0);

```

Secondly, ESP32 ADC is not really linear, and tend to have lower reading than the actual value. You will need to do some calibration if you want to get a more accurate reading. You can take a look at my github on esp32-adc-calibrate.

---
Tags: esp32, voltage-divider
---


# Question
Title: Powering Arduino Components with AA in Parallel and Series
simulate this circuit – Schematic created using CircuitLab

I have 6 AA batteries that I would love to power my Arduino Nano and HCSR04 ultrasonic sensor. However, for my low power application I want to use the bare minimum power required for the components. Since the Nano can run as low as 4.5 volts and the sensor requires 5 volts, I think the best solution would be 4 AA batteries in series to power the hcsr04 and 3 AA batteries in series to power the nano. Since I have 6 batteries I was thinking 3 AA batteries wired in parallel with 3 AA series batteries. I drew the circuit diagram above and realize something is horribly wrong. So I was hoping someone could point me in the right direction.

# Answer
Wiring 6 batteries up so it gives you both a stack of 3 and a stack of 4 is not easy, and although you can do it you shouldn't do it. The only arrangement is this:

simulate this circuit – Schematic created using CircuitLab

(The grey link is optional and makes little difference if it's there or not).

The reason you shouldn't really do that arrangement is that you have a mismatch in your capacities, as `[BAT1+BAT2] || [BAT3+BAT4]` has more capacity than `BAT5`, so the current drawn from the 4.5V output will cause BAT5 to go flat far sooner than the others. This will then cause BAT5 to take a reverse charge as current from the other cells flows through it damaging it permanently (especially bad for rechargeable batteries as you will not be able to recharge it, but pretty nasty for alkaline batteries too).

Another consideration when running from different voltages like this is the communication between the different units. If the Arduino is running at a lower voltage the signals it sends out will be of a lower voltage, and it expects to receive signals at a lower voltage. Likewise with the HC-SR04; it will expect to receive higher voltage signals and will send out higher voltage signals. So you will require some logic level translation between the two devices to correct that mismatch in the signal voltages.

As you can see it's all starting to get a little messy now.

A much simpler solution is to keep everything at one voltage. The ideal voltage is 5V since that is the common voltage that all the devices expect to work at.

Since you are running from batteries you want efficiency. To that end you need an efficient solution for generating a stable 5V. The Arduino's built-in regulator is far from efficient, so that can be instantly discounted.

A more efficient solution is a step-down or "buck" switching regulator. This uses PWM to rapidly turn the power on and off (before then filtering and smoothing it) to effectively convert voltage into current.

You'd run your system off a voltage higher than 5V then use a switching regulator to reduce the voltage down to 5V. Since you have 6 batteries at your disposal the logical voltage would be 6x1.5V = 9V - all 6 batteries in series:

simulate this circuit

If you're running non-rechargeable batteries then you don't need to worry about low-voltage cutoff (you shouldn't over-discharge rechargeable batteries), so this arrangement will get the most out of your battery life. Depending on the "drop out" voltage of the regulator (you can get some with a "zero drop-out bypass" mode) your batteries could get down as far as 0.8V each before the system starts to become unstable (even lower if your HC-SR04 is one of the "upgraded" ones that can run from 3V).
> 2 votes

---
Tags: arduino-nano, battery
---


# Question
Title: How can I use separate power source for the Arduino and the motors
How can use a separate power source for powering Arduino, and another battery for powering the motors? How can I make connections through the motor driver module L298N? I know how normally we use one battery to power the Arduino as well as the motors. But I am facing the problem while using different power sources.

# Answer
> 1 votes
That motor driver has an optional on-board 5V regulator. It can be enabled / disabled with a jumper.

With that regulator enabled you just need to connect a ground and your control signals (ENA/IN1/IN2 or ENB/IN3/IN4).

If you disable that regulator (remove the jumper) then you need to provide power from the Arduino's 5V pin to the +5V screw terminal.

The ENx pin(s) (after removing any jumpers that may be on them) connect to any PWM capable pin (this is the speed control pin). IN1/IN2 or IN3/IN4 connect to any IO pin since these are just used to set the direction or control the braking modes. ENA controls the speed of motor 1, and IN1/IN2 control the direction of motor 1. ENB and IN3/IN4 are likewise for motor 2.

---
Tags: arduino-uno, motor, battery, raspberrypi, l298n
---


# Question
Title: I need help creating a code that moves a DC motor CW or CCW based off of 2 different buttons
I know I can make the motor move backwards and forwards with buttons but I don't want it to move at full speed. I want it to increment in very small amounts to where it can be adjusted very small amounts at a time. I should also be able to hold the button so it moves continuously. I also have a motor with an encoder on it. Maybe there is a way to use the numbers on the encoder to increment? so press the CW button and now the motor wants to move till the encoder reaches +10 from where it was at? I understand what I want to do, just need help getting there. Thanks

HERE IS THE CODE I FIGURED OUT THAT MAKES MY DC MOTOR INCREMENT CW AND CCW

```

#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

  //delay(100);

}

```

# Answer
> 1 votes
Here is the code i eventually figured out. It increments my DC Motor basically by activating it for a small amount of time in the direction of whichever button was pushed.

```
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

}

```

# Answer
> 0 votes
To formulate the comments into an answer:

In principle it is of course possible to put an encoder onto a DC motor shaft and then drive the motor, until you reach the desired position. But you won't get good precision or accuracy with this. You wrote

> till the encoder reaches +10 from where it was at

Since most encoders have more than 10 tics per full rotation (you didn't specifiy how much yours has), this can mean rotating only a fraction of a full rotation. Let's assume, that the encoder has 40 tics per full rotation. With 10 tics you have a quarter rotation. It seems you want precision in the range of about 1 tic.

DC motors are made for spinning relatively fast. They don't give you control over the position with steps. They mostly have very few coil/magnet combinations (for example just 2 coils, which are switched internally). Thus you have just an inert motor shaft, which is driven by the motor. It will need time to accelerate and to decelerate. With most motors, you may even get a half or full rotation, when you wanted only a quarter rotation (the 10 tics). Calculating the correct timings to get it any better will be not easy for relatively small reward. DC motors are not made for rotations below a small number of full rotations.

You could tackle that problem by using a geared DC motor. The shaft after the gears will run slower and thus have the explained problem not so badly. Then you have to live with the smaller speed.

**Or you could go a more proper way and just use a stepper motor**, which is made for small steps in the range of sub-full-rotation. It is a bit more difficult to drive (also depending on the driver circuit), but it gives you the position control, that you want. And to rotate continuously: A continuous rotation on a stepper motor is nothing else but step after step taken in fast succession (much like running is a fast succession of steps with your feet).

---

Note: The stepper motor does not have a feedback like an encoder on it. The motor driver will just drive the coils to step the motor. If the motor is stalled or if it is overloaded, you might loose some steps (meaning that the coils are driven for the steps, but the motor doesn't actually move). You could sense that with an additional encoder on the motor shaft. But in most cases that is not necessary. If you just make sure, that the motor is not overloaded at any time, you will be fine. Or you might not worry about some steps being lost sometimes, if the overall precision is good enough. That is your decision.

---
Tags: arduino-mega, motor, button
---


# Question
Title: Why impedance between I/O pin and ground drops when Arduino is not powered
I have a 4KHz 5V pulsed signal connected to Arduino UNO pin2 (ISR).

* When the board is powered, the pulse is attached to ISR rising edge, and is working as intended.
* I don't know the output impedance of the pulsed signal, but when the board is not powered, the pulse drops to 2V.
* The resistance between pin2 and ground is about 500K when not powered. The resistance is infinite when powered.
* The pulsed signal does NOT drop when connected to a 500K resistor.

**Question:**

* What is the cause of the signal drop?
* How to prevent it ? (It's not practical to disconnected the signal from Arduino, but I can make sure Arduino is always powered. How to deal with transient situations like reset ?)

Thanks in advance !

# Answer
The Atmega328p (which is used in the Un\[ (and actually all other AVR microcontrollers) has clamping diodes in the input hardware to protect it from overvoltage (above Vcc). When not powered, Vcc is at the same level as ground, so any positive voltage on an input pin is above Vcc. The protection diodes get conductive to protect the input hardware. Note, that the diodes can be fried easily, if a too high current flows through them. You should prevent that.

**How to prevent it?** By not doing it. You should never provide a voltage on an input of an unpowered chip (like any chip). If you really need to unpower the Arduino, you can prevent the voltage from reaching the input pin with a MOSFET.
> 3 votes

# Answer
I do that all the time but I also read the data sheet. There is a limit on the amount of current you can inject into a processor pin or in total, that is on the data sheet. Also be aware when you inject current you can cause VCC to go out of specification unless it has enough load to support it. Typically I limit my input current to less than 1mA with a resistor. This also protects me in case I get a negative excursion. For a 5V system that resistor is 5K or greater, with 10K being very common. The input resistance reading is only good to check if the pin is shorted. It is connected to an active junction of a FET and a few Diodes. The voltage and or polarity of your ohm meter will definitely affect the reading. The resistance that may be there is due to chip resistance, bonding wire resistance etc. all low in value.
> 0 votes

---
Tags: arduino-uno, interrupt, isr
---


# Question
Title: How do I add or subtract to a pre-determined value without having it default back to the original value?
Typical apologies in advance, it's been quite some time since I've tinkered with Arduinos. Using an Arduino Micro Clone (Pro Micro), TF02 LiDAR, and a Adafruit 1.2" 7-segment display, I've been working on a rangefinder that is able to be adjusted up/down by increments of 1. I've hit a wall though. I am unable to adjust the distance value without it returning to the original value. Say the distance is at 6'2". When I push the "up" button, the value is 6'3" but then returns to 6'2". Same applies for the "down" button. Also, when the distance is at, for example, 1'0", and I press the down button, instead of going to 0'11", it displays 0'99". I'm at a wall in terms of what I can do to resolve this. Any help is appreciated!

```
*
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
Adafruit_7segment matrix = Adafruit_7segment(); //d pin 2, c pin 3
#include <SoftwareSerial.h>// soft serial port
#include <Wire.h>

//button stuff
int Up_buttonState = 0;
int Dn_buttonState = 0;
int Up_lastButtonState = 0;
int Dn_lastButtonState = 0;
const int  UpPin = 7;
const int  DnPin = 8;

//LiDAR stuff
int dist;// LiDAR actually measured distance value
int strength;// LiDAR signal strength
int check;// check numerical value storage
int i;
int uart[9];// store data measured by LiDAR
const int HEADER=0x59;// data package frame header
long inches, INCH, feet, ftin;

SoftwareSerial mySerial(9,10); //rx tx,

void setup()
{
pinMode(UpPin, INPUT);
pinMode(DnPin, INPUT);
 Serial.begin(9600);

 mySerial.begin(115200);//set the Baud rate of LiDAR and Arduino serial port
  #ifndef __AVR_ATtiny85__

  #endif
  matrix.begin(0x70);
}
void loop()
{

 if (mySerial.available())//check whether the serial port has data input
 {
    if(mySerial.read()==HEADER)// determine data package frame header 0x59
    {

      uart[0]=HEADER;

      if(mySerial.read()==HEADER)//determine data package frame header 0x59
      {
       uart[1]=HEADER;

      for(i=2;i<9;i++)// store data to array
         {
          uart[i]=mySerial.read();
         }
           check=uart[0]+uart[1]+uart[2]+uart[3]+uart[4]+uart[5]+uart[6]+uart[7];
           if(uart[8]==(check&0xff))// check the received data as per protocols //if data received

             { //start equations
               dist=uart[2]+uart[3]*256;// calculate distance value

               //equations for converting mm to ft,in
               inches = (dist * .3937);
               INCH = inches% 12;
               feet = (dist / 2.54) / 12;
               ftin = feet*100 + INCH;

               Up_buttonState = digitalRead(UpPin); // add 1 to ftin
                if (Up_buttonState != Up_lastButtonState)
                {
                  if (Up_buttonState == HIGH)
                  {
                    ftin++;
                  }
                  delay(500);
                }
                Up_lastButtonState = Up_buttonState;

               Dn_buttonState = digitalRead(DnPin); // subtract 1 from ftin
                if (Dn_buttonState != Dn_lastButtonState)
                {
                  if (Dn_buttonState == HIGH)
                  {
                    ftin--;
                  }
                  delay(500);
                }
                Dn_lastButtonState = Dn_buttonState;

               Serial.print(ftin);
               matrix.print( ftin , DEC );
               matrix.writeDisplay();

             }
      }
    }
 }

}

```

# Answer
> 1 votes
You wrote:

> ```
> ftin = feet*100 + INCH;
>
> ```

What is this monster? I am not very familiar with imperial units (and I wonder why anyone would still want to use them), but I believe a foot is not 100 inches.

Oh, I see. The monster is a kludge to manage the display in feet & inches. But note that it is computed at every loop iteration as a function of the measured distance. I doesn't make sense to apply a correction to the monster as it is going to be recomputed on the next iteration. That's why the value “returns” to what it is supposed to be. As to why the down button changes “100” to “99”, I think it is quite obvious: 100 minus one is 99. It is not a good idea to do arithmetics with the monster.

If you want the correction to persist, you have to store it in a global variable (or `static` local), and add that variable to the measured distance at every loop iteration. For example:

```
// In global scope:
int correction = 0;

// In loop():
dist = ...;
inches = dist * 0.3937008 + correction;  // correction added here
ftin = (inches/12) * 100 + (inches%12);  // only used for display

if (Up_lastButtonState == LOW && Up_buttonState == HIGH) {
    correction++;
    delay(500);
}
if (Dn_lastButtonState == LOW && Dn_buttonState == HIGH) {
    correction--;
    delay(500);
}

```

Note that the monster is used for display **only**. No arithmetics are performed on it, as that would not make any sense.

---
Tags: arduino-pro-micro
---


title: ESP32 servo runs continuous

text:
# Question
Title: ESP32 servo runs continuous
I have ESP32 connected to TZT servo SG90. This is the code

```
#include <ESP32Servo.h>
#define TURN_TIME 175

Servo myservo;  // create servo object to control a servo
// 16 servo objects can be created on the ESP32

int pos = 0;    // variable to store the servo position
// Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33
#define servoPin  17
#define MOTOR_1_PIN 22

void setup() {
  pinMode(servoPin, OUTPUT);
  Serial.begin(9600);
    // Allow allocation of all timers
    ESP32PWM::allocateTimer(0);
    ESP32PWM::allocateTimer(1);
    ESP32PWM::allocateTimer(2);
    ESP32PWM::allocateTimer(3);
    myservo.setPeriodHertz(50);    // standard 50 hz servo
    // using default min/max of 1000us and 2000us
    // different servos may require different min/max settings
    // for an accurate 0 to 180 sweep
}

void loop() {

  myservo.attach(servoPin, 700, 2500); // attaches the servo on pin 18 to the servo object
  myservo.write(0);
  delay(TURN_TIME);
  for(int i =0; i<180; i++)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  delay(3000);
  for(int i =180; i>0; i--)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  myservo.detach();
  delay(3000);

}

```

My servo starts rotating one way and reverse for few degrees, then after 5 seconds the servo starts rotating at one way forever..

I had no problems with arduino and nodemcu board. What should I change in the code?

EDIT: I have connected the servo with battery, they have common ground. The pin on esp32 that I am using is G17. "#define servoPin 17" in the code

# Answer
I used other servo library and it worked.. Then i changed the pulse width with this line of code. The default is 1000-2000. But it rotates only 95 degrees. When it's pushed to around ~2850us the servo rotates up to 181-185 degrees. `servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);`

```
#include <Servo_ESP32.h>

static const int servoPin = 16; //printed G14 on the board
int delayTime = 20;
Servo_ESP32 servo1;

int angle =0;
int angleStep = 5;

int angleMin =0;
int angleMax = 180;
#define CHANNEL_NOT_ATTACHED -1
void setup() {
    Serial.begin(115200);
    servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);

}

void loop() {
    for(int angle = 0; angle <= angleMax; angle +=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }

    for(int angle = 180; angle >= angleMin; angle -=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }
}

```
> 0 votes

---
Tags: servo
---


title: Cutting neopixel routine code short

text:
# Question
Title: Cutting neopixel routine code short
I've been working on a level meter with a neopixel strip (WS2812).

The code is very simple: reading a potentiometer, mapping the input and showing the output in the led strip.

So far, so good. The code I include below is working fine but, obviously, ugly and repetitive. Since my knowledge of programming is very weak, I wonder if there is any loop way to cut the code short. Please note that the seven led have different colours. Actually this is the confusing point for me to build a loop. Any idea, folks?

Yes, I also know that using so many delays isn't the mos elegant solution, but it does not compromise the device performance and the bar led appearing is quite nice.

```
void leveller () {
     int millivolts;
     int level;

     millivolts = analogRead(A3);

     level = map(millivolts, 0, 1024, 0, 7);
     if (level <=0){
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          strip.show ();
      }
      else if ((level > 0)&&(level<1)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
      }
      else if ((level>= 1)&&(level<2)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
      strip.show ();
      }
      else if ((level>= 2)&&(level<3)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
             delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
      strip.show ();
      }
      else if ((level>= 3)&&(level<4)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          }
      else if ((level>= 4)&&(level<5)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(5, 0, 128, 0);
          delay(30);
          strip.show ();
      }
      else if ((level>= 5)&&(level<6)) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(5, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(6, 0, 128, 32);
          delay(30);
          strip.show ();
      }
      else if (level>= 6) {
          strip.clear();
          strip.setPixelColor(0, 128, 0, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(1, 128, 32, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(2, 128, 64, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(3, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(4, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(5, 0, 128, 0);
          delay(30);
          strip.show ();
          strip.setPixelColor(6, 0, 128, 32);
          delay(30);
          strip.show ();
          strip.setPixelColor(7, 0, 128, 64);
          delay(30);
          strip.show ();
    }
}

```

# Answer
First, a small remark:

> ```
> if ((level > 0)&&(level<1))
>
> ```

`level` is an integer, and there is no integer that is both strictly larger than zero and smaller than one.

> ```
> if ((level>= 1)&&(level<2))
>
> ```

There is only one integer that verifies this condition. It would be clearer then to just write

```
if (level == 1)

```

Now, for your actual question: one trick that often works to shorten repetitive code is to turn code into data, store the data in arrays and run through them with loops. Here the sequence of colors can be stored in an array:

```
const uint8_t colors[8][3] = {
    {128,   0,   0},
    {128,  32,   0},
    {128,  64,   0},
    {  0, 128,   0},
    {  0, 128,   0},
    {  0, 128,   0},
    {  0, 128,  32},
    {  0, 128,  64},
};

```

You can then call `setPixelColor()` within an loop that runs through the array. As the end point of the loop depends on the measured level, it could be written like this:

```
void leveller() {
    int level = map(analogRead(A3), 0, 1024, 1, 9);
    strip.clear();
    for (int i = 0; i < level; i++) {
        const uint8_t *color = colors[i];
        strip.setPixelColor(i, color[0], color[1], color[2]);
        strip.show();
        delay(30);
    }
}

```

Note that, since the output of `analogRead()` is always smaller than 1024, the variable `level` will always be smaller than 9, i.e. it will take values between 1 and 8 inclusive. And that is the number of colors that will be shown.
> 1 votes

---
Tags: loop, neopixel
---


# Question
Title: I want to create 10 levels with one button but this code shows only level 1?
```
#include <Adafruit_NeoPixel.h>
const int PIN = 4;
const int NUMPIXELS = 10;
const int BUTTONPIN = 6;
int buttonState = 0;
int PINState = 0;
int level = 1;
int dt = 100;
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.begin();
  pinMode(BUTTONPIN, INPUT);
  Serial.begin(9600);
}

void loop(void) {
Serial.println(buttonState);
  buttonState = digitalRead(BUTTONPIN);
  if (digitalRead(BUTTONPIN) == HIGH) {
    if (buttonState == 0) {
      buttonState = 1;
    } else {
      buttonState = 0;
    }
  }

  if (buttonState == 1) {
    opdracht(level);
  }
  else {
    if (level >= 10) {
      level++;
    } else {
      level = 1;
    }
    pixels.clear();
  }
}

//level 1
//void opdracht1() {
//  pixels.setPixelColor(0, pixels.Color(150, 0, 0));
//  pixels.setPixelColor(5, pixels.Color(0, 0, 150));
//  pixels.show();
//}

void opdracht(int x) {
  if (x == 1) { //level 1
    pixels.setPixelColor(0, pixels.Color(150, 0, 0));
    pixels.setPixelColor(5, pixels.Color(0, 0, 150));
    pixels.show();
  }

  if (x == 2) { //level 2
pixels.setPixelColor(8, pixels.Color(150, 0, 0));
pixels.setPixelColor(6, pixels.Color(150, 0, 0));
pixels.setPixelColor(1, pixels.Color(0, 0, 150));
pixels.show();
  }

```

# Answer
You forgot to ask a question. So I will assume the intended question is “Why does this code always show level 1?” and I will try to answer that.

The variable `level` is defined here:

```
int level = 1;

```

Its initial value is 1. Then it is updated here:

```
if (level >= 10) {
  level++;
} else {
  level = 1;
}

```

The first time this section of code runs, `level` has its initial value, namely 1. The condition in the `if` evaluates to false, then the statement

```
level = 1;

```

is executed, which assigns the value 1 to `level` (which has no effect, as that was already its value anyway).

The next time that section of code runs, `level` has still the vale 1, and the effect is the same as the previous time.
> 1 votes

---
Tags: adafruit, sketch, hardware, variables, led-strip
---


# Question
Title: Can't turn off fan using PWM and analogWrite(x, 0)
I'm trying to make PWM Signal Generator with Arduino Uno. I'm trying to control 230V 50hz "NRG118" combi boiler fan. The fan powered by AC and have 3pins for PWM control. "vcc,gnd,pwm" Wired them to arduino "5v, GND, 11" pins.

I can control the card on the arduino "0to100% with a simple code below but I can't turn it off. I tried digitalWrite nothing changed. Tried different pins 5-6-9-11 nothing changed. Tried to wire gnd+vcc to outsource powersuply nothing changed.

Also I have a simple PWM generator "HW-723 XY-LPWM PWM Signal Generator Module". The "HW-753" can control the fan without any other component but it may have builtin special component like a NPN but im not sure about it.

In description I found this and maybe its a requirement but I have no idea about electronic components: "The PWM output pin on the microcontroller drives an NPN MMBT3904 type transistor which in turn drives the PWM output pin of the module. The transistor has a series 1K resistor tied to VIN+, so the PWM signal will swing between ground and the module supply voltage on the VIN+ pin."

With the HW-753; at startup the fan is not running but when I wire to my arduino it starts with 100% power and when i set "analogWrite(x, 0)" dutycycle reducing but fan still running at %1 speed and I read 0.07volt with multimeter on "PWM+GND" pins.

Most people can not run, I cant stop.... It's killing me people...
What am I doing wrong?

```
void setup() {
  pinMode(6, OUTPUT);
}
void loop() { //the code only for test. Using loop is dumb.
  //digitalWrite(6, LOW);
   analogWrite(6, 0);
   delay(5000);
}

```

# Answer
If you are working with the AC motor, then it is probably works even PWM cable is not attached. In this case there is no reason to use "analogWrite(PIN, 0)". It will not work.

"An external resistor divider connected to the VMIN input sets the minimum fan speed by fixing the minimum PWM duty cycle (1.25V to 2.65V = 0% to 100%, typical). It depends on controler card manufacturer. check datasheet"

If you cant find datasheet like me then check how others do. There is diagram of "HW-753 Signal Generator Module" below. As you can see between VIN+ and PWM there is 1k Resistor and both wired to an NPN, also the mid leg of NPN passing 1k resistor while going to pwm to protect the card. Also 3rd leg is wired to gnd. So it is not the same thing I was doing before. If you work with AC then you must always consider that and just forget what people say. Do not drown like me. I hope it will helps someone.
> 0 votes

---
Tags: pwm
---


# Question
Title: Programming an arduino using only switches to give 0 or 1
I am not too experienced about the working of arduino but I know that it involves data in computer language ( 0 and 1)

I have an array of 8 switches plus a few extra. As I am unable to (due to some reasons) program it through my pc, I wanted to know if it is possible to manually use switches to send data and program it? (complexity doesn't matter).

If yes, then could you tell me how I could do it (taking into consideration my limited knowledge).

If no then why?

# Answer
> 3 votes
Short answer: If you are unable to program your Arduino using a computer, you are unable to program your Arduino at all.

The Arudino is built to be programmed using a serial interface (usually USB) that interacts with the bootloader, plus an IDE on the other end of the cable. It is not set up to be programmed with switches.

You could conceivably build an Arduino programmer that would let you enter a program using 8 switches plus an enter button. Such a programmer would collect the program into a memory buffer, and then load it into the Arduino using the USB interface but it would take WEEKS of working constantly to enter the simplest of programs, and the odds that you could do it without multiple errors is pretty much zero. Plus, it would probably cost several hundred dollars to build such a programmer. It would be a pointless exercise in masochism.

(Not to mention the fact that you would have to somehow compile your Arduino program into machine code, and convert that into binary in order to enter it.)

Some of the earliest computers required that the operator enter the first few instructions via switches as you describe, and then the computer would read and begin executing the rest of its program from a tape drive. Those computers only had a few thousand bytes of memory, and even then, the instructions the operator had to enter were just enough to start the machine booting from tape.

# Answer
> 2 votes
While not *physically* impossible it would be a really silly thing to attempt.

However, if *I* were to attempt it I'd probably use just 3 switches (or rather 2 switches and one button though you could use a switch instead of the button).

I'd wire it up so that the RESET, MISO and SCK pins were all connected to the switches in such a way that I could hold the whole board in RESET for extended periods (i.e., switch between RESET and GND), set a HIGH or a LOW as needed on the MISO pin, and toggle the SCK pin HIGH and LOW (I'm not sure off hand if you need to idle LOW or HIGH with the clock - the datasheet will tell you).

Then I'd become extremely intimate with the ICSP protocol of the ATMega328P.

That would then allow me, extremely slowly, to act like a hardware programmer and instruct the ATMega328P to program itself with data I sent.

You might also like to attach a shift register to the MOSI and SCK pins with 8 LEDs on it so you can monitor the responses from the Arduino while programming.

It would take forever to upload even the simplest of programs, and the error rate would be far to high, but it *could* be done if you were *really* desperate and had nothing else to do (including eat or sleep) for a number of days.

---
Tags: arduino-uno
---


# Question
Title: Leading Zeroes on Arduino Ethernet MAC Address
How can I pass the MAC address to Ethernet shield with leading zeroes?

I change the default MAC address from `DEADBEEFFEED` to something like `DEADBEEFFE01`. So I only change the last number from `0xED` to `0x01`. My board is communicating to a separate server and when I look at the MAC in that server, my board is listed as `DEADBEEFFE1`.

It's not as simple as printing the MAC address with padded zeroes as the board is actually removing it.

I've looked at the Ethernet library and I saw that the mac is passed as an array of `uint8_t`. I think that's why, the last number is read as 1 (which is correct) but passed as just that.

Is there a way for the MAC to pass leading zeroes?

# Answer
> 3 votes
Writing this in case someone in the future might be interested.

The values passed in the Ethernet library is correct. The last value, 0x01 must be 1 and is written correctly, `0x01` in the registers of the W5500 inside the Ethernet shield.

Where I've got it wrong is how I pass the MAC address to the server. I'm basically creating a string for a json message. In there, I've put `%02x` to make sure that zeroes are padded.

---
Tags: ethernet
---


# Question
Title: I want to make mesh network with nodemcu (esp8266)
in this all the nodemcu are in both mode receiving and transmitting, if i made 6 nodemcu connected with each other as mesh network to control home appliances, using mac address. suggest how i will start to reach the destination.

# Answer
> 1 votes
there are libraries for this already, i have used this one, but i have not tested the mesh function yet

---
Tags: esp8266
---


# Question
Title: 9 volt battery not being able to power motor driver
Currently I am using a 9 Volt Duracell A one like this:

I am using it to power a motor driver which contains 2 motors within. I can see where the main problem is coming and that is to do with that the voltage is not big enough. But I don't understand why this is. I see in the manual for the robot that I am building it is using a smaller voltage battery than what I am using. I tried using another set of batteries but the motors did not move at all then. The 9V Duracell battery that I am currently using has only been used for about a week (so it probably hasn't ran out), its practically brand new.

# Answer
It is likely not a question of the voltage being "big enough". You do need to feed the correct voltage to your robot, but max current and capacity are also very important.

Those "9V transistor batteries" have very low peak current and very low total power capacity (measured in milliamp-hours, or mAh.) They are not up to the job of powering motors. You could easily drain a 9V battery like that in 15 minutes, much less a week.

You should connect 6 D cells in series, and use that instead. That would give you enough peak current and total capacity for your robot.
> 0 votes

---
Tags: motor, battery, voltage
---


title: Help needed!!! I have an upcoming exam

text:
# Question
Title: Help needed!!! I have an upcoming exam
I have an upcoming exam about the codes and stuff. Its about the basics like "blink with delay" and the "millis function". I need to get these things learned but i have no idea how?! Does anybody know a good site or how i can learn this?

# Answer
> 3 votes
Learning to write code really takes practice - you learn far more by doing it than by reading about it. Start with the basic Blink example - search for a tutorial online if you want one, there are many - and get that running. Then play with it. Change the blink interval. Try adding a second LED, perhaps it turns off when the other turns on, for instance.

Every time you touch the code you'll have an "opportunity" to make a mistake or a typo. Fixing those will give you some insights you'll never get from reading about coding.

Once you've "squeezed all the juice" out of Blink, move on to Blink Without Delay. Run it, just as it is, at first. Than start tweaking it. Change one or both of the blinking periods. Again, try adding another LED with yet another blink rate.

These hands-on games are the best way to learn this stuff. Having someone (or Arduino Stack Exchange) who can help you when you're stuck is a great resource but the things you discover and the skills you acquire on your own when you fix your own mistakes are the ones that will stick with you (even 50 years later! ;-)

---
Tags: arduino-uno
---


# Question
Title: Whatever components we connect to the Arduino, their grounds and 5v pin connection must be the same?
I am trying to connect different types of sensors & motors to the Arduino should I make their grounds and 5v pins on the same connection.

# Answer
> 1 votes
All the grounds must be connected. They don't have to be the same physical pin - the Arduino has multiple GND pins, but they are all connected internally.

The 5V doesn't matter where you get that from, as long as it's regulated and the associated ground is connected to all the others.

---
Tags: arduino-uno, sensors, arduino-motor-shield, raspberrypi, ultrasonics
---


title: ESP8266 RF Calibration

text:
# Question
Title: ESP8266 RF Calibration
As an off-Topic to my main question, regarding Robodyn's Uno+Wifi - it seems that Wifi does not work ( fail to connect and fail find any network ).

Juraj advised to use External Antenna ( did not work ) and try to make an RF calibration as shown on espressif's site. Which I fail to understand how it is done.

a) Can anyone help with RF Calibration ?

b) Might it be another reason for that ?

Guy

**EDIT\_1** Just to be clear, a sלetch was uploaded and executed successfully to the ESP8266 module (Basic WiFi connect and network scan ).

**Edit\_2**

# Answer
> 1 votes
You can't do anything else with the RF calibration then to clean the flash area where it is stored. There are two reason for doing it:

First is reason to delete the RF calibration area is, if it was written by different version of Espressif SDK, including changing between AT firmware and Arduino. Then it is almost always wrong. I think they changed the data structure so some values are swapped.

Second reason is if the SDK did the calibration in wrong conditions like without antenna.

There is not much information about RF calibration. The FAQ has "Please erase the RF parameters to trigger overall calibration."

The AT firmware reference has (addresses for 4MB-C1):

* blank.bin 0x3FB000 Initializes RF\_CAL parameter area.
* esp\_init\_data\_default.bin 0x3FC000 Stores default RF parameter values, has to be downloaded into flash at least once. If the RF\_CAL parameter area is initialized, this bin has to be downloaded too

The esp8266 Arduino core writes the data of esp\_init\_data\_default.bin as part of the sketch's binary.

EDIT: the SDK does the 'digital calibration' at boot. it takes some microseconds. it is not done at every boot, but after some count of resets. this can be configured in the init section

---
Tags: esp8266, arduino-uno-wifi
---


# Question
Title: Can I use and external power supply and USB at the same time on my Arduino?
Can I use the Arduino with an External wall-wart and the USB at the same time? I need to power more LEDs, and the USB on my computer can only supply so much. But, I didn't want to destroy my computer because I had the USB and the external plugged in.

I saw this,

External power supply?

But I am still unsure. The reason I want to at all is because when I connected this circuit, the Arduino would cease to be recognized on the USB. I don't know if it is because there wasn't enough power to the LED, if I short-circuited something, or something else. I do not wish to break my laptop though.

What happens if I power the Arduino with both the USB and external power voltage simultaneously?

These all seem to indicate you don't just "plug in" with both, and you need some other kind of regulator or something. But in that same answer, one person says,

https://arduino.stackexchange.com/a/896/69706

And that indicates when the power is plugged in the USB is cut off. Again, my fear is breaking my laptop, and that is the main question. Especially in light of this,

Is supplying 5V from both external 5V and USB harmful?

The external power is this,

9 VDC 1000mA regulated switching power adapter

# Answer
> 2 votes
Yes, you can simultaneously connect external power supply and USB. As explained in one of the answers, that you linked, the Arduino chooses it's power input through the supplied voltage on Vin/barrel jack. Vin has no direct connection to the VUSB, so the USB port will not get any voltage from the external supply, thus it does not get damaged.

**BUT:** Your thinking is wrong. Clearly your LEDs need more than 500mA. This current should never flow through the Arduino. You can easily fry the protection diode or the voltage regulator (which is an inefficient linear regulator), if you connect all the LEDs to the 5V pin. One GPIO pin can only provide about 20mA (40mA at absolute max, you should stay below 20mA) and only 100mA through all GPIOs together. They are not made to provide power, but for switching.

Instead you should connect the LEDs outside of the Arduino to the power supply. If you want to use the specified 9V power supply, you need to buy a buck switching voltage regulator, which gets the voltage down to 5V for you. Make sure, that this regulator is rated for a current significantly higher, than what you need.

**How to control the LED then?** That depends on your LEDs. If you just have some bare LEDs, you could use a transistor to switch the higher voltage from the Arduino. If you have a plain LED strip you can also use a transistor. Best use a MOSFET for this. If you have an addressable LED strip, just connect the power lines to the 5V output of your new switching regulator and the data line to the Arduino.

---
Tags: power, usb
---


# Question
Title: Using Arduino to create a countdown that unlock a box
Am new to Arduino. So permit me if I sound so novice.

I want to create a countdown device (a clock that will countdown or something) that will unlock a box when the time is up.

As an example, let say, I set the clock to start counting down from 2hours, but when it remains 5mins for the countdown to elapse, the box will unlock

What are the things needed for it to work as all examples I see are mostly for opening the door or box when the temperature changes.

# Answer
> 1 votes
This sounds as an escape room puzzle. From an electronic point of view you need something to lock/unlock the box like a servo motor, a stepper motor or (best option) a normally closed solenoid. You might need some components to drive such locking mechanism, like a mosfet or transistor (possibly a darlington), depending on which device you choose and what voltage it requires to operate. Simplest solution is a servo motor which doesn’t require anything, but has a low torque, meaning the box can easily be forced. Most robust and reliable solution is a NC solenoid, common ones are 12V so you’ll need a p-channel enhance mosfet and a couple of resistors to drive it from an Arduino.

To display the time you’ll probably want to go for an LCD, common ones are 16 col x 2 rows, most have an integrated chip to drive them using only a few wires.

Apart from that, you need a battery pack (voltage and power depending on your locking circuit choice) and may be a push button (for safety unlock).

From a software perspective you want to create a loop which starts by locking the box and then counts down the time: when the time left is less than 5 mins it activates the unlocking mechanism circuit.

```
int current = 0;
const int max = 2 * 60 * 60; // 2hrs in sec
const int grant = 5 * 60; // 5mins in sec
bool unlocked = false;

void setup() {
    lock();
}

// executed once every second
void loop() {
    // any safety open check should be performed here...
    // if still locked and less than 5 mins to end
    if (!unlocked && current > max - grant) {
        unlock();
    }

    display(current++);
    wait(1000);
}

// does what it is needed to unlock and sets the unlocked variable to true
void unlock() { ... }

// does what it is needed to lock and sets the unlocked variable to false
void lock() { ... }

void display(int secs) {
    int h = secs / (60 * 60);
    int m = (secs / 60) % 60;
    int s = secs % 60;
    // display on LCD the values above with the proper formatting
}

```

A couple of notes:

* if you go for a normally closed solenoid be sure to have a way to get inside the box if something goes wrong with your circuit or if the batteries get drained
* you might want to have a hidden button or other way to force the unlock, especially for debugging and testing

---
Tags: arduino-uno
---


# Question
Title: Run HEX program from SD with another program
I want to write a program in which I can select a HEX file recorded on a SD card (via a LED screen, etc.) and run it, i.e. transfer control to it, like launching programs on a PC. Is this possible and if so, how? I only found ways to directly run a sketch from an SD card without that "program"

# Answer
The HEX files on SD card would have to be linked for a specific address in flash. Normal program is linked for address zero on ATmega, but the bootloaders are an example on how to link for specific address in flash.

Then you could use the do\_sdm() function provided by Optiboot 8 (see the example) to write the bytes from the HEX file to the right location in flash memory. Next step would be to call the start address as function same way as do\_spm() is made accessible with optiboot.h in the example.

```
typedef void (*loaded_function_t)();

const loaded_function_t loaded_function = (loaded_function_t)(ADDRESS_OF_LOADED_FUNCTION);

```

then you can use

```
  Serial.prinln("Execute the loaded code...);
  loaded_function();
  Serial.prinln("Loaded code finished.");

```
> 0 votes

# Answer
Not with an Uno, no, it's not possible. Or it's very very hard and the results would be less than desirable. You need a proper MCU with lots of RAM and the ability to run code from it, which you can't with an Uno.

It would be less work to write your own scripting language to control things from a text file.
> 0 votes

---
Tags: arduino-uno, bootloader
---


# Question
Title: Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4
Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4.

Problem: Only want a single segment/fx\_mode to run at any one time.

---

```
#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {

ws2812fx.init();

ws2812fx.setBrightness(85);

// divide the strip of 60 LEDs in to 4 segments

ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);

ws2812fx.setSegment(1, 15, 29, FX_MODE_SCAN, RED, 3000, true);

ws2812fx.setSegment(2, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);

ws2812fx.setSegment(3, 45, 60, FX_MODE_SCAN, RED, 3000, true);

ws2812fx.start();
}

void loop() {

ws2812fx.service();
}

```

# Answer
> 1 votes
The used library doesn't give you the direct possibility to automate the segment changes. So you need to write that code yourself.

Currently you are setting up all segment in `setup()` and starting them together via `start()`. Instead you should add the corresponding segment only, when it should be on, and removing all segments, that should not run. In the following I don't remove and add a segment, but I'm replacing the previous segment (described below)

I propose a code like the following, to light up each element after the other for a specific time each (**not tested**):

```
#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

#define SEGMENT_INTERVAL    3000
unsigned long segment_timestamp;
uint8_t current_segment = 0;
#define SEGMENT_N   4

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
    ws2812fx.init();
    ws2812fx.setBrightness(85);
    ws2812fx.start();
}

void loop() {
    if(millis()-segment_timestamp > SEGMENT_INTERVAL){
        segment_timestamp += SEGMENT_INTERVAL;
        switch(current_segment){
            case 0:
                ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);
                break;
            case 1:
                ws2812fx.setSegment(0, 15, 29, FX_MODE_SCAN, RED, 3000, true);
                break;
            case 2:
                ws2812fx.setSegment(0, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);
                break;
            case 3:
                ws2812fx.setSegment(0, 45, 60, FX_MODE_SCAN, RED, 3000, true);
                break;
        }
        current_segment = (current_segment + 1) % SEGMENT_N;
    }
    ws2812fx.service();
}

```

**What happens here?** First we use the `millis()` function in the pattern of the `BlinkWithoutDelay` example to time the change of segments to every 3s (3000ms) without blocking the execution of the other code (here the service routine of the LED animation). I will not go into detail here, since this principle is described at numerous places through the web and this site. Just search for something like "Arduino millis" or "Arduino Blink without delay". Now is only important, that the code inside the if statement will be executed every 3s (can be changed with `SEGMENT_INTERVAL`).

In the if statement we use a switch statement to set the corresponding segment, that should be activated at that time. Here we always set the segment 0, since only one segment is active at any time. Instead of removing the previous segment and adding the new one, we just change the previous segment to the data of the new segment.

With the line

```
current_segment = (current_segment + 1) % SEGMENT_N;

```

we increment to the next segment, while wrapping around from segment 3 to segment 1 via the modulo operator `%`. This is needed to loop through the segments.

The call to `ws2812fx.service()` is still needed, since it handles the actual animation of the current segment.

---

Note, that the above code can still be improved. You could save all the segment data in an array of structs and replace the switch statement with one line, using the `current_segment`'th element of the array. I will leave that improvement to you.

---
Tags: arduino-uno, ws2812
---


title: Code for Degrees not

text:
# Question
Title: Code for Degrees not
Using Audrino Nano and MKS SERVO42 42 Stepper Motor With Driver Board Closed Loop with the LCD. I have got the motor going by using the menu on board. Now able to run Code1 https://github.com/makertut/Arduino-Closed-loop.git out of GitHub and it runs as it is designed. Line 5 int numstep = 1030; cc runs the number of steps indicated and changing this number will determine the movement. I can do the math to calculate the degrees for number of step for a particular stepper. I would like to use degrees instead of steps for my program. Does anybody know how to code this? Thanks Greg

# Answer
This is basic algebra 1.

Say `steps / degree = 5`

So write that as 2 fractions:

```
steps   5
----- = -
degree  1

```

Then take the reciprocal of both sides:

```
degrees   1
------- = -
step      5

```
> 1 votes

---
Tags: arduino-nano, stepper
---


# Question
Title: Seems like I cant control 4 stepper motor at once
Im trying to control 4 stepper motors with the AccelStepper library.

Something like this:

```
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
//AccelStepper BR(1,stepPin4,dirPin4);

```

The problem is, It works just fine if I declare 3 instance of the AccelStepper, but once I uncomment the 4th one there's an error.

```
Error message: Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ESP32 Dev Module, Disabled, Default, 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"

In file included from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/xtruntime.h:30:0,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portmacro.h:80,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/portable.h:94,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/freertos/freertos/FreeRTOS.h:105,

                 from C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/Arduino.h:32,

                 from sketch\Test_file.ino.cpp:1:

C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/include/esp32/xtensa/config/specreg.h:40:13: error: expected unqualified-id before numeric constant

 #define BR  4

             ^

C:\Users\Parit\Desktop\Test_file\Test_file.ino:31:14: note: in expansion of macro 'BR'

 AccelStepper BR(1,stepPin4,dirPin4);

              ^

Multiple libraries were found for "WiFi.h"

 Used: C:\Users\Parit\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\WiFi

exit status 1

Error compiling for board ESP32 Dev Module.

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

```

Im not sure if the problem is the ESP 32 or the code. I use the A4988 driver to connect with all 4 stepper motors.

# Answer
> 1 votes
The variable name `BR` is already used somewhere else.

Use a different variable name

```
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
AccelStepper BackRight(1,stepPin4,dirPin4);

```

---
Tags: esp32, stepper-motor
---


# Question
Title: need to make my partners pill box turnover sensitive
ive done some arduino stuff back in uni like 7 years ago; and reserached premade items-ive looked online at many pill organisers and the best and cheapest one is $149 and isn't shipping to the UK rite now. but basically my partner needs to take 1 pill a day without fail. second set of pills is less urgent and not an issue if he misses, but basically is there like a thing I could whip together to sense when he has turned the pill case over that day or not? maybe sync to phone(would be super useful) so he knows when he has actually taken it.

# Answer
I wouldn't go with a "turn-over" sensor, but would just use a (big) button. I'd go with something like an ESP8266/ESP32. Those can connect to WiFi. Then have it send a push notification when being pressed (that is; the pill has been taken). Maybe light up an LED to also indicate the pill has been taken. Turn off the led at midnight. Also send a different notification when the button hasn't been pressed before, say noon.

For push notifications, you can use PushSafer, PushBullet, or Prowl (which I had most success with).

Have a look at Kevin Darrah article, and youtube channel. He uses it's own boards, but most of the code will work on any ESP board.

But try to imaging how the system would work, in your head first. Just throwing technology at a problem isn't always the best solution. My grandma has 7 pill boxes, one for each week. Which helped to keep track of whether a pill was taken that day.

Best of luck.
> 1 votes

---
Tags: gyroscope
---


# Question
Title: ST7789 TFT display only shows a correct image while Arduino reset button is held down - Why?
I am trying to get the ST7789 TFT display to work with Arduino. I followed online guides for connections and am using the fast library fron github and included workbench ino (https://github.com/cbm80amiga/Arduino\_ST7789\_Fast). Problem: The program runs and drives the display but the image is corrupt and only partial. I discovered that if I quickly and firmly press the reset button - and keep it pressed down - the image at the moment of reset press suddenly becomes full and good (albeit static because reset is pressed). Ofcourse as soon as I release the reset button the program restarts with the same corrupt image (the pictures below illustrate the issue).

I could not find a description of this particular problem by online searching. Here is what I tried to fix it (all to no avail):

* I confirmed all pins are correct as defined in the ino script.
* I ensure only the 3.3v power line is used. I have never connected the Vcc to 5 v
* I tried with a genuine Arduino UNO as well as a clone - both show the same behaviour.
* I used 1k:2k resistor voltage dividers for the data lines, res and DC - these did not help. In fact the display did not work at all with the voltage dividers, only the backlight came on and the screen flickered slightly. I checked that I was getting ~3v in the middle of each divider.
* I used two separate ST7789 display boards, bought from two separate sellers on different occasions - both show the same behaviour.

\[Edits in response to comments below\]

* The same behviour occurs when using a sketch that uses the standard Adafruit libraries (as opposed to the fast library linked above).
* The same corruption is seen when run on an arduino nano clone. However, with the nano, pressing the reset button shows only a fleeting glimpse of the full image prior to resetting (i.e. holding down the reset button does not preserve a static image on the screen).

Any ideas about what is going on and how to fix it? Thanks.

# Answer
> 3 votes
I found the answer to this problem. After reading multiple web pages / YouTube videos from multiple authors on this device and ~all of them warning you must never connect the Vcc to 5v or it will destroy the display, I found one or two that suggested you *could* use 5v because in this particular module there is a built-in regulator. So, faced with the thing being useless anyway, I decided to take the plunge and connect the Vcc of the TFT to the 5v pin of the Arduino and - hey presto - it works perfectly (see picture below: note the clear full image without the reset button being held down and also notice the voltage pin of the TFT is now connected to Arduino 5v compared to the pictures in my question).

The picture below shows the back of my TFT display module and, from what I have read, it is the J3Y transistor that is key to the voltage regulation in this module.

I hypothesise that pressing the reset button must have allowed equalisation of the voltages somehow but it is beyond my knowledge to explain it. I tried measuring the 3.3v pin on the Arduino with a voltmeter while holding down the reset button but I could see no change (the TFT module was not in situ for this test so maybe there is some interaction between Arduino and the TFT circuitry during reset).

Please note: I suspect this is a peculiarity of the particular TFT display module I have. Please DON'T run your 3.3v devices at 5v unless you have good reason to believe that they can take it. I only tried this after reading a couple of pages (including the detailed specs on the TFT module seller's listing) that suggested it would be OK with my particular TFT module - your's may be different. But if you have the same problem you see in my question then maybe that is something to consider. Thanks to those who have responded.

---
Tags: arduino-uno, display, tft
---


# Question
Title: Sensor that detects when metal sieve is clogged with debris
I'm a newbie here and would really appreciate all kinds of suggestions and answers from the experts here.

I am trying to make a small grey water recycling system project, and for the my primary filtration process tank, I will be using a combination of Metal Sieve and Cloth filter medium. The problem is, I will be making the system alert the user when filters are in need of changing and maintenance.

I made a quick sketch of my idea on paint, and as you can see, I am planning to make my grey water collection tank to look that way.

I am thinking of using pressure sensor to sense the change of weight in the sieve and cloth part of the tank for a minimum amount of time so that the system will not confuse water flow weight vs. the weight of the debris on the metal sieve, but I'm thinking that the pressure sensor is not waterproof.

I'm also thinking of like the laser module, and when the light breaks at certain level, meaning there is too much debris that has to be removed. I also googled load cells or weight sensors, but I'm really sorry I'm new to this, I don't know what is the best sensor to use for my problem.

I'm thinking of a float switch a few inches on top of my metal sieve and cloth and when it does not go on a OFF state for a certain amount if time, then the sieve is clogged, but my tank could overflow..

I need something that, when the sieve is clogged, the tank will no longer accept grey water input to avoid overflow. It has to be submersible in water too :'(

Is there a type of sensor that is most suitable for my problem?

Thank you so much everyone. Have a nice day.

# Answer
> 3 votes
I would tackle this not from the point of view of the filter, but from the point of view of the water itself.

The water will be impeded by the filter. As the filter gradually clogs that impediment will increase. The net result will be a slower flow of water through your filter.

There's a number of things you could do to detect that:

1. Measure the incoming water flow rate and the outgoing water flow rate and calculate the difference.

This would mean having all the water flowing through two flow meters which would complicate your design as the filter will no longer be able to deposit directly into the tank. But when the difference in flow between the in and out sensors gets above a certain point (to be determined by you) then you can safely say that the filter is blocked.

2. Measure the "backlog" of water. To do this the input portion of the filter will have to be sealed (or largely sealed). Again the filter will impede water flow, and the more it's clogged the more it impedes. Once the impediment becomes too high the water will start "backing up" up the input pipe as it can't get through the filter fast enough. At this time you can detect that rise in water level with a float switch.

You'd have a simpler design now, as the filter can deposit straight into the tank. Whether you want to detect the rise in water level in the incoming pipe itself or in the gap between the filter and where the pipe comes in depends largely on the size of your filter. With a large filter it may be better to have a smaller space at the top and measure in the pipe. That will "amplify" the level rise and make it easier to detect.

# Answer
> 3 votes
Have you considered a Differential Pressure Sensor, They can be gotten for a few dollars complete with the basic electronics and drift compensation on board. Try looking for: nxp pressure sensor for a start. These will interface to the Arduino A/D. I use an absolute one for barometric pressure and a differential to measure the air pressure my fish pond, this tells me if the air line is open or broken.

# Answer
> 2 votes
It seems to me what you want to detect is when the filter starts backing up and the flow of water out of the filter can't keep up with the in-flow. That will let you turn off the in-flow before the tank overflows.

So put a float switch or other level sensing switch on the space **above** the filter. Set it so it trips when the water standing on top of the filter gets close to the top of the tank. If the filter gets clogged and the water can't flow through fast enough, the water level on top of the filter will start to rise, and when it gets high enough, the level sensor will trip and your Arduino can shut off the flow of gray water into the filter tank.

---
Tags: sensors
---