title: Modbus IP with Simply Modbus TCP

text:
# Question
Title: Modbus IP with Simply Modbus TCP
```
include SPI.h
include Ethernet.h
include Modbus.h
include ModbusIP.h

//Modbus Registers Offsets (0-9999)
const int SENSOR_IREG = 100;
//Used Pins
const int sensorPin = A0;

//ModbusIP object
ModbusIP mb;

long ts;

// Set Port to 502
EthernetServer server = EthernetServer(502);

void setup() {
  //Assign the modbus device ID.
  regBank.setId(1);

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    byte ip[] = { 192, 168, 1, 177 };

    mb.config(mac, ip);

    // Add SENSOR_IREG register - Use addIreg() for analog Inputs
    mb.addIreg(SENSOR_IREG);

    ts = millis();

}

void loop() {

   //Call once inside loop() - all magic here
   mb.task();

   if (millis() > ts + 2000) {
       ts = millis();

       mb.Ireg(SENSOR_IREG, analogRead(sensorPin));
   }
}

```

I am trying to read data from the first analog pin through ModbusTCP using SimplyModbusTCP but I keep getting errors when I poll my Arduino. I am using an Arduino UNO with a Ethernet Shield W5100 and Modbus Library. I am request data from Ip address 192.168.1.177 Port:502 Slave:1 and Function Code:03. The error I get is "Error 66 occurred at TCP Read in SMT8.0.vi. LabVIEW: The network connection was closed by the peer."

# Answer
Looks like SimplyModbus was the problem, used Modbus poll and was able to read data.
> 0 votes

# Answer
You should not create the Ethernet server. The library creates the server and your server takes the port first.

Modbus function code to read Input registers is 04.
> 0 votes

---
Tags: ethernet, modbus
---


# Question
Title: State change detection with a colour sensor
I have added static variables to this code and instead of getting repeated notes whilst dwelling on green, I get a single note instead. This is what I wanted. However, my loop isn't allowing for a new note to be fired either when the sensor returns to a green colour. I'm afraid I'm not getting the hang of this!

```
  /*
  // TCS230 color recognition sensor
  // Sensor connection pins to Arduino are shown in comments

  Color Sensor      Arduino
  -----------      --------
  VCC               5V
  GND               GND
  s0                8
  s1                9
  s2                12
  s3                11
  OUT               10
  OE                GND
*/
#include <MIDI.h>

const int s0 = 8;
const int s1 = 9;
const int s2 = 12;
const int s3 = 11;
const int out = 10;

// LED pins connected to Arduino
int redLed = 5;
int greenLed = 6;
int blueLed = 7;
// Variables
int red = 0;
int green = 0;
int blue = 0;
int indeks = 0;
const int rgbr = 7;
const int rgbg = 6;
const int rgbb = 5;

MIDI_CREATE_DEFAULT_INSTANCE();

void setup()
{
  MIDI.begin();                      // Launch MIDI and listen to channel 4

  Serial.begin(9600);
  pinMode(s0, OUTPUT);
  pinMode(rgbr, OUTPUT);
  pinMode(rgbg, OUTPUT);
  pinMode(rgbb, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(out, INPUT);
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(blueLed, OUTPUT);
  digitalWrite(s0, HIGH);
  digitalWrite(s1, HIGH);
}

void loop()
{
  color();

  int tmpr = (((20 - red) - 10) * 30); //int tmpr=(((20-red)-10)*30);
  int tmpg = (((20 - green) - 10) * 30); //int tmpg=(((20-green)-10)*30);
  int tmpb = (((20 - blue) - 10) * 30); //  int tmpb=(((20-blue)-10)*30);

  if (tmpr < 0)
    tmpr = 0;

  if (tmpg < 0)
    tmpg = 0;

  if (tmpb < 0)
    tmpb = 0;

  if (tmpg > tmpb && tmpg > tmpr)
  { tmpb = 0;
    tmpr = 0;
  }
  analogWrite(rgbr, tmpr );
  analogWrite(rgbg, tmpg );
  analogWrite(rgbb, tmpb );

  static uint8_t noteOn;

  if (tmpg > 149 && tmpg < 151) {
    static uint8_t noteOn = 0;
    if (!noteOn) {
      noteOn = true;
      MIDI.sendNoteOn(79, 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);

    }
  }
  else {
    static uint8_t noteOn = 1;
    if (noteOn) {
      noteOn = false;
      MIDI.sendNoteOff(79, 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);

    }
  }
}

void color()
{
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  //count OUT, pRed, RED

  red = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);

  digitalWrite(s3, HIGH);
  //count OUT, pBLUE, BLUE
  blue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);
  digitalWrite(s2, HIGH);
  //count OUT, pGreen, GREEN
  green = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH);

}

```

# Answer
Because the MIDI library for Arduino does not keep track of which notes are on or off, you will have to do that yourself.

Add a `static` variable called `noteOn` that will hold a `0` or a `1`, keeping track of whether you have a note turned on or not.

Then, when your `loop()` determines that it should turn on a note, it first checks if a note is already on. If the note is not already on (`!noteOn`), then send note on command, and set `noteOn=true` (same as `noteOn=1`) so that next time around, you won't send the note on command again.

```
void loop()
{
  static uint8_t noteOn;

  [...]

  if (tmpg > 149 && tmpg < 151) {
    if (!noteOn) {
      noteOn = true;
      MIDI.sendNoteOn(79, 127, 1);    // Send a Note (pitch 79, velo 127 on channel 1)
      MIDI.sendControlChange(64, 127, 1);
    }
  } else {
    if (noteOn) {
      noteOn = false;
      MIDI.sendNoteOff(79, 0, 1);     // Stop the note
      MIDI.sendControlChange(64, 0, 1);
    }
  }
}

```
> 2 votes

---
Tags: arduino-mega, programming, midi
---


title: Atmega32u4 issue

text:
# Question
Title: Atmega32u4 issue
I made a custom ATmega32u4 board for my project. Components came from clone of Arduino Pro Micro (with bootloader and code which I uploaded) from AliExpress. I soldered everything in to my board according to my schematic but the board doesn't work. I don't have any signal from that.

https://i.stack.imgur.com/qskHc.jpg

# Answer
You have an error in your schematic.

You have used the net name VCC for your main power circuit. However your USB incoming power is labelled as +5V.

That means you have two separate nets - +5V with power on it, and VCC isolated from it entirely.

You need to connect those two nets together - name them both VCC or both +5V so they form a single net (easiest is to adopt VCC since you use that on other connections too).

To "fix" your current PCB you could connect a small wire from the cathode of D2 to pin 44 AVCC on the main chip which will bridge the two nets together.
> 5 votes

---
Tags: atmega32u4, custom
---


# Question
Title: 3.3 V Pro Micro clones flashing LEDs after 1200 bit/s touch
I have several Pro Micro clones.

This morning I uploaded a sketch into one of them (that was previously unprogrammed, so it stayed in bootloader mode) and when I wanted to upload the sketch a second time, the problem began:

When I now run the reset procedure for Arduinos with integrated USB (open the COM port of the Pro Micro for example in PuTTY at 1200 bit/s and close it again), **the LEDs start flashing rapidly and the Arduino disappears from the Windows Device Manager**.

Hover for a (slightly annoying) image:

>

So then I grabbed a second, identical Pro Micro and uploaded the Blink sketch into it. It was also previously unprogrammed. The sketch executed, but when I now do the reset procedure, it exhibits the same behavior now (flashing LEDs).

I can still upload sketches just fine, by setting the COM port to a different (arbitrary) COM port to prevent the reset procedure from reaching the Pro Micro and resetting the Pro Micro manually after starting the upload procedure.

This only happens with the 3.3 V/8 MHz variant, not with the 5 V/16 MHz variant. I have selected the appropriate variant in the IDE.

How can I repair the automatic reset function?

# Answer
I was finally able to solve this by using one of the Pro Micros to re-burn the bootloader of the other one.

For reference, the process is like this:

1. Flash the example sketch "ArduinoISP" into the first Pro Micro
2. Connect the two Pro Micros like this:

```
Programmer (on USB)   Target
GND ----------------- GND
VCC ----------------- VCC
15 ------------------ 15
14 ------------------ 14
16 ------------------ 16
10 ------------------ RST

```
3. Choose "Arduino as ISP" as Programmer
4. Because both are Pro Micros, selecting a different board is not necessary.
5. Click "Burn Bootloader"
> 1 votes

# Answer
Arduino Pro micro will enter bootloader if you connect it with 1200 baudrate. See this pos Upload code on Arduino Leonardo using command line
> 0 votes

---
Tags: usb, reset, arduino-pro-micro
---


# Question
Title: Fluctuating voltage coming out of arduino uno 3.3 output pin
Problem with my arduino is when I check voltage of 3.3 volt pin using multimeter , voltage varries a lot from 1.5v upto 5v. Due to which esp8266 wifi module connected to this 3.3v pin gets very hot.

Is the arduino is faulty or can me made to produce steady 3.3 v . Kindly suggest .

Thank you.

# Answer
> 2 votes
The Arduino cannot power an ESP8266 directly.

A genuine Arduino has the LP2985 which can provide up to 150mA (about a quarter of what you need for an ESP8266) and will go into "thermal shutdown" when it gets overloaded.

However, a Chinese (or other cheap) clone could use something even less powerful, with or without thermal protection. In this case overloading the 3.3V pin could irreversibly damage the 3.3V regulator (which may be internal to the USB chip, killing the USB connection in the process) and thus render it unable to regulate the voltage down to 3.3V properly.

If the latter is the case then it is also possible that the higher voltage passed through by the failed regulator could have also killed the ESP8266 chip.

# Answer
> 1 votes
I am sure the voltage is stable without load. Voltage fluctuations are sign of not enough current available.

If you look into the Uno specs, you will find out that the 3.3 V pin can supply max 50 mA.

If you look into esp8266 datasheet in power section you will find out that it needs far more current than 50 mA.

Power the esp8266 from 5V pin over a voltage converter.

---
Tags: arduino-uno, esp8266, voltage-level
---


# Question
Title: Arduino Uno ADCH register stuck at 255 when read from ISR
I'm working on a project that will essentially become an oscilloscope in the long run. I am following this guide. My code is uploaded here for more reference.

In my .ino file I have called functions to set up register such that I have a timer ISR called at a frequency of 100 KHz, and an ADC clock rate of 2 MHz. The ADC is also set so that the result is left shifted so ADCH contains an 8-bit result. In a separate .h file I have an ADC ISR that looks like this:

```
ISR(ADC_vect)
{
  // Read 8-bit conversion result from ADCH.
  uint8_t byte0 = ADCL;
  uint8_t byte1 = ADCH;

  data_byte = byte1;
  flag = true;
}

```

The loop() function is the following:

```
void loop()
{
  if (flag == true)
  {
    //Serial.println("ISR HIT");
    Serial.println(data_byte);
    flag = false;
  }
}

```

So, when the ISR is called the flag is set to true, and in the loop() function I am notified with an "ISR HIT" printed on the serial monitor, this operation is successful.

However, I also have a volatile global variable in my .ino function called **data\_byte** (also declared as an extern in the .h file) that I set byte1 to. When byte1 is printed to the serial monitor the result is:

```
255
255
255

```

**Any ideas on why the value of ADCH is stuck at 255?** My hardware is simply a light sensor connected to pin A0, 3.3 V, and GND.

# Answer
It would seem the problem lies here:

```
// Set Register to all zeros since Vref
// will be set to internal voltge and
// analog pin A0 is used.
ADMUX = 0x00;

```

According to the datasheet, the bits `REFS[1:0]` of the `ADMUX` register select the voltage reference as:

* 00: AREF, Internal V ref turned off
* 01: AVCC with external capacitor at AREF pin
* 10: Reserved
* 11: Internal 1.1V Voltage Reference with external capacitor at AREF pin

Settings those bits to zero means that you are now supposed to provide your own reference through the AREF pin. If you want to use the 5 V supply as a reference, you should set them to 01. This is confirmed by the block schematic. Here is the part of that schematic relative to the reference voltage:

When `REFS0` is zero, the highlighted transistor does not conduct, hence the only way to provide a voltage reference is through the AREF pin.
> 0 votes

---
Tags: arduino-uno, interrupt, adc, analog-sampling, digital-analog-conversion
---


title: Need help on Arduino as ISP

text:
# Question
Title: Need help on Arduino as ISP
If I use an Arduino board to bootload a new chip, is it still possible to use the microcontroller on the board for another project, or it will only be for bootloading new chips.

# Answer
There are more ways to flash a bootloader to new AVR chip. To which you refer? If you replace the chip on Uno to burn a bootloader to it with a programmer, then it is very unclear what you are asking, because the original chip is not involved in this process.

If you ask about ArduinoISP sketch, then simply it is a sketch. You upload it as any other sketch and replace it with any other sketch.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: (ultrasonic sensor code : No such file or directory)
I'm beginning in Arduino I do not understand what the error means. Please tell me where I can find the resources to understand it and allow the code to compile.

```
#include <RCSwitch.h>
#include <Ultrasonic.h>

Ultrasonic ultrasonic(11,10);
RCSwitch mySwitch = RCSwitch();

int i;

void setup() {
    mySwitch.enableTransmit(4);
}

void loop() {
    i = ultrasonic.Ranging(CM);
    mySwitch.send(i, 24);
    delay(100);
}

```

> Arduino: 1.8.7 (Windows 7), Board: "Arduino/Genuino Uno"
>
> 433mhz-lcd-water-level-transmitter:2:24: error: Ultrasonic.h: No such file or directory
>
> compilation terminated.
>
> exit status 1 Ultrasonic.h: No such file or directory
>
> This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

# Answer
It means what it says:

> Ultrasonic.h: No such file or directory

The file `Ultrasonic.h` can't be found.

Anything in your code that starts `#include...` is usually a *library*. These are third party pieces of software that you have to obtain and install into the relevant location (See Installing Additional Arduino Libraries).

Some libraries are bundled with the IDE, and some are available through the "library manager" in the IDE. However most aren't, and you will have to get used to finding those libraries and installing them.

The location you got your example code from will most likely link you to where to find the relevant libraries to get the code working.
> 1 votes

# Answer
This kind of error means that the Arduino IDE (assuming that is what your are using) did not find 'Ultrasonic.h' in a folder named 'libraries' within your Arduino sketch folder. (Some libraries are contained in other places within the IDE's executable, but putting your additional libraries in '.../libraries' keeps everything easy to find and maintain).

Go to `File | Preferences` (in Windows or Linux) or `Arduino | Preferences` (Mac). The top box in that dialog is the path to your sketch folder. That folder should contain one called 'libraries'.

The libraries folder should have a folder for each library, so in this case, there should be a folder named 'Ultrasonic', containing files 'Ultrasonic.h' and 'Ultrasonic.cpp'. There may be other items in there as well, perhaps an Examples folder, a 'keywords.txt' file (helps the IDE with syntax coloring), a text file with release notes, etc., but the important structure is

```
[path/to/your/sketch/folder]
     libraries
         Ultrasonic
              Ultrasonic.h
              Ultrasonic.cpp
         someotherlibrary
              someotherlibrary.h

```

etc.
> 1 votes

# Answer
i found another library ultrasonic solve my first problem(Ultrasonic.h: No such file or directory) but then have another error... it say(class Ultrasonic' has no member named 'Ranging').... in this time i changed some of my code and now working good

my code after solve

```
#include <RCSwitch.h>
#include <Ultrasonic.h>

Ultrasonic ultrasonic(11,10); // (Trig PIN,Echo PIN)
RCSwitch mySwitch = RCSwitch();

int i;

void setup() {
  mySwitch.enableTransmit(4);
}

void loop() {
Ultrasonic ultrasonic(11,10,3000); // (Trig PIN,Echo PIN, Max.TimeOut in µsec )
  mySwitch.send(3000 ,24);
  delay(100);
}

```
> 0 votes

---
Tags: arduino-uno, programming, sensors
---


# Question
Title: Powering Arduino and LED strips from one adapter
My project has my Arduino controlling 10 led strips. I'm going with a plan by @gre\_gor that is posted here: Setting 10 RGB Strips Independently from Single Arduino ...where each strip is controlled by an STM32 driver.

I'm packing all electronics into a tight space and will need to have the power adapter external with just the cable coming in.

I need power both to the arduino and directly to the stm32's.

Question: can I simply split the 12V power cable to send power to both the led strips and the arduino? Or is there something I should worry about?

# Answer
Powering an Arduino and LED strips is no different to powering your TV, satellite receiver, DVD player, etc all from one socket in the wall.

Connect all the grounds (-) together, and connect all the powers (+) together.

All you need to worry about is that the total current draw of all the devices combined doesn't exceed the amount of current that the power supply can provide (oh, and that they all operate at the same voltage, of course).
> 0 votes

---
Tags: arduino-uno, led-strip
---


title: Arduino Protothreads by Example

text:
# Question
Title: Arduino Protothreads by Example
I am trying to get Arduino working with Protothreads and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:

```
#include <pt.h>

static struct pt t1, t2;

void setup() {
    PT_INIT(&t1);
    PT_INIT(&t2);
}

void loop() {
    doSomething(&t1, 500);
    doSomethingElse(&t2, 500);
}

static int doSomething(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(100);
    PT_END(pt);
}

static int doSomethingElse(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(250);
    PT_END(pt);
}

```

Does anyone see anything that jumps out at them as missing or wrong?

# Answer
> 2 votes
Check this example: rather than sleep(), it uses PT\_WAIT\_UNTIL

```
  while(1) {
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
      timestamp = millis();
      doSomething();
  }

```

That should be the proto-thread way of waiting: PT\_WAIT\_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.

The rest looks fine, but I have not tried to run the code.

# Answer
> 0 votes
Why reinvent the wheel? There are libraries that can do just that for you. For example **ArduinoThread**. I tried it out and did not need to keep looking further. There are also Wiring and SoftTimer but I did not try those.

---
Tags: programming, threads
---


title: Programing a Bare Pic32

text:
# Question
Title: Programing a Bare Pic32
I recently received two types of Pic32 microcontrollers from Microchip, specifically the `PIC32MX270F256B` and the `PIC32MX230F256B`. I would like to use an Arduino Uno to setup the bootloader and to do all the programming. I found a tool to upload to the board here, but as it is from a 2012 forum here, I cannot figure out what it is exactly used for. It seems to be able to upload hex files, but in which format and to what is unclear to me. I also found Arduino bootloaders for a similar group of microcontroller here, however I cannot tell exactly which version I need, if any, or how to upload it.

Any help on how to use these tools or others would be greatly appreciated as my only experience with Arduino before this is with a simple to program to Arduino Uno.

# Answer
> 2 votes
I am unaware of any Arduino-based tools for installing a bootloader on a PIC32. If you are going to work with PIC32 you really should invest in a proper programmer.

I often use (pretty much throw-away) Chinese clones of the PICkit2 programmer. You can find them on eBay nice and cheap. Genuine Microchip programmers are pretty expensive, so these cheap clones are quite handy...

You will also want to install the chipKIT environment into the Arduino IDE.

When it comes to the bootloader there are no official boards that use those chips. So you will need to compile your own version, which is not trivial. You will need to install MPLAB-X and the XC32 compiler and create a new profile within the project with the right settings for your board.

And then of course you will have to craft a board configuration for your custom board.

All-in-all it's quite a complex task porting a new board / chip to the chipKIT environment, and you would probably be better off directly using MPLAB-X and programming directly in C (although it's harder to get started in that environment). The PIC32 chips are considerably more complicated to work with than little AVR chips.

---
Tags: uploading
---


# Question
Title: Change operational mode of CAN transceiver
I have two MCP2515 stand-alone CAN controllers with SPI interface, two TJA1042 CAN transceivers and two Arduino Uno boards. As you may know TJA1042 have two operational modes:

1. Sleep mode
2. Normal mode.

If I want to change the mode of operation of one transceiver from sleep mode to normal mode(wake it up), I should send a wake up pattern waves from the other transceiver which is in normal mode. for example one of the wake up patterns is: 5.5 µS low, 5.5 µS high and again 5.5 µS low. Now I don't know how to send these patterns with Arduino because MCP2515 is SPI interface.

I use this library: MCP\_CAN

# Answer
> 1 votes
Transmitting this "wake signal" does not "wake" the transceiver. What it's actually doing is the transceiver, when in "standby" mode, only allows through signals that have a dominant or recessive state that is longer than the filter time (5.5µs). Any transitions in the bus after a stable period of 5.5µs or more will get passed through.

The transceiver does *not* enter "normal" mode at that point. It is down to the CAN device to activate the transceiver through setting the STB pin LOW.

> When pin RXD goes LOW to signal a wake-up request, a transition to Normal mode will not be triggered until STB is forced LOW.

Exactly *what* you send is of no consequence to the transceiver - only whether it has D and R states that are longer than 5.5µS. It's up to the CAN device to interpret them and know if it should wake up the transceiver and place it in NORMAL mode.

And the MCP2515 also doesn't care what it receives. When the WAKEIE bit is set it will cause the MCP2515 itself to wake from its sleep mode when *anything* is received - at which point it signals to the Arduino through its INT pin that it's woken up.

However your chosen library has no ability included in it to control the WAKEIE bit of MCP\_CANINTF - only the TXxIF bits are supported. So you will have to expand the library to provide that facility.

The general idea of operation is:

* The transceiver lets through a "slow" signal (like transmitting 0b00110011)
* The MCP2515 receives "something"
* INT pin goes LOW and the Arduino reacts to it
* The Arduino drives STB LOW and reception can proceed normally.

Note that it is the Arduino that will be controlling STB, not the MCP2515.

---
Tags: arduino-uno, spi, can-bus
---


title: 8relay module asks more than specs

text:
# Question
Title: 8relay module asks more than specs
I have a 8 relay module that should use not more than 20 mA per relay. Altough when measuring it asks around 70. If I use 6 relays, that would be more than an Arduino Mega can give. (I already lost 1 arduino here.)

How this is possible..?

# Answer
it is solved by giving the relay module power with external transfo. Not by arduino
> -1 votes

# Answer
Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.

Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.

The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.
> 0 votes

---
Tags: arduino-mega, relay
---


# Question
Title: 7 segment multiple display, only display 1 digit
I try to create a display so that when I press the button, the counter is increased by one. The problem is only one of them light up and it is not showing the correct output, it is showing the combination of both digit (e.g. 01 showing 0, 02 showing 8). Here is my full code.

```
const int a = 8;  //For displaying segment "a"
const int b = 9;  //For displaying segment "b"
const int c = 4;  //For displaying segment "c"
const int d = 5;  //For displaying segment "d"
const int e = 6;  //For displaying segment "e"
const int f = 2;  //For displaying segment "f"
const int g = 3;  //For displaying segment "g"
const int D1 = 7;
const int D2 = 13;

bool bPress = false;
const int IncbuttonPin = 10;

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonPushCounterD1 = 0;
int buttonPushCounterD2 = 0;

int IncbuttonState = 0;
int lastIncbuttonState = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(a, OUTPUT);  //A
  pinMode(b, OUTPUT);  //B
  pinMode(c, OUTPUT);  //C
  pinMode(d, OUTPUT);  //D
  pinMode(e, OUTPUT);  //E
  pinMode(f, OUTPUT);  //F
  pinMode(g, OUTPUT);  //G
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);

  pinMode( IncbuttonPin , INPUT_PULLUP );
  Serial.begin(9600);

}

void loop() {

   IncbuttonState = digitalRead(IncbuttonPin);

   checkIncButtonPress();

  if( bPress ){
    bPress = false;
     turnOff();
     lightDigit1(buttonPushCounterD1);
     delay(5);
     lightDigit2(buttonPushCounterD2);
     delay(5);
  }
}

void checkIncButtonPress()
{
   // compare the IncbuttonState to its previous state
  if (IncbuttonState != lastIncbuttonState) {
    // if the state has changed, increment the counter
    if (IncbuttonState == LOW) {
      // if the current state is HIGH then the button went from off to on:
      bPress = true;
      buttonPushCounter++;
      buttonPushCounterD1 = buttonPushCounter / 10;
      buttonPushCounterD2 = buttonPushCounter % 10;
      Serial.println("on");
      Serial.println(buttonPushCounterD1);
      Serial.println(buttonPushCounterD2);

    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastIncbuttonState = IncbuttonState;

}

void lightDigit1(byte digit) {
  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  displayDigit1(digit);
}

void lightDigit2(byte digit) {
  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  displayDigit2(digit);
}

void displayDigit1(byte digit)
{
 //Conditions for displaying segment a
 if(digit!=1 && digit != 4)
 digitalWrite(a,HIGH);

 //Conditions for displaying segment b
 if(digit != 5 && digit != 6)
 digitalWrite(b,HIGH);

 //Conditions for displaying segment c
 if(digit !=2)
 digitalWrite(c,HIGH);

 //Conditions for displaying segment d
 if(digit != 1 && digit !=4 && digit !=7)
 digitalWrite(d,HIGH);

 //Conditions for displaying segment e
 if(digit == 2 || digit ==6 || digit == 8 || digit==0)
 digitalWrite(e,HIGH);

 //Conditions for displaying segment f
 if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
 digitalWrite(f,HIGH);
 if (digit!=0 && digit!=1 && digit !=7)
 digitalWrite(g,HIGH);
}

void displayDigit2(byte digit)
{
// digitalWrite(D1, HIGH);
// digitalWrite(D2, LOW);
 //Conditions for displaying segment a
 if(digit!=1 && digit != 4)
 digitalWrite(a,HIGH);

 //Conditions for displaying segment b
 if(digit != 5 && digit != 6)
 digitalWrite(b,HIGH);

 //Conditions for displaying segment c
 if(digit !=2)
 digitalWrite(c,HIGH);

 //Conditions for displaying segment d
 if(digit != 1 && digit !=4 && digit !=7)
 digitalWrite(d,HIGH);

 //Conditions for displaying segment e
 if(digit == 2 || digit ==6 || digit == 8 || digit==0)
 digitalWrite(e,HIGH);

 //Conditions for displaying segment f
 if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
 digitalWrite(f,HIGH);
 if (digit!=0 && digit!=1 && digit !=7)
 digitalWrite(g,HIGH);
}

void turnOff()
{
  digitalWrite(a,LOW);
  digitalWrite(b,LOW);
  digitalWrite(c,LOW);
  digitalWrite(d,LOW);
  digitalWrite(e,LOW);
  digitalWrite(f,LOW);
  digitalWrite(g,LOW);
}

```

when I remove the code

```
     lightDigit1(buttonPushCounterD1);
     delay(5);

```

It is showing the correct output, but only for 1 digit. Anyone can help me on this? Thanks.

# Answer
You aren't multiplexing your displays properly.

At the moment you are doing:

1. Do nothing until the button is pressed
2. Switch on display 1
3. Turn on the segments for digit 1
4. Wait 5ms
5. Switch off display 1
6. Switch on display 2
7. Turn on the segments for digit 2
8. Wait 5ms
9. Go to 1

For about 5ms you will get a brief flash on one digit, but since you don't turn off the segments you turned on for that digit they are just added to for the second digit - which you display for an extended period.

To multiplex properly you must:

* Turn off segments that are no longer used for the current display (best to turn them *all* off)
* Repeatedly display *both* digits *all the time*.

Ideally your method would be:

1. Turn off all segments
2. Turn on segments for digit 1
3. Turn on digit 1
4. Delay 5ms
5. Turn off digit 1
6. Turn off all segments
7. Turn on segments for digit 2
8. Turn on digit 2
9. Delay 5ms
10. Turn off digit 2
11. Go to 1 (usually the `loop()` handles that for you).

And *separate* to that you handle your button press and changing the value to display.

Also note the turning off of a digit *before* arranging the segments for the next digit. This prevents *ghosting* where you get a faint impression of the previous digit overlaid on the current digit.
> 1 votes

---
Tags: 7-segment
---


# Question
Title: If/Else Statements on Arduino not executing
I have a bit of code below, the problem is only the first 'if' statement will execute when called on. When I call on *u, q, or any of the other if statements* it will go straight to the else and not execute. Tried switching the following ifs to 'else if' but got the same result.

```
#include "Arduino.h"
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include "DHT.h"

DHT dht1(3, DHT11);
DHT dht2(2, DHT11);

void setup()
{
  pinMode(13,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(4,OUTPUT);
  digitalWrite(13,LOW);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  digitalWrite(10,LOW);
  digitalWrite(9,LOW);
  digitalWrite(8,LOW);
  digitalWrite(7,LOW);
  digitalWrite(6,LOW);
  digitalWrite(5,LOW);
  digitalWrite(4,LOW);
  Serial.begin(9600);
  dht1.begin();
  dht2.begin();
}

void loop()
{
  float DHT11_t = dht1.readTemperature(true);
  float DHT21_t = dht2.readTemperature(true);

  if(Serial.read() == 'u')
  {
    Serial.println();
    Serial.print(DHT11_t,1);
    Serial.println();
    Serial.print(DHT21_t,1);
    Serial.println();
  }

  if(Serial.read() == 'c')
  {
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
    Serial.print("NDX");
    Serial.println();
    Serial.print("u");
    Serial.println();
  }

  if(Serial.read() == 'q')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
    Serial.print("STX");
    Serial.println();
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    Serial.print("u");
    delay(2000);
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    Serial.print("NDX");
    Serial.println();
    Serial.print("u");
    Serial.println();
  }

  if(Serial.read() == 'w')
  {
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
  }

  else if(Serial.read() == 'e')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
  }

  if(Serial.read() == 'r')
  {
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
  }

  if(Serial.read() == 't')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
    delay(30000);
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    delay(750);
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
    delay(30000);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
  }

  if(Serial.read() == 'y')
  {
    digitalWrite(13,HIGH);
    digitalWrite(12,HIGH);
    digitalWrite(11,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(9,HIGH);
    delay(30000);
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    delay(750);
    digitalWrite(8,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(4,HIGH);
    delay(30000);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
  }

  else
  {
    digitalWrite(13,LOW);
    digitalWrite(12,LOW);
    digitalWrite(11,LOW);
    digitalWrite(10,LOW);
    digitalWrite(9,LOW);
    digitalWrite(8,LOW);
    digitalWrite(7,LOW);
    digitalWrite(6,LOW);
    digitalWrite(5,LOW);
    digitalWrite(4,LOW);
  }

}

```

# Answer
> 4 votes
`Serial.read()` takes the first byte out of the serial buffer. Once it's executed, this byte is gone, so the `Serial.read()` in the next if statement will fetch the next byte (if available). What you can do is assign the result of `Serial.read()` to some variable before the first if statement, and then use that variable instead of `Serial.read()` in the if statements.

---
Tags: arduino-uno, serial, programming, arduino-ide, loop
---


# Question
Title: Assembly for loop repeating 2 times when it's only suppose to do it once
*I'm programming an Arduino Nano so I belive that this question should be qualified for this SE.*

I am trying to dim up an LED using a for loop in AVR assembly.

My problem is that the cycle is repeated twice before ending, while it is suppose to end after the first cycle.

A cycle is when the `red_loop` is repeated 256 times (to dim the led up). At that point, the value should overflow causing the variable to go back to 0. The code should stop there, but mysteriously, it does another cycle and then it stops.

Does anyone know why?

Here is my code :

```
.org 0x000

ldi r16, 0b111
out ddrb, r16

ldi r16, 0xff
out portb, r16

ldi r16, 0

; ff00 pin
; ff01 value
; ff02 led

ldi r16, 0b000
sts $ff00, r16

ldi r16, 0
sts $ff01, r16

red:
    ldi r16, 0b001
    sts $ff00, r16

red_loop:
    rcall pwm

    lds r16, $ff01
    inc r16
    sts $ff01, r16
    cpi r16, 0
    brne red_loop

end:
    rjmp end

pwm:
    ldi r24, 190

pwm_pre_loop:
    ldi r17, 0

pwm_loop:
    lds r16, $ff01
    cp r17, r16
    brge off

    cp r17, r16
    brlo on

pwm_loop_check:
    inc r17
    cpi r17, 0
    brne pwm_loop

    inc r24

    cpi r24, 0
    brne pwm_pre_loop

    ret

on:
    lds r16, $ff00

    sbrc r16, 0
    cbi portb, 0

    sbrc r16, 1
    cbi portb, 1

    sbrc r16, 2
    cbi portb, 2

    rjmp pwm_loop_check

off:
    lds r16, $ff00

    sbrc r16, 0
    sbi portb, 0

    sbrc r16, 1
    sbi portb, 1

    sbrc r16, 2
    sbi portb, 2

    rjmp pwm_loop_check

```

# Answer
> 1 votes
The problem is that the register `r17`, which you use as a PWM timing ramp, overflows twice every time you enter `pwm_pre_loop`:

* when you increments it past 127, it overflows to −128
* when you increment it past 255, it overflows to 0.

When using a counter the way you are using `r17` here, you usually have it overflow only once per cycle: either you consider it holds a signed number which overflows from 127 to −128, or you consider it holds an unsigned number which overflows from 255 to 0. I guess the latter is more common. Your code is confused about that register's signedness:

* The instruction `brge` (named “Branch if Greater or Equal (Signed)” in the instruction set datasheet) tests the `S` (sign flag) bit of the status register, which is useful for *signed* comparisons.
* The instruction `brlo` (“Branch if Lower (Unsigned)”) tests the carry flag, which is used for *unsigned* comparisons.

You should decide once on the signedness of the counter, and then use it consistently. Since here unsigned makes more sense, you can just replace `brge` by `brsh` (“Branch if Same or Higher (Unsigned)”).

Or better yet, remove the second test, which is redundant:

```
pwm_loop:
    lds r16, value
    cp r17, r16
    brsh off  ; if (r17 >= r16) goto off;
    rjmp on   ; else goto on;

```

Note by the way that you can name your RAM variables. And you can use some of the other available registers instead of the RAM.

---
Tags: avr, assembly
---


title: NodeMcu pins and an RGB LED

text:
# Question
Title: NodeMcu pins and an RGB LED
I'm using a NodeMcu for my project and am running out of pins to use. I have a MFRC522 Module, IR Receiver, Buzzer and RGB LED connected. I am facing the problem that whenever I start scanning for RFID tags with the MFRC522 module, the onboard LED starts flashing very fast and the RGB LED changes to an undefined color.

I looked up the pin definitions of the NodeMcu, but couldn't quite find information on what pins I can use for this and which I can't, and why this only happens once I start up the RFID reader.

This is my wiring sketch:

I found this pin layout image, as well as the datasheet.

The code shouldn't be really relevant since it works before starting the RFID reader, but here is the setup of the reader, just in case:

```
#define SS_PIN D4   // SPI - Slave Select Pin
#define RST_PIN D2  // SPI - Reset Pin - not actually connected

MFRC522 mfrc522(SS_PIN, RST_PIN);

// Initial setup for SPI and MFRC522
bool rfidSetupCompleted = false;
void setupReader()
{
  SPI.begin();
  mfrc522.PCD_Init();
  rfidSetupCompleted = true;
}

```

These are the pin definitions of the RGB LED:

```
#define LED_BLUE D8
#define LED_GREEN D3
#define LED_RED D2

```

Any help is highly appreciated! I'm assuming I am using a pin that is used for other purposes (such as maybe D8), but I can't figure out which, and why. I did try to change up the pins and switched D0 and D8 (buzzer and one LED pin), but without luck. I also tried disconnecting each LED pin separately, but didn't learn anything from that either.

# Answer
> 1 votes
I fixed the issue by swapping pin D4 and D8, and then setting up the MFRC522 at the very start of the program. I originally set it up before I started using it, which caused the color to change during the first scan.

# Answer
> 0 votes
SPI.begin sets io15 (D8) mode even it is not used as SS pin for your device. It is better to use io15 (D8) as slave select pin for one of the slave devices. In your case for the one device you have on SPI bus.

Pins io 0 (D3) and io 2 (D4) have on-board pull-up, because they are boot configuration pins. Set them LOW right after setting pinMode for them, to not let current to LED RGB legs.

---
Tags: esp8266, nodemcu, rfid, rgb-led
---


# Question
Title: One port of motor shield doesn't operating stepper motor
1. One port of my motor shield (i.e M1 & M2) is not driving the stepper motor as it should.stepper motor jitters at its position.
2. While the other port (M3 & M4) works fine but it makes stepper motor too hot and also it's respective motor driver L293D IC.
3. While all the ports of motor shield works fine with DC Motor.

I am making CNC plotter using this setup.
I am powering motor shield with 12 V adapter and Arduino is connected with USB cable.

This is the code I am using :

```
#include <Servo.h>
#include <AFMotor.h>

#define LINE_BUFFER_LENGTH 512

char STEP = MICROSTEP ;

// Servo position for Up and Down
const int penZUp = 115;
const int penZDown = 83;

// Servo on PWM pin 10
const int penServoPin =10 ;

// Should be right for DVD steppers, but is not too important here
const int stepsPerRevolution = 48;

// create servo object to control a servo
Servo penServo;

// Initialize steppers for X- and Y-axis using this Arduino pins for the L293D H-bridge
AF_Stepper myStepperY(stepsPerRevolution,1);
AF_Stepper myStepperX(stepsPerRevolution,2);

/* Structures, global variables    */
struct point {
  float x;
  float y;
  float z;
};

// Current position of plothead
struct point actuatorPos;

//  Drawing settings, should be OK
float StepInc = 1;
int StepDelay = 0;
int LineDelay =0;
int penDelay = 50;

// Motor steps to go 1 millimeter.
// Use test sketch to go 100 steps. Measure the length of line.
// Calculate steps per mm. Enter here.
float StepsPerMillimeterX = 100.0;
float StepsPerMillimeterY = 100.0;

// Drawing robot limits, in mm
// OK to start with. Could go up to 50 mm if calibrated well.
float Xmin = 0;
float Xmax = 40;
float Ymin = 0;
float Ymax = 40;
float Zmin = 0;
float Zmax = 1;

float Xpos = Xmin;
float Ypos = Ymin;
float Zpos = Zmax;

// Set to true to get debug output.
boolean verbose = false;

//  Needs to interpret
//  G1 for moving
//  G4 P300 (wait 150ms)
//  M300 S30 (pen down)
//  M300 S50 (pen up)
//  Discard anything with a (
//  Discard any other command!

/**********************
 * void setup() - Initialisations
 ***********************/
void setup() {
  //  Setup

  Serial.begin( 9600 );

  penServo.attach(penServoPin);
  penServo.write(penZUp);
  delay(100);

  // Decrease if necessary
  myStepperX.setSpeed(600);

  myStepperY.setSpeed(600);

  //  Set & move to initial default position
  // TBD

  //  Notifications!!!
  Serial.println("Mini CNC Plotter alive and kicking!");
  Serial.print("X range is from ");
  Serial.print(Xmin);
  Serial.print(" to ");
  Serial.print(Xmax);
  Serial.println(" mm.");
  Serial.print("Y range is from ");
  Serial.print(Ymin);
  Serial.print(" to ");
  Serial.print(Ymax);
  Serial.println(" mm.");
}

/**********************
 * void loop() - Main loop
 ***********************/
void loop()
{

  delay(100);
  char line[ LINE_BUFFER_LENGTH ];
  char c;
  int lineIndex;
  bool lineIsComment, lineSemiColon;

  lineIndex = 0;
  lineSemiColon = false;
  lineIsComment = false;

  while (1) {

    // Serial reception - Mostly from Grbl, added semicolon support
    while ( Serial.available()>0 ) {
      c = Serial.read();
      if (( c == '\n') || (c == '\r') ) {             // End of line reached
        if ( lineIndex > 0 ) {                        // Line is complete. Then execute!
          line[ lineIndex ] = '\0';                   // Terminate string
          if (verbose) {
            Serial.print( "Received : ");
            Serial.println( line );
          }
          processIncomingLine( line, lineIndex );
          lineIndex = 0;
        }
        else {
          // Empty or comment line. Skip block.
        }
        lineIsComment = false;
        lineSemiColon = false;
        Serial.println("ok");
      }
      else {
        if ( (lineIsComment) || (lineSemiColon) ) {   // Throw away all comment characters
          if ( c == ')' )  lineIsComment = false;     // End of comment. Resume line.
        }
        else {
          if ( c <= ' ' ) {                           // Throw away whitepace and control characters
          }
          else if ( c == '/' ) {                    // Block delete not supported. Ignore character.
          }
          else if ( c == '(' ) {                    // Enable comments flag and ignore all characters until ')' or EOL.
            lineIsComment = true;
          }
          else if ( c == ';' ) {
            lineSemiColon = true;
          }
          else if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) {
            Serial.println( "ERROR - lineBuffer overflow" );
            lineIsComment = false;
            lineSemiColon = false;
          }
          else if ( c >= 'a' && c <= 'z' ) {        // Upcase lowercase
            line[ lineIndex++ ] = c-'a'+'A';
          }
          else {
            line[ lineIndex++ ] = c;
          }
        }
      }
    }
  }
}

void processIncomingLine( char* line, int charNB ) {
  int currentIndex = 0;
  char buffer[ 64 ];                                 // Hope that 64 is enough for 1 parameter
  struct point newPos;

  newPos.x = 0.0;
  newPos.y = 0.0;

  //  Needs to interpret
  //  G1 for moving
  //  G4 P300 (wait 150ms)
  //  G1 X60 Y30
  //  G1 X30 Y50
  //  M300 S30 (pen down)
  //  M300 S50 (pen up)
  //  Discard anything with a (
  //  Discard any other command!

  while( currentIndex < charNB ) {
    switch ( line[ currentIndex++ ] ) {              // Select command, if any
    case 'U':
      penUp();
      break;
    case 'D':
      penDown();
      break;
    case 'G':
      buffer[0] = line[ currentIndex++ ];          // /!\ Dirty - Only works with 2 digit commands
      //      buffer[1] = line[ currentIndex++ ];
      //      buffer[2] = '\0';
      buffer[1] = '\0';

      switch ( atoi( buffer ) ){                   // Select G command
      case 0:                                   // G00 & G01 - Movement or fast movement. Same here
      case 1:
        // /!\ Dirty - Suppose that X is before Y
        char* indexX = strchr( line+currentIndex, 'X' );  // Get X/Y position in the string (if any)
        char* indexY = strchr( line+currentIndex, 'Y' );
        if ( indexY <= 0 ) {
          newPos.x = atof( indexX + 1);
          newPos.y = actuatorPos.y;
        }
        else if ( indexX <= 0 ) {
          newPos.y = atof( indexY + 1);
          newPos.x = actuatorPos.x;
        }
        else {
          newPos.y = atof( indexY + 1);
          indexY = '\0';
          newPos.x = atof( indexX + 1);
        }
        drawLine(newPos.x, newPos.y );
        //        Serial.println("ok");
        actuatorPos.x = newPos.x;
        actuatorPos.y = newPos.y;
        break;
      }
      break;
    case 'M':
      buffer[0] = line[ currentIndex++ ];        // /!\ Dirty - Only works with 3 digit commands
      buffer[1] = line[ currentIndex++ ];
      buffer[2] = line[ currentIndex++ ];
      buffer[3] = '\0';
      switch ( atoi( buffer ) ){
      case 300:
        {
          char* indexS = strchr( line+currentIndex, 'S' );
          float Spos = atof( indexS + 1);
          //         Serial.println("ok");
          if (Spos == 30) {
            penDown();
          }
          if (Spos == 50) {
            penUp();
          }
          break;
        }
      case 114:                                // M114 - Repport position
        Serial.print( "Absolute position : X = " );
        Serial.print( actuatorPos.x );
        Serial.print( "  -  Y = " );
        Serial.println( actuatorPos.y );
        break;
      default:
        Serial.print( "Command not recognized : M");
        Serial.println( buffer );
      }
    }
  }

}

/*********************************
 * Draw a line from (x0;y0) to (x1;y1).
 * int (x1;y1) : Starting coordinates
 * int (x2;y2) : Ending coordinates
 **********************************/
void drawLine(float x1, float y1) {

  if (verbose)
  {
    Serial.print("fx1, fy1: ");
    Serial.print(x1);
    Serial.print(",");
    Serial.print(y1);
    Serial.println("");
  }

  //  Bring instructions within limits
  if (x1 >= Xmax) {
    x1 = Xmax;
  }
  if (x1 <= Xmin) {
    x1 = Xmin;
  }
  if (y1 >= Ymax) {
    y1 = Ymax;
  }
  if (y1 <= Ymin) {
    y1 = Ymin;
  }

  if (verbose)
  {
    Serial.print("Xpos, Ypos: ");
    Serial.print(Xpos);
    Serial.print(",");
    Serial.print(Ypos);
    Serial.println("");
  }

  if (verbose)
  {
    Serial.print("x1, y1: ");
    Serial.print(x1);
    Serial.print(",");
    Serial.print(y1);
    Serial.println("");
  }

  //  Convert coordinates to steps
  x1 = (int)(x1*StepsPerMillimeterX);
  y1 = (int)(y1*StepsPerMillimeterY);
  float x0 = Xpos;
  float y0 = Ypos;

  //  Let's find out the change for the coordinates
  long dx = abs(x1-x0);
  long dy = abs(y1-y0);
  int sx = x0<x1 ? StepInc : -StepInc;
  int sy = y0<y1 ? StepInc : -StepInc;

  long i;
  long over = 0;

  if (dx > dy) {
    for (i=0; i<dx; ++i) {
      myStepperX.onestep(sx,STEP);
      over+=dy;
      if (over>=dx) {
        over-=dx;
        myStepperY.onestep(sy,STEP);
      }
    delay(StepDelay);
    }
  }
  else {
    for (i=0; i<dy; ++i) {
      myStepperY.onestep(sy,STEP);
      over+=dx;
      if (over>=dy) {
        over-=dy;
        myStepperX.onestep(sx,STEP);
      }
      delay(StepDelay);
    }
  }

  if (verbose)
  {
    Serial.print("dx, dy:");
    Serial.print(dx);
    Serial.print(",");
    Serial.print(dy);
    Serial.println("");
  }

  if (verbose)
  {
    Serial.print("Going to (");
    Serial.print(x0);
    Serial.print(",");
    Serial.print(y0);
    Serial.println(")");
  }

  //  Delay before any next lines are submitted
  delay(LineDelay);
  //  Update the positions
  Xpos = x1;
  Ypos = y1;
}

//  Raises pen
void penUp() {
  penServo.write(penZUp);
  delay(penDelay);
  Zpos=Zmax;
  digitalWrite(15, LOW);
    digitalWrite(16, HIGH);
  if (verbose) {
    Serial.println("Pen up!");

  }
}
//  Lowers pen
void penDown() {
  penServo.write(penZDown);
  delay(penDelay);
  Zpos=Zmin;
  digitalWrite(15, HIGH);
    digitalWrite(16, LOW);
  if (verbose) {
    Serial.println("Pen down.");

  }
}

```

This are the connections I made:

I tried replacing motors with each other but the case remains same just the motor now connected to the port(which is not working ) starts jittering and another one works but gets too hot.

# Answer
I ran into the same issue yesterday. The problem is that one of the pins of the M1 Port touches the housing of the usb-jack and shortens Vcc to Gnd. Try to put some tape around the housing...

bye
> 2 votes

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


# Question
Title: Accessing one code using another code on RobotDyn Uno+WiFi board
Ok so I've been trying to do this for quite some time now. Still couldn't get it to work. I am trying to read a ESP8266 WiFi program from a normal Arduino Uno program. I've seen some people do this:

```
#include <SoftwareSerial.h>

```

Then

```
SoftwareSerial esp8266(2,3);

```

Let me see a working example of this?

Thanks for everything.

# Answer
You can't 'access code'. You can write sketches to communicate for example over Serial or SoftwareSerial. You connect the pins of Serial interfaces RX to TX and let sketch in one MCU read or parse what the sketch in other MCU sent over Serial with print or write.

The onboard connection on Uno+WiFi board is over Serial. So you can't use USB and connection to esp8266 at the same time. But you could use SoftwareSerial like other use it with esp8266, if you connect some pins (for example 6 and 7) of Uno headers to Serial of esp8266 which is accessible on the esp8266 header on the board.
> 2 votes

---
Tags: esp8266, softwareserial
---


# Question
Title: How to Connect ESP8266 with ultrasonic sensor and dht11 without breadboard?
I want to connect the sensors in Esp8266 after I code those using arduino uno r3. The problem is that I don't have the idea on connecting those sensors without breadboard. Thank you

# Answer
> 2 votes
If you do not want to use a breadboard, you could solder the wires together of tie them together, so long as none of the wires which aren't supposed to be touching are touching. Or you can also use flex tape! (Don't mind my meme)

# Answer
> 1 votes
A diagram of the internal wiring of a breadboard is found at http://www.fiz-ix.com/2016/04/breadboard-wiring-diagram/

Image duplicated here:

All you need to do is make sure all the same connected points from your breadboard circuit remain connected in the same way on a perfboard or PCB.

There are several ways to make a circuit on perfboard, and this answer on electronics SE shows some examples of using solder bridges as interconnects, short uninsulated wires, and insulated "wire wrap" wires.

You can also find perfboards with the same connection layout as a breadboard for easy transfer from a breadboard-wired circuit, as shown below:

---
Tags: esp8266, sensors, temperature-sensor
---


title: DIP switches on RobotDyn Uno+WiFi

text:
# Question
Title: DIP switches on RobotDyn Uno+WiFi
There are theses 8 small pins on the Uno+WiFi board. Can someone please give me a detailed table or something on the settings of these 8 DIP switches?

I'm sorry if this question has already been answered somewhere else but I am bad at looking for stuff online.

Thanks

# Answer
There are 3 major chips on the board. Atmega 328, esp8266 and the USB converter CH340. Every device has one RX and one TX pin. But you need sometimes connect the Atmega to esp8266, sometimes connect the Atmega to computer over USB and sometimes connect the esp8266 to computer. The first 6 switches are in pairs (RX and TX) for connecting two of the 3 devices.

* 1,2 ON all others OFF connect esp8266 to Atmega. no connection to computer.
* 3,4 ON all others OFF connects Atmega to computer over USB. no connection to esp8266
* 5,6 ON all others OFF connects esp8266 to computer over USB. no connection to Atmega

The switch 7 sets io 0 of esp8266 LOW which puts esp8266 to flashing mode at reboot. So you turn it ON with connection of esp8266 to USB (computer) to upload sketch to esp8266.
> 1 votes

---
Tags: esp8266
---


# Question
Title: nodeMCU - Millis() - Simple Counter - How long is LED on?
PROGRESS, now I have this (WITH GREAT HELP):

```
void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;

void loop()
 {
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

 if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here

    }
  }

 }

```

This now tells me how many millis the gymnast is in the air, divided by 1000.0 with 3 decimals. If I start the Serial Monitor when the gymnast is in the trampoline bed, then I can get the seconds of air\_time the gymnast has. Is there a way to have this script running ONLY for 10 loops?

# Answer
Declare a global (or static) boolean variable to keep track of whether the timer is running or not, as well as a variable to hold the start `millis()` value. When the lux drops below your threshold, subtract the current `millis()` from the start value, and you have the duration in milliseconds, which is trivial to convert to mm:ss.sss format.

Example code (not a complete sketch)

```
uint32_t timer_start = 0;
uint8_t timer_running = false;

void loop() {
  if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.print(millis()-timer_start); // format however you like here
    }
  }
}

```

---

> This now tells me how many millis the gymnast is in the air, divided by 1000.0 with 3 decimals. If I start the Serial Monitor when the gymnast is in the trampoline bed, then I can get the seconds of air\_time the gymnast has. Is there a way to have this script running ONLY for 10 loops?

Certainly. If it is assumed that you want a cumulative total air-time, then you need to declare another global or static variable to hold the cumulative air-time, and you need to have another variable to keep track of how many cycles have passed.

```
void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;
uint32_t total_time = 0;
uint8_t jump_count = 0;

void loop()
{
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

  if (jump_count<10) {
    if (lux>150) {
      if (!timer_running) {
        // Timer is not already running, so capture the start time
        timer_start = millis();
        timer_running = true;
      }
    } else {
      if (timer_running) {
        // The timer is currently running; stop it calculate/print the run time
        timer_running = false;
        // Add this-jump air time to the cumulative total:
        total_time += millis()-timer_start;
        // Increment jump_count
        jump_count++;

        Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here
      }
    }
  } else {
    // Print the total air-time for 10 jumps;
    Serial.println((total_time)) / 1000.0, 3);
  }
}

```
> 3 votes

---
Tags: nodemcu, millis
---


# Question
Title: Using Arduino UNO for uploading a sketch to the Espresso Lite v2
I am trying to use my Arduino UNO as a programming interface to load sketches on the Espresso Lite v2.

I followed the instructions to setup the Wifi network (long press gpio13 and the AP thing), but now I want to run code on it.

I uploaded this sketch to the UNO, in order to allow for serial communication(i chose method 3): `void setup(){
 pinMode(0,INPUT);
 pinMode(1,INPUT);
}
void loop(){
}`

Afterwards I configured the Arduino IDE with the necessary libraries and device manager plugins for the Espresso, so I selected "Espresso Lite 2.0" as the target board and for programmer "Arduino as ISP".

This is what my tools menu looks like:

I connected the 3.3V, GND, TX (to TX) and RX (to RX) and RESET (to RST) headers from the Arduino UNO to the Espresso Lite holes. If I open the Serial Monitor I can see serial output so I think the connections are correct.

I tried to upload an empty sketch and i got these errors (verbose upload): `Sketch uses 246096 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27588 bytes (33%) of dynamic memory, leaving 54332 bytes for local variables. Maximum is 81920 bytes.
C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.13/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x0 -cz 0x400000 -ca 0x00000 -cf C:\Users\ADMINI~1\AppData\Local\Temp\arduino_build_89/sketch_oct08a.ino.bin
esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
 setting board to ck
 setting baudrate from 115200 to 115200
 setting port from COM1 to COM3
 setting address from 0x00000000 to 0x00000000
 setting erase size to 0x00400000
 setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
An error occurred while uploading the sketch
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 read 0, requested 1
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: 0D instead of C0
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: 45 instead of C0
resetting board
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 read 0, requested 1
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: 0D instead of C0
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: 74 instead of C0
resetting board
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 read 0, requested 1
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: 0D instead of C0
trying to connect
 flush start
 setting serial port timeouts to 1 ms
 setting serial port timeouts to 1000 ms
 flush complete
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: 45 instead of C0
warning: espcomm_sync failed
error: espcomm_open failed`

This is the serial output after i tried to upload:

**What am I doing wrong?**

# Answer
> 0 votes
Don't connect reset pins together. Selecting "Arduino as ISP" is irrelevant in many ways.

Put the esp8266 into flashing mode by resetting it with io 0 LOW at reboot (hold button GPIO0 and click the RESET button). **And then Upload from IDE**. The esptool can't reset the board to flashing mode because you don't have RTS and DTS line from Uno.

Picture from manufacturers page:

---
Tags: arduino-uno, serial, esp8266, arduino-ide, ftdi
---


title: ATTINY85 with RGB LED

text:
# Question
Title: ATTINY85 with RGB LED
I'm trying to DIY about a dozen BlinkSticks (discontinued, Adafruit) pictured here

I'm thinking to use a Digispark ATTINY85 to control a single RGB LED to show the status of some program running under Linux. Here is the proto board I have my eye on:

I could either use a single individually addressable RGB LED with a built-in WS281X controller

or a plain RGB LED with each color pin connected to a GPIO pin on the TINY85.

This is my first Arduino project, so I'm not familiar with the best way to approach this project. I'm trying to keep the part count low as well so the serial data approach is appealing too. Has anyone done this before and can explain their setup?

---

Prior work I've found for the simple control approach:

# Answer
The newest blinkstick uses an addressable led, while the Adafruit kit appears to use a regular 4 pin RGB led. These are easier to get.

The digispark and the blinkstick are almost identical, but they use different pins for the USB connection. So to use the firmware for the blinkstick on the digispark, you need to change the pin numbers in usbconfig.h

```
#define USB_CFG_DMINUS_BIT      3
#define USB_CFG_DPLUS_BIT       2

```

PS. the pin numbers in usbconfig.h don't seem to match the schematic, so I'm not sure what's going on
> 1 votes

---
Tags: usb, rgb-led, attiny85
---


title: Leonardo Problem

text:
# Question
Title: Leonardo Problem
I have boiled this down to a very simple piece of code:

```
int testKey;

void setup() {

Serial.begin(9600);

}

void loop() {

Serial.println("Input Source ID "); //Ask me the number

while (Serial.available()==0){ } //Wait for me to answer

testKey = Serial.parseInt();  //Store my answer in this variable

Serial.print("Parsed Input is ");  //Print the results on serial monitor

Serial.println(testKey);

}

```

When I run the code on my Leonardo, or Uno, I expect to have Input Source ID to be printed on the serial monitor. It remains blank (it is set to 9600 baud). If I go ahead and enter a 1, then the serial monitor starts working. However, from this point on, it seems to ask me for the ID again, and print a 0 to the serial monitor:

Parsed Input is 1
Input Source ID
Parsed Input is 0
Input Source ID

It then is waiting for me to enter a new Source ID. If I then enter a 2, this is what I get, in addition to what was already there.

Parsed Input is 1
Input Source ID
Parsed Input is 0
Input Source ID
Parsed Input is 2
Input Source ID
Parsed Input is 0
Input Source ID

My question is, why doesn't the void loop start automatically and immediately prompt me for input? Secondly, after I give it a number, it seems to run it twice, inserting a 0 into the variable. Why? This seems so straightforward, but it has me stumped. I tried some delay statements here and there, to no avail. Thanks in advance.

# Answer
> My question is, why doesn't the void loop start automatically and immediately prompt me for input?

It does. However your serial monitor isn't open at that time and can't receive it. Unlike the Uno the Leonardo *does not reset when you open the serial port*.

A common workaround, to make it look more like an Uno, is to add:

```
while (!Serial);

```

in `setup()` after `Serial.begin(...)`, so that it does nothing until you open the serial terminal.

> Secondly, after I give it a number, it seems to run it twice, inserting a 0 into the variable. Why?

Simple: you're parsing the number as a number. You're then parsing a blank line as the number.

If you have the serial monitor set to send CR + LF as the line ending you get the integer terminated by CR, followed by no integer (represented by 0) followed by LF.
> 1 votes

# Answer
This line:

```
while (Serial.available()==0){ } //Wait for me to answer

```

Doesn't wait for you to answer, it only waits until the first character is typed. This while loop happens about a million times a second on an Uno. You can't possibly type more than one character in that microsecond. Once you type it, the clock starts ticking, because `parseInt()` uses a timeout value, so if no valid digit character is entered by the timeout, it exits. The default timeout is 1000ms (1 second).
> 0 votes

---
Tags: arduino-uno, arduino-leonardo
---


title: Optical Rotary Encoder Index issue

text:
# Question
Title: Optical Rotary Encoder Index issue
I have the following code working correctly except for the Index portion. I am not sure if I have the syntax correct for the hardware. The end result I am looking for is to have the encoder reset to 0 degrees every time the index comes around (360 degrees). I am also looking for any comments on the code as I would like the encoder output to be as accurate and efficient as possible.

Here is the code:

```
// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts
#define CLOCKWISE            1       // direction constant
#define COUNTER_CLOCKWISE    2       // direction constant

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT_PULLUP);
  pinMode(ENCODER0PINB, INPUT_PULLUP);
  pinMode(ENCODER0PINI, INPUT_PULLUP);

  // interrupts
  attachInterrupt(3, onInterrupt, RISING);
  attachInterrupt(4, onReset, CHANGE);

  // enable diagnostic output
  Serial.begin (9600);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible
void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b )
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);

  if (i = 1)
  {
  encoder0Position = 0;
  }
}

```

# Answer
In your onReset() function you have an assignment instead of a comparison:

```
if (i = 1) // This is always true
{
encoder0Position = 0;
}

```

`i = 1` should be `i == 1`
> 2 votes

---
Tags: arduino-mega, rotary-encoder
---


# Question
Title: How do I create a state machine for my purpose?
I am new to Arduino.

I have a motor which drives a sliding door back and forth. The motor is connected to an H bridge which has two control pins (direction, speed). I have a switch which is intended to activate the motor for a set amount of seconds to open the door fully. When the switch is deactivated, the motor reverses for the same duration as opening.

I have written some basic code using the 'if' argument, but my issue is that the code under the 'if' argument loops when my switch is activated/deactivated whereas I want it to run once per switch activation. Looking online I saw that a state machine may be my solution, but my lack of expertise with coding means I cannot create a state machine. This is my code:

```
const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH) {
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //I only need the motor to activate for four seconds, but 'if' loops it infinitely
  } else {
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, HIGH);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //Same issue  here
  }

;
  delay(1);
}

```

# Answer
Creating a few boolian variables could help with this.

```
bool opening = 0
bool closing = 0

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH && opening == 0) { //variable "opening" is tested
    opening == 1  //variable "opening" is set to on
    closing == 0  //variable "closing" is set to off
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW);
  }
    else if (buttonState == Low && closing == 0){ //variable "closing" is tested
      opening == 0    //variable "opening" is set to off
      closing == 1    //variable "closing" is set to on
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, HIGH);
      delay(4000);
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, LOW); //Same issue  here
  }
  delay(1000) // delay is in milliseconds. So 1000 = 1 second
}

```

These new variables are set when the code is ran the first time. Therefore, no looping.
> 1 votes

# Answer
A schematic will help to create a solution. Are you using a resistor, like 10K, to pull the switch pin low? If the button is not pressed and the code keeps looping through like it is pressed, I recommend adding the resistor. You may need to add another component though. Like a micro-switch on the frame of the door that gets tripped while it is closed. Or a button to close the door. Without that every loop through the code will think the switch is held low and activate the motor. Which might burn out the motor or trip a fuse.

```
if(buttonstate == high){
//open door
}
else{
if(microswitch == high){
//H-bridge pins low, low
{
else{
//close door
{

```

simulate this circuit – Schematic created using CircuitLab
> 0 votes

---
Tags: motor, h-bridge
---


# Question
Title: how to increase the delay factor of DHT11?
There is no compiler error but output is showing timeout error. as per as the instruction given in https://github.com/RobTillaart/Arduino/issues/61

it says to increase the timeout factor but i did not found the constraints which were asked to be changed.

# Answer
The DHT11 and DHT22 used to be cheap and easy to use humidity and temperature sensors when they were used together with an Arduino Uno.

But things have changed.

* They are not accurate and can become totally inaccurate with certain gasses or fumes.
* It turned out, that the most used DHT libraries have a serious bug that creates a shortcut in the datasignal. This was no problem with the Arduino Uno, which can output 40 mA with a pin. The newer processors have problems with that shortcut.
* In 2018 the DHT11 seems to behave differently, the internal controller has probably changed.
* Because the communication with the sensors requires accurate timing, the interrupts are turned off temporarily. That was no problem with the slow Arduino Uno, but it is not normal with a faster processor.
* Some libraries use a timeout with a loop or with clock cycles. That worked well with the Arduino Uno, but it is not always reliable with newer processors.

In 2018, all the DHT libraries for the ESP8266 and ESP32 have issues with the DHT11 and DHT22.

Since the sensors are not very accurate anyway, it is best to stay away from all the troubles and avoid them. There are a number of good humidity sensors with I2C interface.
> 0 votes

---
Tags: timers, nodemcu, temperature-sensor
---


title: Bending pins of HC-SR04

text:
# Question
Title: Bending pins of HC-SR04
I got a question regarding the ultrasound sensor (HC-SR04) connecting to the arduino. I have a project, and the space is really tight, so i will have to bend the pins of the HC-SR04. Is this okay to do, and if yes, how should i go about and do this ?

# Answer
> 0 votes
The easiest things to do if space is a premium is to unsolder (or cut) the pins and then solder directly the wire to the corresponding spots.

Otherwise, you can also just get straight pins and replace them, You can also choose on which side of the board, as the holes are though it.

Lastly, about bending, it's doable with pliers if you want to make the pins face "forward" but depending on the quality of your pins they might break in the operation.

---
Tags: arduino-nano, hc-sr04
---


# Question
Title: ESP8266 upload data to google cloud platform
I am trying to upload information to my appspot created with Google App Engine. I am able to do it when I in my browser type:
http://myname.appspot.com/query?city=Copenhagen&temp=20&id=website
But I cannot get it to work on the ESP8266. Here is my code:

```
const char* MY_URL = "http://myname.appspot.com";

void uploadHTTP() {
    // Define the WiFi Client
    WiFiClient client;
    // Set the http Port
    const int httpPort = 80;

    // Make sure we can connect
    if (!client.connect(MY_URL, httpPort)) {
        return;
    }
    else {
        Serial.println("Connected to MY_URL");
    }

    String url = "/query?city=Copenhagen&temp=20&id=ESP8266";

    // Post to appspot
    if (client.connect(MY_URL, httpPort)) {

        // Sent HTTP POST Request
        client.println("POST " + url + " HTTP/1.1");
        Serial.println("POST " + url + " HTTP/1.1");
        client.println("Host: " + String(MY_URL));
        Serial.println("Host: " + String(MY_URL));
        client.println("User-Agent: Arduino/1.0");
        Serial.println("User-Agent: Arduino/1.0");
        client.print("Content-Length: ");
        Serial.print("Content-Length: ");
        client.println(0);
        Serial.println(0);
        client.println("Content-Type: application/x-www-form-urlencoded");
        Serial.println("Content-Type: application/x-www-form-urlencoded");
        client.println("Connection: close");
        Serial.println("Connection: close");
        }
    //Done
    Serial.println("");
    Serial.println("my HTTP done");
    Serial.println("");
}

```

# Answer
> 2 votes
Your biggest problem is that you are trying to use a website URL as a FQDN. That's not going to work.

When you connect to a remote machine you connect to the name (`myname.appspot.com`) which gets translated into an IP address for you to open a connection to.

When you use a web browser it parses the URL to extract the protocol (`http`) and the FQDN (`myname.appspot.com`) and uses the protocol to determine the port (and what language to speak) to connect to, then look up the IP address from the FQDN.

You need to drop the `http://` from your FQDN which is causing it to break (there is no host called `http://myname.appspot.com`). The fact that you are connecting to port 80 and speaking the HTTP language implies that you are using HTTP.

To put it into more layman's terms: if you "need to call Fred to talk about going to the pub" you first look up fred's number in the phone book then call that number. Then only once he has answered do you talk about going to the pub. What you *don't* do is try and find the number to call by looking in the phone book under "talk about going to the pub with Fred". It won't be there.

If you are programming your ESP8266 directly you should consider using the much simpler bundled `ESP8266HTTPClient.h` library.

---
Tags: programming, esp8266, wifi, http
---


# Question
Title: How to monitor state of 50 Digital Inputs
Good day.

I have a specific project need and I spent the past couple of days searching on forum, blogs, etc and I'm still not clear if that's feasible to do with Arduino or not.

I need to monitor the state of ~50 digital inputs and trigger an action when any of the pin changes either from 0 to 1 or from 1 to 0, pretty much the same as pin state interrupt works, only difference is that I need to "listen" to ~50 pins, instead of just a couple. I must be able to identify what pin triggered the action and what was the change (0-\>1 or 1-\>0).

My initial idea is to use a MEGA 2560 and have a group of 50 "if" statements on the main loop comparing the previous state or each pin (stored in individual variables) with the current one and triggering the corresponding action if something changed.

I'd like to hear from the experts here what would be a more elegant or smarter/faster way to accomplishing this.

I'm eager to receive your feedback.

Thank you.

# Answer
> 1 votes
I had a project that used 16 rotary encoders and I used the MUX Shield which uses 74HC4067 analog multiplexers. They port to A0 - A3 on the shield which is fine as you can set these pins to Digital Inputs else you can get teh breakout version and connect to any input pins. I also used a Due since ALL pins can be interrupt enabled. Reading was a bit of a pain but worked like this... The method is.. Continually address each input in turn in the loop or an interrupt is not detected, when an interrupt fires, address each input in turn again to find out which pin changed state. Hope that helps.

# Answer
> 0 votes
The Mega 2560 appears to have 24 pin change interrupts (I haven't checked if they're all broken out on the Mega Arduino board).

A combination of as many pin change interrupts and 'manual' scanning could be quicker than scanning them all individually.

Another option would be to group as many as possible onto the same ports and use direct hardware access to looks for changes- with this you'd be able to do 8 inputs at a time. With 8 inputs on each port, you just need to have seven main checks that the port value has changed and then jump off to a handler that deals with what specific pin has changed and what action is needed.

# Answer
> 0 votes
See answers in Good solution for more interrupts on an Arduino. E.g.:

Answer lhballoti:

You can use an I/O expander, for example an MCP23008 and MCP23017. They are available in SPI and I2c. Interrupts can be configured (edge-sensitive, level-sensitive) for each input.

Answer embedded.kyle:

You could use a Programmable Interrupt Controller (PIC) such as the 82C59A. It will cascade if you need more than the eight interrupts it provides. It's a bit old school but I think it will handle all of your requirements.

---
Tags: interrupt, pins, digital-in
---


# Question
Title: No data sent over serial port in linux c++
TL;DR - I am attempting serial communication with Arduino with code that I found here and nothing gets sent over (Arduino programmed to respond, and I checked that it does with its serial monitor)

Hi there, I was looking for a way to send information over to an Arduino Mega (2560) unit over linux serial port by C++.

I came across the following solution: Solution I'm using this guy's code for write (I'm able to read data from the arduino) and use the same parameters (they work, as I'm able to receive data from the Ardunio). I programmed my Arduino to send "Hi" over serial whenever it sees at least 1 bit of information, and checked it worked through the Arduino IDE Serial Monitor.

Yet when running the C++ code, the arduino doesn't respond. Do anyone might have idea why?

Full disclosure - I inserted @Lunatic999's code to a class so I can make an instance of it for my needs of the code.

```
fd = open(portNameC, O_RDWR | O_NOCTTY | O_SYNC); //open port ("opens file")

```

Serial Parameters:

```
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( fd, &tty ) != 0 ) {
   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( fd, TCIFLUSH );
if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

```

**Write** (this code I put inside a function which I call)

```
unsigned char cmd[] = "INIT \r";
int n_written = 0,
    spot = 0;

do {
    n_written = write( fd, &cmd[spot], 1 );
    spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

```

Arduino code:

```
bool dataRecieved = false;
int ledpin = 13;

void setup() {
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(19200);
}

void loop() {
  while(!dataRecieved)
  {
   digitalWrite(ledpin,HIGH);
   if (Serial.available() > 0)
   {
     dataRecieved = true;
   }
  }
  digitalWrite(ledpin,LOW);
  delay(1000);
  digitalWrite(ledpin,HIGH);
  delay(1000);
  Serial.println("hi");
}

```

# Answer
The Arduino resets the moment you open the serial port. Once reset the bootloader executes, which consumes (and discards since it's invalid) any serial data for a second or so before your sketch runs.

Because of this anything you send immediately after opening the serial port is ignored.

There are two commonly accepted "fixes" for this:

1. Delay for a pre-defined period after opening the serial port, and
2. Have the Arduino send a "READY" signal before doing anything else which your program waits for before sending.
> 0 votes

---
Tags: serial, arduino-mega, c++, linux
---


# Question
Title: ESP8266-01S Stopped responding after second launch
Here's the code:

```
#include <SoftwareSerial.h>
#define RX 6
#define TX 5

String AP = "...";
String PASS = "...";

SoftwareSerial esp8266(RX,TX);

void setup() {
  Serial.begin(9600);
  Serial.println("Setup started");

  esp8266.begin(115200); // Change this to the factory baudrate used by ESP8266
  delay(1000);

  Serial.println("Setting BAUDRATE to 9600");
  esp8266.println("AT+IPR=9600");
  esp8266.begin(9600);
  delay(500);
  Serial.println("Setup finished");

  reset();
  connectWifi();
}

//reset the esp8266 module
void reset() {
  Serial.println("Resetting...");
  esp8266.println("AT+RST");
  delay(3000);

  if (esp8266.find("OK"))
    Serial.println("Module Reset");
  else
    Serial.println("Module Reset Failed!!!");
}

//connect to your wifi network
void connectWifi() {
  Serial.println("Connecting to Wifi...");
  String cmd = String("AT+CWJAP=\"") + AP + "\",\"" + PASS + "\"";
  esp8266.println(cmd);
  delay(4000);
  Serial.println("Checking Wifi...");
  int ctr=0;
  while(!(esp8266.find("OK"))) {
    if(esp8266.find("ERROR")) {
      Serial.println("Cannot connect to wifi...");
      break;
    }
    delay(50);
    ++ctr;
    if(ctr>10){
      Serial.println("Cannot connect to wifi...");
      break;
    }
  }
  Serial.println("ConnectWifi finished");
}

```

The ESP8266-01S wires are as follows:

1. GND to arduino ground
2. 3v3 to arduino 3v3
3. RX to arduino pin 5
4. TX to arduino pin 6
5. EN to arduino 3v3

The thing worked for one time, and when I re-compiled and sent it again without any changes or even button presses, it stopped working. Furthermore, if I connect ESP module directly through arduino rx and tx and connect arduino reset to ground, I still don't get anything. The led on the esp is blinking during data transfers, but everything else doesn't change and I get no response at all.

# Answer
> 0 votes
You need to re-flash your AI Thinker firmware. AT+IPR kills certain versions of the firmware.

Install the latest version of the firmware and use `AT+UART_DEF=9600,8,1,0,0` and `AT+UART=9600,8,1,0,0`. (The former sets the default baud rate, the latter the current baud rate).

You can read more here.

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


# Question
Title: What are the benefits or advantages of Arduino CLI?
I saw that Arduino got a CLI (Command Line Interface), and my first question was "why?" Even after reading the article, I don't see or understand its advantages.

What advantages or benefits does a CLI have for Arduino?

I haven't done much with Arduino in several years. For example, there wasn't an Arduino SE when I was fooling around with Arduino, so I probably have an out of date context for Arduino development.

# Answer
Simple: you can program the Arduino without needing a GUI.

One good example: You have an Arduino connected to a Raspberry Pi built into a robot. You SSH into the Pi, edit the Arduino's program, and upload the new code. All from wherever you happen to be.

A second example: You can integrate Arduino compilation into your own software. Such as a web interface for compiling your code. I know of one such project where the creator has made a custom website for editing their robot code and using UECIDE's CLI (which pre-dates Arduino's) to compile and upload the code to the target board.

And yes, you have an outdated context of Arduino development, as evidenced by your use of the phrase "fooling around with". Arduino is not a toy. It's a development platform and educational tool. Maybe back when you were "fooling around" with it, it was little more than a toy, but things have moved on a long long way since then. The Arduino ecosystem boasts boards with chips from every manufacturer you can imagine to fill every niche you can conceive. The API and available libraries have certainly matured.
> 3 votes

---
Tags: arduino-ide
---


# Question
Title: How to create a weather station with only GY-BME280-3.3 chip and w5100 Ethernet shield mounted over arduino mega 2560 r3
Want to create a weather station with only GY-BME280-3.3 chip and w5100 Ethernet shield mounted over Arduino mega 2560 r3 but I have no previous experience with Arduino. And The Arduino will be hooked up to a router using the Ethernet shield and powered using desktop USB connection or may be with the barrel jack and I want to control it using a GNU/Linux machine. So far I am trying to follow these https://educ8s.tv/arduino-bme280-weather-station,

https://startingelectronics.org/tutorials/arduino/modules/pressure-sensor,

http://cactus.io/projects/weather/arduino-weather-station,

but none of these is an exact match for my setup, so a little confusing as a noob. But my questions is,

How to hook up the GY-BME280-3.3 sensor to the Arduino on which the Ethernet shield is already mounted?

EDIT: So far I have connected the first 4 pins to the pins on the Ethernet on 1-\>3.3v, 2-\>gnd, 3-\>A5, 4-\>A4 ***or*** 1-\>3.3v, 2-\>gnd, 3-\>13, 4-\>11, 5-\>10, 6-\>12 but to no avail. Only 1+6-\>3.3v, 2-\>gnd, 3-\>21, 4-\>20 finds the sensor but reading is 0,0,0mb in that case and shows reading if SparkFun BME280 library is loaded.

Still the question is, if there any other pin combinations where I don't have to join 1+6 to a 3.3v, just one pin to 3.3v will be enough?

# Answer
> 1 votes
You must decide if you want to connect the sensor over I2C or over SPI interface. According to datasheet of the sensor, at power-up pin CSB determines the interface. If CSB is pulled-down SPI is selected. CSB must be connected to VCC to select I²C interface.

On current revisions of Mega and Uno the 'standard location' of I2C pins SDA and SCL is near pin 13 after the Ground and AREF pin. Other location on Mega are pins 20 and 21. (A4 and A5 on Uno). Note that the 'standard location' pis are connected together with the 'numbered' pins, so you can't use 20 and 21 even if you connect the sensor to the standard location pins.

Pin SDO determines the I2C address of the sensor.

If you want to use SPI to connect the sensor to Mega, use SPI pins 50 to 52 and you can use pin 53 as CS (SS) pin. Ethernet shield uses pin 10 as CS for W5100 and pin 4 as CS for pin for the SD card. Note, that Ethernet shield connects to SPI bus on the ICSP header, but those are still SPI bus pins 50 to 52.

Adafruit has a tutorial for this sensor with wiring for Mega.

---
Tags: arduino-mega, sensors, ethernet-shield
---


# Question
Title: ESP8266 timer to trigger actions (logic issue)
so I have an application in which there are 2 specific times (eg 9AM, 6PM) where a variable curPos is updated. Everything is converted in ms since 00:00 (9AM = 32400000, 6PM = 64800000). Now, the actions (curPos updates) should be triggered every day at these times. To retrieve the current real time (always in ms) I'm sending a http request to a website. This is done only once in the setup().

The idea is that I have to access somehow (http request) the current real time in order to determine when are 9AM and 6PM in my ESP8266, since the start of the sketch. The current real time is needed only once at the beginning (in case there's an issue and the sketch restarts). Then I can calculate the difference between the current real time and the timers.

The next step would be to translate the values into a 24hour cycle starting at the startup/reset time, so that it can repeat itself without need to request again the real time.

I'm lost in the logic on how to deal with this and with millis() to check when it's time to trigger one of the actions.

This is what I'm doing now with the HTPP GET payload in the setup() (I can successfully retrieve the 3 values in ms from the GET response)

```
      String payload = http.getString();

      int commaIndex = payload.indexOf(',');
      int secondCommaIndex = payload.indexOf(',', commaIndex + 1); //Search for the next comma just after the first

      mainTime = payload.substring(0, commaIndex).toInt(); //current real time in ms
      timers[0] = payload.substring(commaIndex + 1, secondCommaIndex).toInt(); //9AM in ms
      timers[1] = payload.substring(secondCommaIndex + 1).toInt()); //6PM in ms

      timers[0] = abs(mainTime - timers[0]); //the time difference before reaching the first timer (in ms)
      timers[1] = abs(mainTime - timers[1]); //the time difference before reaching the second timer (in ms)

      // my attempt to turn the time differences into a 24hrs "local" (in the sketch) time
      //dayMs is 24hrs in ms (86400000)
      if(timers[0] < 0)
        timers[0] = dayMs - timers[0];

      if(timers[1] < 0)
        timers[1] = dayMs - timers[1];

```

and in the loop I'd need a comparison (I think) but I'm just really lost on this

```
//I think millis need to be reset after 24hrs since the start of the sketch?

if(millis() == timers[0]){
      curPos = 1; //first timer expired then trigger
  }else if(millis() == timers[1]){
      curPos = 7; //second timer expired then trigger
  }

```

thanks!

# Answer
For time-keeping on a long-term basis, you are going to run up against clock drift and offsets from tick-tracking. You may be better off using a real-time-clock (RTC) such as the DS1307. This and RTCs like it are often available in breakout boards with a coin-cell battery holder built in.

You would still get the time from your HTTP or NTP source, but the RTC will be much better at keeping the "right" time as you would expect a wristwatch or desk clock to do, versus using the MCU for counting milliseconds.

You can use Ticks or `millis()` to set up a periodic read of the RTC every second or every 10 seconds, etc. Avoid using the MCU clock for long-term real-world time keeping.
> 1 votes

# Answer
I describe how I do it in my project. I use the Time library a.k.a TimeLib. I set the time I retrieved not by NTP but over modbus from a device which is the source of other data in my project. In your case, you have the http request.

The input to set the time to TimeLib is UNIX epoch. Epoch are seconds from 1970-01-01. If you set only the seconds of the current day, the date would stay 1970-01-01.

And then I have for example this function

```
boolean restHours() {

  const int BEGIN_HOUR = 9;
  const int END_HOUR = 22;

  int hourNow = hour(now());

  if (hourNow >= BEGIN_HOUR && hourNow < END_HOUR) {
    if (state == RegulatorState::REST) {
      state = RegulatorState::MONITORING;
    }
    return false;
  }
  if (state == RegulatorState::MONITORING) {
    state = RegulatorState::REST;
    clearData();
  }
  return true;
}

```

`now()` returns the 'epoch' time. `hour(now())` returns the current hour.

or in other function I test if it the should be executed. it enables the execution of the rest of the function only in interval 9:00 to 10:00

```
void susCalibLoop() {

  const byte SUSCALIB_HOUR = 9;
  static boolean done = false;

  int hourNow = hour(now());

  if (hourNow != SUSCALIB_HOUR) {
    if (done) {
      done = false;
    }
    return;
  }
  if (done)
    return;
...

```
> 0 votes

---
Tags: esp8266
---


# Question
Title: How to use the 0.91' 128*32 OLED by arduino pro mini?
I buy a OLED as picture below, I want to use https://github.com/adafruit/Adafruit\_SSD1306 to control it. But the example of https://github.com/adafruit/Adafruit\_SSD1306 can't be compiled. The error as the second picture below. How should I to use this OLED ?

>

# Answer
In addition to installing the Adafruit\_SSD1306 library, you also need to install the Adafruit\_GFX library, which is a dependency of the SSD1306 library.
> 1 votes

---
Tags: arduino-pro-mini
---


title: LCD Identification FPC-JG00467-01B SR36

text:
# Question
Title: LCD Identification FPC-JG00467-01B SR36
I salvaged an old LCD from a calculator (Texas Instruments) and I want to interface it with a microcontroller (preferably an Arduino). I‘ve searched the whole internet but I simply can‘t find any information about this display and its driver. I am looking for a specialist who can identify this:

# Answer
It's most likely a custom part for which there is no public data sheet. LCDs are almost always custom-designed, and require special driver circuitry. This is especially true for such mass-produced items as calculators.

**Edit:**

There is code to screen capture using an ESP32.

https://github.com/marcrobm/TTRX\_Remote/blob/master/main/drivers/TTRX\_T30X.cpp

The Protocol is a relatively simple parallel interface with some data pins and a clock pin. To implement a Driver, one could implement the above linked code "in reverse".
> 2 votes

---
Tags: lcd, display
---