# Question
Title: Printing Serial Readings for 2+ Parallax Ping Sensors
trying print values for two sensors, one works the other is 0, any tips on how i can use more than one?

```
const int pingPin = 10;
const int pingPinz = 11;
unsigned int duration1, duration2, inches1, inches2;

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

void loop() {
  pinMode(pingPin, OUTPUT);          // Set pin to OUTPUT
  pinMode(pingPinz, OUTPUT);          // Set pin to OUTPUT
  digitalWrite(pingPin, LOW);        // Ensure pin is low
  digitalWrite(pingPinz, LOW);        // Ensure pin is low
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);       // Start ranging
  digitalWrite(pingPinz, HIGH);       // Start ranging
  delayMicroseconds(5);              //   with 5 microsecond burst
  digitalWrite(pingPin, LOW);        // End ranging
  digitalWrite(pingPinz, LOW);        // End ranging
  pinMode(pingPin, INPUT);           // Set pin to INPUT
  pinMode(pingPinz, INPUT);           // Set pin to INPUT
  duration1 = pulseIn(pingPin, HIGH); // Read echo pulse
  duration2 = pulseIn(pingPinz, HIGH); // Read echo pulse
  inches1 = duration1 / 74 ;        // Convert to inches
  inches2 = duration2 / 74 ;        // Convert to inches
  Serial.println(inches1);            // Display result
  Serial.println(inches2);            // Display result
  delay(200);                 // Short delay
}

```

# Answer
> 1 votes
Your problem is in how you are working with the two sensors. At the moment you are triggering both sensors together then waiting for the first one to echo back. Only when that has responded do you then wait for the second one to echo back, and that echo has been and gone already.

Imagine you have two tennis balls. You throw them both at different walls at the same time, then attempt to catch them both. While you are catching the first ball the second one bounces off the back of your head and rolls under the table. That's what's happening with your echos.

So instead you need to treat both sensors completely separately. Trigger the first, then get the response. Then trigger the second and get the response.

---
Tags: sensors
---


# Question
Title: Recover from wrong Wi-Fi password on Arduino Yún
I'm trying to customize my Arduino Yún to work as an access-point (or hotspot) for providing services to clients directly connected and, alternatively, to work as a client on a wireless network for downloading resources from the Internet.

The access to such a wireless network is gained after the user submits a network SSID and password in the web control panel provided by Yún.

How can I recover from a user submitting a wrong password? At the moment the Yún stays stuck without any connection, and thus is unreachable via SSH to attempt any recover.

# Answer
At the end I came out with a button connected to one of the digital input pins and a sketch that, using the bridge to communicate with the "Linux part" of Yún, restores original values in the configuration files and reboots the whole controller.

After the reboot completes the Arduino Yún is accessible again through the Wi-Fi network "Arduino Yun xxxxxxxxxx".
> 0 votes

# Answer
The simplest option is to provide a serial console interface which will either give full access to the OS (pipe through *Console*) or a menu driven interface that sends instructions to the main chip (through *Bridge*).

The user would then connect to the USB interface and use a terminal program to access the configuration in whatever way you have chosen. This could either be via options within your installed sketch, or by uploading a special sketch through the USB connection.
> 0 votes

---
Tags: wifi, arduino-yun, wireless
---


# Question
Title: How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?
How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.

> avrdude: usbdev\_open(): did not find any USB device "usb"

I've already added myself to the `dialout` group,

> sudo usermod -aG dialout $USER

And, I did that after I confirmed the `dialout` group owns the device (in my case `/dev/ttyACM0`:

```
$ ls /dev/ttyACM0 -l
crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0

```

# Answer
This is because in the IDE I was using

* Sketch → **Upload Using Programmer \[`Ctrl` \+ `Shift` \+ U\]**

However, I should have been using

* Sketch → **Upload \[`Ctrl` \+ U\]**
> 0 votes

# Answer
Try "Tools\> Port:\> then select your board" Make sure your pc hasn't assigned new com port to the attached usb (Arduino)
> 0 votes

---
Tags: arduino-ide
---


title: What does the bootloader do?

text:
# Question
Title: What does the bootloader do?
As far as I understand it checks for a valid serial connection (new program incoming) and then either writes it to flash or starts executing the existing program.

Can't the 32u4 or EDBG fill the role of an ISP and program the MCU instead of the MCU self-programming? I know the EDBG is accessed via OpenOCD to write the bootloader to the SAMD21 on Arduino Zero boards so why is the bootloader even required?

# Answer
The bootloader is there for convenience.

Yes, you understand what the bootloader does and how it operates. However, you have missed out one benefit, and that is evident when you're *not* using the bootloader. That is, when you're not using the bootloader the *same* connection can be used for a serial connection to the PC. If the 32U4 were directly programming the main MCU then it would be talking to the SPI pins not the UART pins, so you would need a second connection, or both a connection to the UART *and* the SPI pins, and much more complex firmware on the 32U4, in order to get a serial connection to the PC.

So the simplest option is just to have a dumb pass-through interface from the USB to the UART pins and have the main MCU self program with a bootloader.

It also means that you don't need any special programming hardware when making your own board - just something (another arduino maybe) to get the bootloader on there in the first place (or buy the MCU pre-programmed) and then use any TTL serial interface to program it with your main program.
> 2 votes

---
Tags: bootloader, atmega32u4
---


# Question
Title: What alternatives are there to the Optiboot bootloader?
Nearly all modern Arduino boards use the Optiboot bootloader. Compared to the ATmegaboot used before, this is smaller in flash terms (by about 1.5KB) and faster in upload speed (115.2k vs 57.6k) and starts your sketch quicker (the delay whilst waiting after reset is shorter).

Are there any alternatives to the Optiboot bootloader? Specifically, are there any smaller (in flash terms) boot loaders? What differences do they have?

# Answer
> 10 votes
Optiboot is about the smallest bootloader available.

But, there is a much more powerful (with inbuilt console for hardware testing, RAM and Flash contents checking, etc) bootloader with a more developed and robust stk500v2 communications protocol between avrdude and the AVR bootloader.

I've used it on the ATmega2560 and on the ATmega1284p. It works for both 3 byte and 2 byte program counter MCU.

I have a STK500v2 Bootloader version on Sourceforge.

This bootloader is based the Peter Fleury STK500v2 bootloader, updated by Mark Sproul. I've made edits to have it supporting with the Goldilocks (an ATmega1284p) board.

The key feature is to use the **STK500v2** protocol for uploading the Flash image to the Arduino. This protocol is more robust and gives better error capabilities than the **avr109** protocol. As an aside the avr109 protocol is called "Arduino" in the Arduino world, because it toggles DTR (to reset the board and automatically enter the bootloader), and the STK500v2 protocol is called "Wiring" in the Arduino world, because of the same reason.

The Fleury/Sproul STK500v2 bootloader is designed to work with the ATmega2560 which has a 3 byte program register, because of the larger Flash size. But, it also supports normal 2 byte boards (everything else really).

For boards with plenty of Flash (like Goldilocks 1284p), there is a **hardware monitor** that can be used to query Flash, SRAM and hardware; you can check connections without additional code, and check the actual contents of Flash and EEPROM. Because the 1284p supports 2 USART, I added the ability to have debugging on **USART1**, so that the upload process via **USART0** isn't disturbed.

# Answer
> 3 votes
TinySafeBoot is an alternative for ATtiny and ATmega devices.

* Compatible to plenty of ATtinys and ATmegas (see below)
* Read/Write access to Flash and EEPROM.
* All IOs available for serial communication
* One-wire, also with multiple AVRs on a single line
* Autobauding, rugged protocol.
* Activated by Reset + Password (optional)
* Password and Timeout user changeable anytime.
* "Emergency Erase" to overcome lost Password - kills all data but leaves bootloader intact.
* ATtinys: ~ 550 bytes,
* ATmegas: \< 512 bytes (!)
* TSB for ATtiny can update itself.
* The Sourcecode is free Software (GPL)

# Answer
> 1 votes
> Are there any alternatives to the Optiboot bootloader?

Err... not really. There's actually **a \[unofficial\] modification to Optiboot to make it faster when uploading.**

> To install the high baud rate variations…
>
> * Ensure the Arduino IDE is not running
> * Download the 7-Zip archive using the link above
> * Extract the three files to the following directory: `{Arduino Installation Root}\hardware\arduino\bootloaders\optiboot\`
> * Open the boards.txt file located in the following directory: `{Arduino Installation Root}\hardware\arduino\`
>
> Find This section inside it:
>
> ```
> uno.name=Arduino Uno
> uno.upload.protocol=arduino
> uno.upload.maximum_size=32256
> uno.upload.speed=115200
> uno.bootloader.low_fuses=0xff
> uno.bootloader.high_fuses=0xde
> uno.bootloader.extended_fuses=0x05
> uno.bootloader.path=optiboot
> uno.bootloader.file=optiboot_atmega328.hex
> uno.bootloader.unlock_bits=0x3F
> uno.bootloader.lock_bits=0x0F
> uno.build.mcu=atmega328p
> uno.build.f_cpu=16000000L
> uno.build.core=arduino
> uno.build.variant=standard
>
> ```
>
> Add the following section…
>
> ```
> uno_uf.name=Arduino Uno / Upload Fast
> uno_uf.upload.protocol=arduino
> uno_uf.upload.maximum_size=32256
> uno_uf.upload.speed=250000
> uno_uf.bootloader.low_fuses=0xff
> uno_uf.bootloader.high_fuses=0xde
> uno_uf.bootloader.extended_fuses=0x05
> uno_uf.bootloader.path=optiboot
> uno_uf.bootloader.file=optiboot_atmega328_250000.hex
> uno_uf.bootloader.unlock_bits=0x3F
> uno_uf.bootloader.lock_bits=0x0F
> uno_uf.build.mcu=atmega328p
> uno_uf.build.f_cpu=16000000L
> uno_uf.build.core=arduino
> uno_uf.build.variant=standard
>
> ```
> * Change the two highlighted values to the baud rate you plan to use: 250000, 500000, or 1000000 Save and close the boards.txt file
> * Using your favourite ISP programmer, install the new bootloader. *Don’t forget to: Ensure the Arduino Uno / Upload Fast board is selected (Tools / Board)*, *If appropriate, ensure the Serial Port of your programmer is selected (Tools / Serial Port)*, *Ensure the programmer is selected (Tools / Programmer)*, *After installing the bootloader, change the Serial Port to the serial port of your Arduino Uno*.

Above text slightly modified for compatibility with site. *Original post*

---

Besides that, and the ATmegaboot bootloader, you can't really find any alternative. I would imagine that if Arduino loads it on all the Unos ever produced, it's pretty optimized. The above hack speeds up upload time, but it doesn't reduce the size of the bootloader. You can also remove the wait time on the bootloader so it has a faster startup.

If you're that concerned about maximising flash see: *How to really shrink a sketch* and this answer \[on on *What can I do if I run out of Flash memory or SRAM?*\].

---
Tags: bootloader
---


# Question
Title: Are INTx pins the only ones eligible for Software Serial?
As opposed to PCINT (Atmel's Pin Change INTerrupt, INTx is arduino-compatible interupt) In other words, does Software Serial use atmel's pin change or arduino falling interrupt?

# Answer
`SoftwareSerial` uses PCINT. `AltSoftSerial` uses INT0 or INT1, which has FALLING, RISING, CHANGE or LOW LEVEL options. See Section 12.2, p. 71 of the Atmel ATmega328 spec, for example.
> 1 votes

---
Tags: interrupt, softwareserial
---


title: Message received with 1 character less

text:
# Question
Title: Message received with 1 character less
I have the following situation:

One Arduino Uno with a 433mhz transmitter wired to the laptop to have serial communication. Another Arduino Uno with a 9V battery wired with a 433mhz receiver and an LCD screen (16x2, I2C).

I have the following code to transmit:

```
#include <VirtualWire.h>

void setup() {
  //Force low when enabled
  vw_set_ptt_inverted(true);
  //Set pin 12 for transmitter
  vw_set_tx_pin(12);
  //Setup with speed of the data transfer.
  vw_setup(4000);
  //Set serial communication at 9600 baud
  Serial.begin(9600);//set Serial
  //Set pin 13 to light up when transmitting
  pinMode(13,OUTPUT);
}

void loop() {
  //If message send via serial monitor
  if (Serial.available()) {
    //wait a bit for the entire message to arrive
    delay(100);

    while (Serial.available() > 0) {
      //Read serial into string
      String message = Serial.readString();
      //Initialize char array
      char msg[message.length()];
      //Write string to char array
      message.toCharArray(msg, message.length());
      //send char array as unsigned int (bits)
      vw_send((uint8_t *)msg, strlen(msg));
      //Wait until the complete message has been send
      vw_wait_tx();
      //Turn on light when finished
      digitalWrite(13,HIGH);
      delay(200);
    }
  }else{
    //Turn off light
    digitalWrite(13, LOW);
  }
}

```

And the following code to receive a message and print on a LCD screen:

```
#include <LiquidCrystal_I2C.h>
#include <VirtualWire.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup() {
  //start up LCD with 16 chars with 2 lines
  lcd.begin(16,2);
  //Turn on backlight
  lcd.backlight();
  //Write initialising message
  lcd.setCursor(0,0);
  lcd.print("Initialisation..");
  //Force low when enabled
  vw_set_ptt_inverted(true);
  //Set pin 12 to receive
  vw_set_rx_pin(12);
  //Setup with speed of the data transfer.
  vw_setup(4000);
  //set pin 13 for light
  pinMode(13, OUTPUT);
  //Start receiver
  vw_rx_start();

  //Set message on LCD that setup has completed
  lcd.setCursor(0,1);
  lcd.print("Completed!");
}

void loop() {
  //initialize array for message
  uint8_t msg[VW_MAX_MESSAGE_LEN];
  uint8_t msgLength = VW_MAX_MESSAGE_LEN;

  //If message received
  if (vw_get_message(msg, &msgLength)){
    //Turn on light
    digitalWrite(13, HIGH);

    //Print on lcd
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.write(msg, msgLength);
  }else{
    //Else turn of light
    digitalWrite(13, LOW);
  }
}

```

My problem is that the message that is being transmitted and received by the other arduino always is short 1 character. For example if I send "test", it receives and displays "tes". What am I missing?

(My short solution was to just add a space to the message, then the space got cut off. But I want to understand what is going wrong.)

# Answer
> 2 votes
I haven't found the source of the problem by reading through the code, and will limit my comments to advice about debugging the problem.

With the code as it stands, there are half a dozen points where the missing character might have dropped out. With just a final result, the problem location is difficult to narrow down. Modify your code to display intermediate data.

For example, in the sending code, print the read-in string and its length to Serial. Eg, if you `#include <Streaming.h>` you can say:

`Serial << message << ' ' << message.length() << endl;` `Serial << msg << ' ' << strlen(msg) << endl;`

and so forth.

\[Note, `msg` actually occupies strlen(msg)+1 bytes, the last byte being a null-byte terminator, which your code doesn't send or receive.\]

In the receiving code, besides the `lcd.write` of `msg`, do an `lcd.print` with `msgLength`.

You can also do some code clean-up in the sender. Remove the line

`while (Serial.available() > 0) {`, and its corresponding `}`, because `Serial.readString()` already contains a character-wait loop with timeout.

---
Tags: arduino-uno, lcd, wireless
---


# Question
Title: Arduino Uno and Raspberry Pi USB Serial Communication
I am trying to get Arduino Uno with Raspberry Pi to communicate with each other. I want the python script to write a message and for my Arduino to read it. This was working before, but I came back a week later and it stopped. Essentially, I want the Raspberry Pi to write '3' and for my Arduino to recognize this 3 and light up some LEDs. Where do you think I am going wrong? The Arduino works when testing it through the IDE and Serial Monitor. There are no errors when running the python script, the LEDS just don't light up, so I assume there is some miscommunication.

Python Code

```
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write('3')

```

Arduino Code

```
String serialRead;
int val;
void setup() {
  Serial.begin(9600);
  strip.begin();
  strip.setBrightness(25);
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  serialRead = Serial.read();
  if (Serial.available() > 0) {
    val = Serial.read();

    if (val > '0' && val <= '9') {
      Serial.println(val);
      val = val - '0';
      Serial.println(val);

      if (val == 3)
      {
        //strip.setBrightness(100);
        colorWipe(strip.Color(127, 127, 127), 50);
        colorWipe(strip.Color(0, 0, 0), 50);
      }
    }
  }
}

```

# Answer
> 4 votes
Just at a glance:

Your loop consumes the byte and stores it in `serialRead`, so there is probably no available data at the outer `if`, so it is never entered.

Try deleting this line:

```
serialRead = Serial.read();

```

---
Tags: arduino-uno
---


# Question
Title: Olimexino 32u4: Wire.endTransmission() hangs
I'm trying to get a TAE5767 (FM radio) to work. According to this instructable I'm trying it on a 5V-Olimexino 32u4 (Leonardo-compatible) with following code (Arduino 1.6.3):

```
#include <Wire.h>

void setFrequency(float frequency) {
  unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  byte frequencyH = frequencyB >> 8;
  byte frequencyL = frequencyB & 0xFF;
  Wire.beginTransmission(0x60);

  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write(0x00);
  Serial.println("sending");
  Wire.endTransmission();
  Serial.println("sent");
}

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

  Wire.begin();
  setFrequency(89);
}

void loop() {
}

```

Unfortunately, it only prints

```
sending

```

First, I thought I'd damaged my chip, but I'm now using the second with the same result. I've also tried the I2C-Scanner from Nick Gammon, but it prints nothing. I've tried adding 2.2k resistors from SCL and SDA to 5V without success. Does someone has a clue what I can try?

# Answer
> 1 votes
I've did not got it working with `Wire`. Hence I've implemented a I2C protocol myself using bit-banging and then it works.

**Update from 2017-September-16**

The problem was not `Wire.h` but a specialty of the Olimexino 32u4 board. I've only found out by using a Real Time Clock connected to the UEXT port's I2C bus, that I have to switch on the power for the UEXT port by setting D8 to LOW. Otherwise SDA or SCL seem to be pulled down preventing any I2C communication.

---
Tags: i2c, wire-library
---


title: Blink question with breadboard & LED

text:
# Question
Title: Blink question with breadboard & LED
I tried a basic Blink example and I found a strange case where :

Works

Does not work

Can someone explain me what is happening ?

# Answer
> 3 votes
It is because the rail in the middle breaks the vertical connections. So the positive leg in the first example is not connected to the negative leg of the LED.

In your second example both the negative leg and the positive leg are connected on the same rail, because of the that the power is not flowing through the LED but directly back to the GND pin of your arduino.

Same for the resistor. Since both legs are connected to the same rail, the resistor has no effect.

---
Tags: led, arduino-nano
---


title: MQ135 output on Arduino Uno

text:
# Question
Title: MQ135 output on Arduino Uno
I bought an FC-22 (MQ135) gas sensor module which I plugged into my Arduino Uno. I connected it to the A0 analog port. Then created a code that reads the raw data from A0 (code below).

When I run the code on my Arduino Uno in my house I get values of about 30. If I blow over the sensor I get values until about 160. My question is now how I have to read / interpret these values.

According to the MQ135 specifications the sensor has a sesitivity for air quality, measuring benzene, alcohol and smoke.

How can I interpret the values I get? What is a good value and what isn't? Do I have to calculate something out of these values?

My code looks like this:

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

void loop() {
  int sensorValue = analogRead(0);
  Serial.print(sensorValue, DEC);
  delay(100);
  if (sensorValue > 50) {
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
}

```

# Answer
> 2 votes
According to the datasheet you have to calibrate it.

---
Tags: arduino-uno, analogread
---


title: How to convert frequency into db

text:
# Question
Title: How to convert frequency into db
I have made an Arduino circuit which outputs in terms of frequency(hz) and I need output in terms of db as well

So is there any formula which can I apply to convert frequency hertz to db or is there any reference link to understand the conversion process.

Any help will be highly appreciated

# Answer
> 2 votes
dB is volume (sound pressure), frequency is pitch. The two are entirely different concepts and can't be converted. A bit like you can't convert the roundness of a doughnut into blue. Roundness and blueness (it has blueberries in it by the way) are two different properties of the doughnut.

# Answer
> 2 votes
dB it self just express in a logarithmic scale a ratio between two values and it self is unit independent (because is a ratio). Just because the most common uses of dB scales are linked to intensity or power doesn't necessarily mean that can't be used to represent other ratios of different types of quantities. Or at least I couldn't find any definition that restricts the use of dB in such cases. The formulas to express such ratio are present here you just have to figured it out what is really your ratio.

So, for example, if you have some kind of sensor that somehow the output is a frequency, let's say something like

```
f(x) = ax + f0  [Hz]

```

There is no reason why you can't express this function in a logarithmic ratio scale using dB something like, related to f0 or f(x=0)

```
L(x) = 10*Log10*(f(x)/f0) [dB]

```

which would give you the represented dB output of your equation with respect to x.

**But** since we are in arduino stackexchange and talking about sensor, the common use of dB in electronics is the representation of power ratio or (the more common) a frequency response of a circuit(or system) that is represented by a Bode Plot, so I advise you to really take a good look at both links and try to figure what you really are asked to represent.

# Answer
> 0 votes
Decibels (Db) are calculated using amplitudes and by definition decibels are the measurement of sound intensity or power level of electrical signal by comparing it with a given level on a logarithmic scale, which is **independent of frequency**.

You can measure the decibels though if you know the amplitude of your source which i'm guessing is ~5v .

---
Tags: arduino-uno, frequency
---


title: The 3.3 volts of the USB To TTL

text:
# Question
Title: The 3.3 volts of the USB To TTL
I'm using ESP with USB to serial converter (D-SUN) is it possible to use the 3.3 volts of the USB instead of the Arduino Uno?

# Answer
I don't know what that adapter is (a link would be nice, or at least the chip number it uses) but in general the 3.3v on a USB TTL adapter can only provide a small current. For instance the FT232RL can only provide up to 50mA at 3.3v. That may not be enough current to drive the RF circuitry of the ESP. The early Arduinos used the FT232RL chip for the USB interface and it was the 3.3v from that which was used for the 3.3v header on the Arduino. This was somewhat of a failing with those Arduinos since the 50mA limit was a real problem when people started using more 3.3v devices. That was one of the driving forces (as well as cost) in the decision to switch to an MCU for the USB interface.

So to be on the safe side I wouldn't use the 3.3v from the USB adapter to power the ESP. You are better using a 5v to 3.3v regulator circuit driven from the 5v of the USB. And yes, that could be a whole Arduino, or build your own on some stripboard.
> 3 votes

# Answer
From my experience using the USB to TTL adapter will not work very well. I got some code on my ESP somehow, but could not get it working reliable. So I ended up powering it from an additional source.
> 1 votes

---
Tags: arduino-uno, serial, esp8266, voltage-protection
---


title: Arduino IDE fails without sudo

text:
# Question
Title: Arduino IDE fails without sudo
I use Arduino IDE 1.6.6 on Ubuntu 15.10.

Starting the Arduino IDE without using `sudo` fails for both:

* uploading the code to the Arduino Uno
* starting the serial monitor

The group I need to add my user to is called `dialout`:

```
myuser@mycomputer:~$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Dez 12 17:57 /dev/ttyACM0

```

So I added `myuser` to `dialout`:

```
sudo usermod -a -G dialout myuser

```

Somewhere I read that I have to add `myuser` to `tty` as well, so I did it:

```
sudo usermod -a -G tty myuser

```

Though I still fail with the above mentioned when trying to use the IDE with `myuser`.

What do I have to do to get the IDE working with `myuser`?

# Answer
There should be a command like 'id' or something similar that will show the groups you are a member of. Run that to check that the new groups have taken effect – you may need to log out and then log back in.

The other thing to check is the group owner of the device itself (in /dev). that will also need to match the group you assigned to yourself. Also make sure that the device permissions allow group access.
> 2 votes

---
Tags: arduino-uno, arduino-ide, ubuntu
---


title: Extra characters remain in Serial

text:
# Question
Title: Extra characters remain in Serial
I have spent the whole day trying to deal with this problem connecting Arduinos together using UART (Serial). But the problem is that it always behaves weirdly. For now the problem is that if previous number (I am sending numbers over serial) stays in the serial port.

Let me describe the problem. I want to send the following sequence of numbers 16 4 100. Numbers are sent with a terminator char after each number, but on the receiver side I get the following result 16 46 100.

As you can see if the previous number is longer (length, has more digits) than the current one, like 16 and 4, 132 and 34, the difference (number of digits) remains in the next result: for 16 and 4 it will be 16 and 46, for 132 and 34 it will be 132 and 342.

I have tried different ways to solve this problem, but unfortunately I cannot find the solution.

Here are my functions used for communication:

```
void sendCommandToSerial(int command) {
  Serial3.print(command);
  Serial3.print(TERMINATOR_CHAR);
  Serial3.flush();
}

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

int readRawBytes(char *inputBuffer,const int bufferSize) {
  return Serial3.readBytesUntil(TERMINATOR_CHAR, inputBuffer, bufferSize);
}
int readIntFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atoi(inputBuffer);
  }
  return -1;
}
int readFloatFromSerial() {
  if(readRawBytes(inputBuffer,DEFAULT_BUFFER_SIZE) > 0) {
    return atof(inputBuffer);
  }
  return -1;
}

```

I have tried both software and hardware serials, still the same. Please help to find and solve the problem.

# Answer
> 3 votes
The Stream member function readBytesUntil() does not null terminate the string. It returns the number of characters read. You must terminate the string with null(0) before calling atoi() and atof() or fill the string will null(0) before calling readBytesUntil().

For more details see Arduino Stream.cpp.

Cheers!

---
Tags: serial, arduino-ide, softwareserial
---


title: Displaying binary to LEDs

text:
# Question
Title: Displaying binary to LEDs
I've written a program for Arduino UNO and 3 LED lights. The program is supposed to turn an inputted number into binary and then display it on the LEDs, on being 1 and off being 0 I have looked it over quite a few times and don't understand why it is not working as it should. I'm a beginner at working with Arduino so I probably just need a more experienced eye to show me where I have messed up. I have a link to a picture of the Arduino setup below. Thanks! https://drive.google.com/file/d/0B8k\_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing

```
//setting up lights
const int lightOne = 13;
const int lightTwo = 12;
const int lightThree = 11;

//array of the lights for when printing the binary
int lights[] = {lightOne, lightTwo, lightThree};

void setup() {
  //setting pin modes and starting up the serial monitor
  pinMode(lightOne, OUTPUT);
  pinMode(lightTwo, OUTPUT);
  pinMode(lightThree, OUTPUT);
  Serial.begin(9600);
}

//converts a given number into binary
String binary(int number) {
  String r;
  while(number!=0) {
    r = (number % 2 == 0 ? "0" : "1")+r;
    number /= 2;
  }
  return r;
}

//outputs the binary string to the lights (not expecting numbers larger than     9)
void printBinary(String binaryNumber) {
  for (int i = 0; i < sizeof(binaryNumber); i++) {
    digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));
    delay(2000);
  }
}

void loop() {
  int input = Serial.read();                //get the number
  String binaryNumber = binary(input);      //convert number to binary
  Serial.println(binaryNumber);             //print binary to serial monitor
  printBinary(binaryNumber);                //display number in binary on     LEDs

}

```

# Answer
> 2 votes
# Welcome to SE Arduino!

## Long Version

You have a couple of things to look at:

1. Don't use `String` class it has too much overhead for Arduino.
2. Your conversion function is not really necessary because you can convert it on your `Serial.println()` by specifying `binary` as output. eg: `Serial.println(number, BIN)`;
3. The `Serial.read` returns an integer, but that `int` only contains a `byte` (unsigned) value anyway (unless there's nothing to be read, in which case it returns `-1`). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use `int` or `byte` (unsigned: `0 <-> 255`) or `char` (signed: `-127 <-> +128`).
4. You could/should/doesn't matter if you use `Serial.available()` or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that `-1` as what you're doing at the moment is taking that and converting it to binary (which is `0xFF` which is everything on). **This is one of your major problems in the code** (the other is in the **Short Version** section.
5. You're using `"0"` and `"1"` which are `ASCII` values, and you haven't indicated how you're getting the number. So it may be `ASCII` (`byte`) or actually a `byte` value. ie, `"0"` is `48 (dec)` or `30 (hex)`. Whereas a `0` is just `zero`. Funnily enough, because you're using modulo (`%`) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: `1` (`0b00000001`) is the same as `"1" = 49 (dec) = 0x31 = 0b00110001` when used with `%2`.
6. Ditch your `delay(2000)`. Delays are evil\* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your `Serial.println()` once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes
7. The big one is in the next section

## Short Version

This is your *main* problem, on this line:

```
digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));

```

I think you need:

```
digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH));

```

You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)

*** Delays are evil**: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/

# Answer
> 1 votes
You need to check that there are characters available before reading. Please see documentation of Serial.read() (and Serial.available()).

Cheers!

---
Tags: arduino-uno, c++, led
---


title: Rotating a motor with L293D

text:
# Question
Title: Rotating a motor with L293D
I'm following this tutorial to control a DC motor with an Arduino.

I have the same problem as this stackexchange post arduino.stackexchange.com/questions/10049/problems-with-l293d where the motor is not rotating.

* The chip is heading to the right. (5v pins are on the right)
* Connecting directly the motor to the battery works.
* Current (5V on the bottom & 2\*1.5V) is flowing everywhere expected EXCEPT on the yellow & green wires of the motor (the red wire of the battery pack is connected to the second line of the breadboard).
* Connecting directly the motor to the battery works.
* I copied the code of the above tutorial which is basically : "digitalWrite(4,HIGH);", there is current on the cable.

Am I wrong into thinking that a L293D chip can output sufficient current ? Is the chip malfunctioning ?

# Answer
> 1 votes
Your picture shows a holder for two AA cells, yielding something in the neighbourhood of 3v. That is far too little for an L293D. (This isn't really your fault, as it appears you got this erroneous idea from following a bad tutorial, but it does demonstrate that not everything you read on the Internet is sensible. Using a 9v "transistor" battery is also a bad idea). 3 cells would be about the minimum, but even there it would not work well, as that chip has two bipolar transistors in the path yielding a voltage drop of over a volt.

To use a an L293D you really want at least a 5 or 6 volt system, and a motor wound for low to moderate current at that voltage.

If you want to use a lower voltage, look at a more modern MOS-based H bridge chip - the TB6612FNG is an often used example. You will however still want to choose motors wound for moderate current at a 3- or 4- cell voltage - those intended for 2-cell usage typically draw more current than is ideal for an IC driver chip.

It is entirely possible that there are additional issues with your attempt as well. Normally, a question such as this would require a complete and accurate schematic diagram, which you have not provided.

---
Tags: arduino-nano
---


# Question
Title: How to learn electronics/programming with Arduino?
I want to learn core and mechanics of microcontrollers with Arduino, and I don't really know where to find good source of knowledge.

Every Arduino related tutorial is about very basic stuff like connecting the LCD display without explaining what every pin does. When it comes to programming tutorials only explain what functions are needed and do not explain what happens inside the hardware.

For example i know what delay() function does, and I know that I can find definition in the source files:

```
void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

```

But what I really want to know what that code does, and how to write own functions. I would appreciate if you could provide me with any starting point. Should I just follow the source files until I get it or is there any better reference?

I have Arduino Leonardo, and experience in programming in C/C++.

# Answer
> 1 votes
For information about the “core and mechanics of microcontrollers with Arduino”, there are numerous articles with lots of details on the arduino.cc forum. However, most of the code posted there sucks, as does most of the code posted here on Arduino Stackexchange. That's a natural consequence of people posting code that doesn't work and they wonder why.

For a reasonably organized and accurate body of information about Arduino hardware and software, see Nick Gammon's Arduino pages. Also see arduino.land pages. For better understanding of Arduino software internals, see garretlab's “Internal Structure of Arduino Software” pages, which are well organized and quite informative about the subjects they cover.

Regarding the specific `delay()` code shown in the question, first consider this slightly simpler version, from Arduino 1.6.3:

```
void delay(unsigned long ms) {
    uint16_t start = (uint16_t)micros();
    while (ms > 0) {
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

```

Ignoring data type constraints, it's evident that the `while` loop counts down `ms` from its original value to zero. The burden of the `if` executes about once per millisecond, because `start` advances 1000 microseconds each time within the `if`.

The casts of `micros()` – ie, where `uint16_t` appears in parentheses before `micros()` – tell the compiler to throw away the upper two bytes of `micros()` \[which is actually an unsigned long, or `uint32_t`\] and treat it as an unsigned 16-bit integer. The low two bytes of `micros()` overflow every 65536 microseconds, on which occasions within a millisecond it will come to pass that although `(uint16_t)micros()` is less than `start`, due to use of unsigned arithmetic `((uint16_t)micros() - start) >= 1000`.

The code you included has one more statement in the `while` loop:

```
    yield();

```

For most models of Arduino, `yield()` is an empty function, a do-nothing if compiled at all. On the Due, with `Scheduler.h` in use to support cooperative (non-preemptive) multitasking using multiple stacks, `yield()` gives the scheduler an opportunity to schedule another task, if one is ready to run. Note that if a “cooperative” but malignant task always takes just under 65536 microseconds to do its work, it can happen that `delay()` as shown never returns.

# Answer
> 2 votes
There are two main topics there: Digital Electronics, and C++ programming, and the Arduino happens to bridge the gap between the two.

That's why it's hard to find tutorials in the style you want. So instead of looking for Arduino tutorials that do what you want you need to split the topics apart and deal with them separately.

Search for C++ programming tutorials. That should help you understand the structure and syntax of a program better. Search for digital electronics tutorials. Good keywords are things like *logic gates*, *combinational logic* or *digital interfacing* and just *digital electronics*. That should help you understand things like logic levels, logical functions, inputs and outputs, and such like.

Once you have basic understanding in both fields you can begin to see how the two relate together. One of the most important skills any engineer has is understanding and interpreting datasheets. From datasheets you can find how the hardware operates and what you would need your program to do to make the hardware do what you want.

---
Tags: programming, c++, arduino-leonardo
---


# Question
Title: GSM GPRS module not getting any output from Rx , Tx
I am using a SIM800 GSM/GPRS module. I connected it using 4 wires: Vcc 3.7 volt (2 amp supply), RX and TX and GND. Whenever I try to send a command it shows me nothing. Here is my code.

```
//Serial Relay - Arduino will patch a
//serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1
//Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);

unsigned char buffer[64];  // buffer array for data receive over serial port
int count=0;               // counter for buffer array

void setup() {
  GPRS.begin(19200);
  Serial.begin(19200);
}

void loop() {
  if (GPRS.available()) {
    while(GPRS.available()) {
      buffer[count++]=GPRS.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);
    clearBufferArray();
    count = 0;
  }
  if (Serial.available())
    GPRS.write(Serial.read());
}

void clearBufferArray() {
  for (int i=0; i<count;i++) {
    buffer[i]=NULL;
  }
}

```

It is an independent module. I've already read the hardware manual and AT command manual. I did everything according to the manual.

# Answer
> 1 votes
Are you sure the baud rate is correct? You could try 115200 and 57600. Is the serial monitor set to "Carriage Return" or "Both NL & CR"? If this isnt set, the modem won't respond to your commands since it requires a '\r' to terminate every command. Is there any indication that the modem is powered (like the net LED blinking)? Your code looks alright but, to be sure everything's okay, use this test program to interact with the modem using the serial monitor; just change your loop() to this:

```
    void loop(){
        while (Serial.available())
            GPRS.write(Serial.read());
        while (GPRS.available())
            Serial.write(GPRS.read());
    }

```

This way, everything you type in the monitor will be relayed to the modem and everything from the modem will be relayed to the PC, all via the arduino.

# Answer
> 0 votes
There doesn't seem to be anything wrong with your code. I'm going to assume you have got the right VCC and the right Serial speed.

Do you have a way of connecting the device directly to your PC and then using a terminal emulator to see if the device is talking?

Is there a library that you could use? Maybe there is some setting that you need that isn't documented.

---
Tags: gsm, softwareserial, uart
---


# Question
Title: Modify SSID and Passwords in WiFi sktechs
This is a question about modifying sketches other than through the IDE.

I'm using an Arduino Uno r3 + Arduino WiFi Shield (not the 101). Up to now I've been using the IDE to manually change the ssids and passwords to connect to wireless networks. As a next step, I'd like to create something that will let update the ssid and password from a source other than an IDE, preferably a batch or bash file. Over the air updates are out of the question (way too advanced) so it is safe to assume that all updates will be done via the USB cable. Based on my limited knowledge of what I *think* needs to happen, I need to solve the following high-level problems:

1. Get the computer to recognize that a gateway is plugged into a USB port
2. Prompt the user to enter the new ssid and network password
3. Write to the ssid and password fields
4. Compile the code and save it (equivalent compile/upload in the IDE)
5. Run the sketch to find and connect to the network

I'd like this to look like two blank fields and a "submit" button to the user.

My imaginary use case is that I'm installing a clone of my gateway/sensor network at a technically-illiterate grandparent's house. I have no idea where to begin or even if such a thing is possible!
Assuming that it is possible, how can I make it easy for them to configure the gateway for use on their home network without resorting to the IDE?

# Answer
> 1 votes
Yes, this is possible. However, you need to have some programming skills (Java, C, C++, anything really that can cope with serial comms) to write the computer-side program.

Forget 'automatic' running of a program without installing a service on the target computer to constantly monitor incoming serial comms. That said, there's nothing to stop you doing that but to me it's an unnecessary extra step. If the End User can handle connecting the Arduino to the computer without having a breakdown, then they can probably cope with launching the input program themselves.

Hence, write a program for the target computer that analyses COM ports for active connections. For each connection, listen for some kind of identification sequence. Perform a basic 'handshake' to verify that it's found the Arduino. Once it has, allow the User to enter the WiFi details, which are then passed on to the Arduino via serial. If you're feeling *slightly* adventurous (the necessary code is provided with the Arduino IDE as an Example, so it's no real challenge) you could have the Arduino scan for networks and offer the User a list to choose from.

On the Arduino, include within the sketch a method of opening serial comms with the target computer. This can be either:

* **Within `loop()`**, at regular intervals, which becomes redundant after you've performed the setup correctly; or
* **A one-time affair within `setup()`**. Each time the Arduino is powered on it attempts to establish comms with the computer, but times out after 30 seconds of 'silence', thus the User has to launch the program on the computer within a reasonable time.

Whichever approach you choose, the code in the sketch follows a similar essence - send a unique message to whatever is listening (if anything at all!) and wait for a specific response. If the computer is connected and the program is running, it should answer. Provided the answer received by the Arduino is expected (thus 'handshake' mentioned earlier), it should then wait for the SSID/pass to be entered by the User and sent by the computer. From there, connecting the Arduino to the network is a trivial process.

# Answer
> 1 votes
You could also make use of the Arduino serialEvent() function. Behind the scenes, every time the loop() function returns, this function (if you define it) is automatically run by the Arduino if the Serial buffer contains data. So all you have to do is define the serialEvent() function and have it read from the serial port and compare what it gets against some pre-defined handshake value. If the read data is a valid handshake, the Arduino should respond with a unique value too and then await the SSID, password and other stuff you wish to set. This means your can run your PC program anytime and simply have it send the handshake and wait for the Arduino's response before sending the wifi details. You can use serialEvent() like this:

```
    void serialEvent(){
        if (Serial.read() == 'Z'){ //if 'Z' is your handshake value
            Serial.write('X');   // if 'X' is the response expected by the PC
            getWifiDetails();   // the handler that gets the needed data
        }
        while (Serial.read() != -1);  // flush to get rid of any garbage
    }

```

The handshake value could be more than 1 byte to increase chances of uniqueness. This method assumes you aren't doing anything else with the serial port, since that could bring garbage to the forefront of Serial.read() calls and cause false triggering of serialEvent() and its IF condition. You could implement a timeout in your handler to handle such events though.

---
Tags: arduino-uno, wifi, shields, sketch
---


title: ATTINYx5 usi for uart?

text:
# Question
Title: ATTINYx5 usi for uart?
Can the ATTINYx5 use its universal serial interface for a better UART than the Sofware Serial library alone? If so, is there a library or tutorial for this?

# Answer
> 1 votes
AVR307 describes implementation of a half duplex UART implementation using the USI. Note that full duplex is not possible due to the synchronous design of the USI.

---
Tags: softwareserial, attiny, uart
---


title: Read serial data from XV11 sensor

text:
# Question
Title: Read serial data from XV11 sensor
I am trying to read data from an XV-11 sensor using the description of the format found here https://xv11hacking.wikispaces.com/LIDAR+Sensor. This is the code I am currently using to communicate with the computer by USB and the sensor with software serial on an arduino uno.

```
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  mySerial.begin(115200);
}

int count = 0;

void loop()
{
    if(mySerial.available())
    {
      byte in = mySerial.read();
      Serial.println(in, HEX);
    }
}

```

However, the data I am receiving on the computer is inconsistent with what I expect. For example, I am expecting a 0xFA byte every 22 bytes, however this only sometimes happens. Many times extra or fewer bytes appear in the middle of the data. I am using the 5 volt arduino serial communication, however I have heard that it is still compatible with 3.3 V sensor communication, so I doubt it is the problem. I don't thinkthe sensor is broken, as it is new from a working unit.

# Answer
Soft Serial is totally unreliable. You may have a better error rate at other baud rates, but you will never achieve the same as a hardware based serial connection. I'd switch my debugging connection to the software serial, nd use the hardware serial for the XV-11.
> 1 votes

# Answer
The 'Serial' baud rate is too low compared to the baud rate of 'mySerial'. It could be causing you to lose bytes as the Serial buffer overflows, especially if the sensor transmits a lot of values in a relatively short interval. Increase the Serial baud rate to 115200 and see how it goes.
> 0 votes

---
Tags: arduino-uno, serial, sensors, softwareserial
---


# Question
Title: Sending large structs via nrf24l01 leads to cliping of some structs members
I started with building of the wireless temp/hygro/other values probes. I use 2 arduinos, both with nf24l01+ wireless transceivers, library used is rf24.h (https://github.com/maniacbug/RF24). Basically ping/pong test works for me - so each arduino communicates properly via nrf24l01+. I added dht22 temperature sensor and just for testing I started with sending structure:

```
typedef struct{
  int A; // just counter to see if receiving new data
  float B; // temperature
} data;

data payload;

```

I send it from Arduino1 like this:

```
radio.write( &payload, sizeof(payload) );

```

Other Arduino2 receives the payload:

```
radio.read( &payload, sizeof(payload) );

```

**This works perfectly and I am able to print the counter value as well as the temperature value** on the oled display o Arduino2. **The problem is when I add float C to the struct for sending/receiving hygrometer values.** Then Arduino2 does not receive/display any valid hygro value, but there is just value of 0.00.

I think I know where my problem is - nrf24.h has possibility to set payload size for nrf24l01+ - both Arduinos have to use the same payload size (default is 16, min is 8, max is 32). I use 8 - as this looks to be the most reliable value when using larger distances between Arduinos. When I tried to set payload size to 32 on both Arduinos:

```
radio.setPayloadSize(32);

```

Then it works and I can receive and display counter, temp, hygro values. So it looks the nrf24l01+ sends a payload of either 8 or 32 bytes and when sending struct with INT, FLOAT, FLOAT - 8 bytes is not sufficient and 32 bytes of payload is needed. But when I will use many other values, I can reach also limit of 32 bytes payload.

I do not have much skills in C programming and also I do not fully understand how data packets are being transferred between nrf24l01+ modules- maybe I just need to adapt my send/receive code to handle sending of the larger structures. Maybe somebody could give me a hint.

# Answer
Your payload is too big. You will have to split it to smaller pieces.

NOTE: If you'd use a library like RF24Mesh then you'd not have to worry about it.
> 3 votes

# Answer
as stated above, it all has to do with the size of your payload. To clarify things, you need to keep in mind how many bytes a certain data type uses/needs:

char: 1 byte int: 2 bytes float 4 bytes

(above is based on the Arduino reference, see https://www.arduino.cc/en/Reference/Float )

Thus, if you set payload size to 8 bytes in the NRF24L01 and then try to send a struct with int, float, float you will have 2 + 4 + 4 = 10 bytes, which does not fit in the payload size.
> 0 votes

---
Tags: nrf24l01+
---


# Question
Title: How to prevent inclusion of unnecessary libraries?
How do you save space by preventing the inclusion of unnecessary binaries?

When I compiled the ROS Blink example, I received the warning:

```
Global variables use 1,951 bytes (76%) of dynamic memory,
leaving 609 bytes for local variables. Maxiumum is 2,560 bytes.
Low memory available, stability problems may occur.

```

Considering the example uses almost no libraries, I was surprised by this, but sure enough, the compiler pulls in a ton of libraries that are never used:

```
Scanning dependencies of src
Scanning dependencies of arduino
Scanning dependencies of ros_lib
src/main.cpp
arduino/wiring.c
arduino/wiring_shift.c
arduino/wiring_digital.c
arduino/wiring_pulse.c
arduino/WInterrupts.c
arduino/hooks.c
arduino/wiring_analog.c
arduino/USBCore.cpp
arduino/new.cpp
arduino/Tone.cpp
arduino/WString.cpp
arduino/HardwareSerial1.cpp
arduino/Stream.cpp
arduino/HardwareSerial3.cpp
arduino/HardwareSerial0.cpp
arduino/CDC.cpp
arduino/HardwareSerial2.cpp
arduino/main.cpp
arduino/HID.cpp
arduino/HardwareSerial.cpp
arduino/IPAddress.cpp
arduino/Print.cpp
arduino/WMath.cpp
arduino/abi.cpp
Linking libarduino.a
ros_lib/duration.cpp
ros_lib/time.cpp
Linking libros_lib.a
Linking firmware.elf
Converting to firmware.hex

```

Why are so many files being included in the compilation, and how do I filter them out?

# Answer
> 2 votes
The Arduino IDE build script will actually copy all core source code file to the tmp directory, compile and generate an archive file. The sketch is compiled and linked with this library. Only the referenced (used) functions and data are linked in the binary.

The size (both program and data) of this blink is somewhat larger than the "standard" blink example but this is due to the publisher-subscriber run-time.

Cheers!

PS: If you google you can find commands to listing what is actually in the generated binary. Here is a starting point.

# Answer
> 2 votes
Part of the compilation process is what is known as *garbage collection*, which is controlled by the compilation flag `-Wl,--gc-sections`

This process goes through the compiled program and works out which sections (functions, blocks of read-only data, etc, each in its own *section* controlled by `-ffunction-sections` and `-fdata-sections` IIRC) and works out which are not needed in your compiled program. It then deletes them.

The problem you have though is not with code or read-only data size, but with static RAM allocation size. This is global variables and local static variables - things used for stiring data, maybe as serial buffers, etc. Most of that is probably part of the underlying RTOS that you have elected to use. Which is the problem of using an RTOS to just blink an LED. It could be seen as a task that is beneath the RTOS and is complete overkill. Of course, since you're just testing, that is pretty irrelevant, however, as you add more functionality you will most likely find that the memory footprint doesn't increase much since it's the "background" stuff that of the RTOS that will always be there regardless of what tasks you are performing.

---
Tags: compile, memory-usage, code-optimization
---


# Question
Title: Convert Long to binary - least signifant bit first
I have found an Arduino function which converts a 2-bytes-`long`-value to a binary value.

e.g. I call `sendCommand(0x05)` And it gives me an output:

`00000101`

```
void sendCommand(unsigned long command){
  for (unsigned long  mask = 1UL << (7);  mask;  mask >>= 1) {

    if (command & mask) {

    Serial.print( "1" );
    } else {

    Serial.print( "0" );
    }
  }
}

```

my Problem is, that I want to have the Least significant bit first. How do I have to adjust this function to achieve this?

e.g. `sendCommand(0x05)` shall give an output:

`10100000`

# Answer
> 1 votes
```
void sendCommand(unsigned long command){
  for (unsigned long  mask = 1UL; mask<256UL;  mask <<= 1) {

    if (command & mask) {

    Serial.print( "1" );
    } else {

    Serial.print( "0" );
    }
  }
}

```

PS a long is actually 4 bytes long. But your code only uses 1 byte of it.

---
Tags: programming
---


title: arduino weather shield with gps

text:
# Question
Title: arduino weather shield with gps
I have Arduino Mega and Weather shield and GPS Receiver - GP-635T (50 Channel).

here is my code for GPS

```
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

TinyGPSPlus gps;

static const int RXPin = 5, TXPin = 4;
SoftwareSerial ss(RXPin, TXPin);

const byte GPS_PWRCTL = 6;

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

  pinMode(GPS_PWRCTL, OUTPUT);
  digitalWrite(GPS_PWRCTL, HIGH);
}

void loop()
{
  smartdelay(800);
}

```

And print weather with this code

```
void printWeather()
{
  Serial.print("lat=");
  Serial.print(gps.location.lat(), 6);
  Serial.print("lat=");
  Serial.print(gps.location.lng(), 6);
  Serial.print("altitude=");
  Serial.print(gps.altitude.meters());
  Serial.print("sats=");
  Serial.print(gps.satellites.value());

  char sz[32];
  Serial.print("date=");
  sprintf(sz, "%02d/%02d/%02d", gps.date.month(), gps.date.day(),gps.date.year());
  Serial.print(sz);

  Serial.print("time=");
  sprintf(sz, "%02d:%02d:%02d", gps.time.hour(), gps.time.minute(), gps.time.second());
  Serial.print(sz);
}

```

But I see only zero for location and date and time. What should I do?

# Answer
> 1 votes
Until you have the correct baud rate *and* good satellite reception, many fields will be zero or empty. I wrote a diagnostic program for NeoGPS that will try different baud rates and confirm that the GPS device is functioning. The example program is in this directory:

```
examples/NMEAdiagnostic

```

Installation instructions are here.

If you're inside, you may not be able to receive anything. Move next to a window or go outside.

# Answer
> 0 votes
You need to feed the output from the GPS module to the `TinyGPSPlus` routines, otherwise they won't do anything (other than return `0`). Try adding:

```
while (Serial.available() > 0) {
  gps.encode(Serial.read());
}

```

to your `loop`. `TinyGPSPlus` comes with examples that you should have a look at. It also provides many debug statistics, e.g. the number of characters processed (`gps.charsProcessed()`) and the if these made sense (`gps.passedChecksum()`).

---
Tags: gps, tinygps
---


title: Set an arduino software clock

text:
# Question
Title: Set an arduino software clock
Me and my friend are having some trouble setting up an software clock to our arduino uno.

It's for a school project and we´ve never done any programming before. thanks!

# Answer
There is a Time library which you can import.

Here are things that I found on the Arduino website.

```
hour();            // The hour now  (0-23)
minute();          // The minute now (0-59)
second();          // The second now (0-59)
day();             // The day now (1-31)
weekday();         // Day of the week, Sunday is day 1
month();           // The month now (1-12)
year();            // The full four digit year: (2009,
                //  2010 etc)
setTime(t);              // Set the system time to the
                      //  give time t
setTime(hr,min,sec,day,month,yr); // Another way to set
                               //  the time
adjustTime(adjustment); // Adjust system time by adding
                     //  the adjustment value

timeStatus();   // Indicates if time has been set and
             //  recently synchronized
             //  returns one of the following
             //  enumerations:
* timeNotSet    // The time has never been set,
             //  the clock started at Jan 1 1970
* timeNeedsSync // The time had been set but a sync
             //  attempt did not succeed
* timeSet       // The time is set and is synced
             //  Time and Date values are not valid if
             //  the status is timeNotSet. Otherwise
             //  values can be used but the returned
             //  time may have drifted if the status is
             //  timeNeedsSync.

setSyncProvider(getTimeFunction);// Set the external time
                              //  provider
setSyncInterval(interval);    // Set the number of
                           //  seconds between re-sync

```

And obviously,

```
#include<Time.h>

```

Tell me in the comments if you need more help.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to create a standalone exe which can burn the code into a Teensy 3.1?
So here's the scenario.

I have sent my teensy 3.1 circuit to a client of mine And now I need to update the code burned onto teensy without providing client access to the code

So is it possible to create an exe or an installer of a kind which on execution simply upload the new code onto the teensy?

Since the code is finally a hex file uploaded onto the controller I hope this must be possible But on doing a quick google search i was not able to find any valid resource which would guide me how to go about it.

# Answer
> 1 votes
Yes, it is perfectly possible.

You will need three things:

1. The HEX file you want to program
2. The programming utility for your chosen board (would be in the IDE folder somewhere - not sure what Teensy uses off hand)
3. A text editor.

Then, using the text editor, you create a `.BAT` file which executes the programming utility with the right parameters to program the board.

It can help to do an upload in the IDE in verbose mode so you can see exactly what command and parameters are being executed.

# Answer
> 1 votes
Yes. Teensy has a command line loader available at https://www.pjrc.com/teensy/loader\_cli.html or https://github.com/PaulStoffregen/teensy\_loader\_cli

Given the hex file, the teensy\_cli client could upload it without giving your client the source code. For non-teensy devices, avrdude could be used similarly.

Alternately, one could fork the cli code, modify it to use an embedded copy of your hex file data in a hard-coded or encrypted constant, and then deliver that modified single-purpose executable file to your client.

# Answer
> 1 votes
The simplest solution is to ask you client to install the TeensyLoader application. https://www.pjrc.com/teensy/loader.html

Send the new HEX file to the client. The client should then connect the board to the computer. Run the TeensyLoader and upload the HEX file. The TeensyLoader will recognize the board when the reset button is pushed. The HEX file will need to be located on disk (after download or mail attachment).

Cheers!

---
Tags: uploading, bootloader, teensy
---


title: Converting ASCII value to String

text:
# Question
Title: Converting ASCII value to String
I have this code.

```
String incoming;   // for incoming serial data

void setup() {
    Serial.begin(9600);  // opens serial port, sets data rate to 9600 bps
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incoming = Serial.read();
            String mysrr = String(incoming);
            // say what you got:
            Serial.print("I received: ");
            Serial.println(mysrr);
    }
}

```

A few of you will recognise this as an Arduino example.

However, when I run it ( I sent it the message "hi"), I get this in the serial:

```
I received: 104
I received: 105

```

Why is this happening?

# Answer
> 0 votes
Serial.read() returns an int not a String. https://www.arduino.cc/en/Serial/Read

Use an int for incoming (as the example). Or even better use a char and skip all the strings.

Cheers!

---
Tags: serial, arduino-mega
---


title: Light leds on this board one at a time

text:
# Question
Title: Light leds on this board one at a time
I am playing around with this Tinycircuits 16 LED board and I can figure out how to persistently light two LEDs at the same time. The page comes with an example that i can modify but I can only do 1 at a time

**How do I light more than one LED at a time?**

```
/*
TinyDuino Edge LED Demo

April 9 2014, by Ben Rose

This example code is in the public domain.

http://www.tiny-circuits.com

*/

void setup()
{
  LedOn(0);//Pass a zero to turn all LEDs off
}

void loop()
{
  for(int i=1;i<16;i++){
    LedOn(i);
    delay(20);
  };
  for(int i=16;i>1;i--){
    LedOn(i);
    delay(20);
  };
}

void LedOn(int ledNum)
{
  for(int i=5;i<10;i++){
    pinMode(i, INPUT);
    digitalWrite(i, LOW);
  };
  if(ledNum<1 || ledNum>16) return;
  char highpin[16]={5,6,5,7,6,7,6,8,5,8,8,7,9,7,9,8};
  char lowpin[16]= {6,5,7,5,7,6,8,6,8,5,7,8,7,9,8,9};
  ledNum--;
  digitalWrite(highpin[ledNum],HIGH);
  digitalWrite(lowpin[ledNum],LOW);
  pinMode(highpin[ledNum],OUTPUT);
  pinMode(lowpin[ledNum],OUTPUT);
}

```

# Answer
> 2 votes
This is your circuit.

I think you can take it from here by looking at the diagram, but please note that e.g. 1 0 0 0 0 will light up 3 and 1, so be careful.

To show more than one, turn on multiple LEDs in rapid succession. It will give the effect that more than one are on. This is known as multiplexing.

**Update:**

After Googling around, I understood it better. I also wrote this code.

```
int IO1 = 50;
int IO2 = 48;
int IO3 = 46;
int IO4 = 44;
int IO5 = 41;
int del = 1000;

void setup() {

  pinMode(IO1, INPUT);
  pinMode(IO2, INPUT);
  pinMode(IO3, INPUT);
  pinMode(IO4, INPUT);
  pinMode(IO5, INPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
    displayLED(1);
    delay(del);
    displayLED(2);
    delay(del);
    displayLED(3);
    delay(del);
    displayLED(4);
    delay(del);
    displayLED(5);
    delay(del);
    displayLED(6);
    delay(del);
    displayLED(7);
    delay(del);
    displayLED(8);
    delay(del);
    displayLED(9);
    delay(del);
    displayLED(10);
    delay(del);
    displayLED(11);
    delay(del);
    displayLED(12);
    delay(del);
    displayLED(13);
    delay(del);
    displayLED(14);
    delay(del);
    displayLED(15);
    delay(del);
    displayLED(16);
    delay(del);// light up LEDS 1, 2 and 3.
}

void displayLED(int a){
    clear();
    if (a == 1){o(1); o(2); h(1); l(2); Serial.println('1');}
    if (a == 2){o(1); o(2); l(1); h(2); Serial.println('2');}
    if (a == 3){o(1); o(3); h(1); l(3); Serial.println('3');}
    if (a == 4){o(1); o(3); l(1); h(3); Serial.println('4');}
    if (a == 5){o(2); o(3); h(2); l(3); Serial.println('5');}
    if (a == 6){o(2); o(3); l(2); h(3); Serial.println('6');}
    if (a == 7){o(2); o(4); h(2); l(4); Serial.println('7');}
    if (a == 8){o(2); o(4); l(2); h(4); Serial.println('8');}
    if (a == 9){o(1); o(4); h(1); l(4); Serial.println('9');}
    if (a == 10){o(1); o(4); l(1); h(4); Serial.println(10);}
    if (a == 11){o(3); o(4); l(3); h(4); Serial.println(11);}
    if (a == 12){o(3); o(4); h(3); l(4); Serial.println(a);}
    if (a == 13){o(3); o(5); l(3); h(5); Serial.println(a);}
    if (a == 14){o(3); o(5); h(3); l(5); Serial.println(a);}
    if (a == 15){o(4); o(5); l(4); h(5); Serial.println(a);}
    if (a == 16){o(4); o(5); h(4); l(5); Serial.println(a);}

}

void clear(){pinMode(IO1, INPUT);
  pinMode(IO2, INPUT);
  pinMode(IO3, INPUT);
  pinMode(IO4, INPUT);
  pinMode(IO5, INPUT);}

void o(int o){
    if (o == 1){pinMode(IO1, OUTPUT);}
    if (o == 2){pinMode(IO2, OUTPUT);}
    if (o == 3){pinMode(IO3, OUTPUT);}
    if (o == 4){pinMode(IO4, OUTPUT);}
    if (o == 5){pinMode(IO5, OUTPUT);}
}

void h(int l){
    if (l == 1){digitalWrite(IO1, HIGH);}
    if (l == 2){digitalWrite(IO2, HIGH);}
    if (l == 3){digitalWrite(IO3, HIGH);}
    if (l == 4){digitalWrite(IO4, HIGH);}
    if (l == 5){digitalWrite(IO5, HIGH);}
}

void l(int h){
    if (h == 1){digitalWrite(IO1, LOW);}
    if (h == 2){digitalWrite(IO2, LOW);}
    if (h == 3){digitalWrite(IO3, LOW);}
    if (h == 4){digitalWrite(IO4, LOW);}
    if (h == 5){digitalWrite(IO5, LOW);}
}

```

# Answer
> 0 votes
That is an interesting challenge. You should include the circuit diagram for this. It really helps understand the code.

.

There is excellent information on this technique to reduce number of pins here.

Cheers!

---
Tags: led
---


# Question
Title: TCP or HTTP connection between web server and arduino
If arduino works as a client and tries to connect to web server (the server is mine), should I connect to it via TCP or HTTP connection? Data will be simple strings (20 chars at max) so TCP connection should probably be enough?

The connection has to work in both ways - web server sending data to arduino and arduino sending data back to server.

# Answer
It's time you learned the OSI 7 layer model: PDNTSPA.

HTTP is a *P*resentation (protocol) that runs over a TCP *S*ession. If you are interacting with a web server then you will be opening a TCP socket and sending HTTP requests.

There is no other way of talking to a web server. It only speaks HTTP, and you can only connect to it through TCP.
> 2 votes

---
Tags: arduino-uno, web-server, tcpip
---


# Question
Title: Arduino / BitVoicer Sending IR code on loop
I was designing a voice automated kitchen lighting system. I have led strips under the cabinets which are remote controlled by an IR remote, so I captured the IR codes and got an IR led to turn them on. Now I introduced BitVoicer so that I could use voice commands to control the LED. I have ran into the issue that the IR led keeps turning the lights on and off, but my IR codes worked prior to using BitVoicer.

Here is my arduino code:

```
#include <BitVoicer11.h>

int IRledPin = 13;

BitVoicerSerial bvSerial = BitVoicerSerial();

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

void loop()
{
  bvSerial.getData();

  if(bvSerial.strData == "")
  {
    return;
  }

  if(bvSerial.strData == "wake")
  {
   LightOnCode();
  }
}

  void pulseIR(long microsecs)
   {
     cli();

     while (microsecs > 0)
      {
        digitalWrite(IRledPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(IRledPin, LOW);
        delayMicroseconds(10);

        microsecs -= 26;
      }
     sei();
    }
   void LightOnCode()
{
  pulseIR(8940);
  delayMicroseconds(4380);
  pulseIR(520);
  delayMicroseconds(600);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(540);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(540);
        delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(540);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(500);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(540);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(600);
  pulseIR(500);
  delayMicroseconds(580);
  pulseIR(540);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1640);
  pulseIR(580);
  delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);

}

```

If anyone could answer my question as to why the led keeps sending extra signals I would appreciate it! If you have any questions don't hesitate to ask!

# Answer
Taking a quick look at the Documentation on page 22, it looks like you need to use your `bvSerial.strData` calls within a function called `void serialEvent()` rather than inside of your loop. I would recommend trying out their tutorial on that page just to make sure you get BitVoicer to work properly before scaling it for your application.

Hope that helps!
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to get weight data from glass electronic bathroom scale sensors?
I am doing a small project with a bathroom scale but I run into some problems. I am using an Arduino Uno V3, HX711 module amp and a scale.

Scale:

HX711 amplifier:

I disassembled the scale to get to sensor wires and I am a bit confused. These sensors have three wires each. So they are half bridge sensors. The scale is using 4 sensors so when the scale is measuring it is measuring with a full bridge. And these 3 wires are RED, BLACK, BLUE. I don't know what is black (GND or Positive) and blue (same guess). Four red wires are given names E+, E-, S+ and S-. I will provide a picture of the disassembled scale.

Two blue wires are soldered together on each side. I guess red wires are signal (S+, S-, E+ and E-) but what are Blue and Black? Then I soldered the wires to these wires to get sensor readings but I don't know what is what.

The sensor is looking like this:

**I tried:**

1. Two different libraries for this project both named HX711 (for this module)
2. Changing A+ for A- on module

> ```
> // Hx711.DOUT - pin #A1
> // Hx711.SCK - pin #A0
>
> #include "hx711.h"
>
> Hx711 scale(A1, A0);
>
> void setup() {
>
>   Serial.begin(9600);
>
> }
>
> void loop() {
>
>   Serial.print(scale.getGram(), 1);
>   Serial.println(" g");
>
>   delay(200);
> }
>
> ```

with no success. I get 0.0g on the serial monitor when calm, and the same when load is on.

**My questions are:** How to know which wire is GND, +5V and which is signal? How to connect 4 of these sensors to read data? How to use HX711 libraries available and HX711 module? And, most important, how to read data from this scale on serial?

# Answer
> 8 votes
Your four half bridge load cell sensors can connect into a full wheatstone bridge as in https://electronics.stackexchange.com/a/199470/30711

If your sensors are like this 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245 or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:

... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture. I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension. In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant. One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above.

If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors.

Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells. With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.

To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires. (This is the function of the soldered-together blues and blacks are in your scale.) Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-. Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A- (Ignore B+/B- as a second, unused channel.)

Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds. The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance. Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown. (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)

simulate this circuit – Schematic created using CircuitLab

Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.

With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low. This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above.

# Answer
> 2 votes
1. The HX711 provides power to a bridge and amplifies the bridge's differential voltage. The scale's original circuit board (which drives an LCD readout) also provides power to a bridge. You are unlikely to get any useful readings while both circuits are applying power to the bridge.

(You could cut the existing wires and attach connectors to allow changing back and forth between the original board and your Arduino circuit.)

2. Some scales like the one shown use a 9 V battery to run the electronics. That voltage, if used, is likely to be incompatible with connecting an Arduino (typically powered by 3.3 V or 5 V) or an HX711 (powered with VDD in the range 2.7 V to 5.5 V) at the same time as the original board.

# Answer
> 1 votes
Text mainly from my comments with some additions - with image added.

The sensors are quite possibly configured as in Fig1 in the data sheet.
If so there should be +5 and 0V across two points, and weight signal between two others.

Use a DMM to Check for Vdd (probably 5V if pV battery, ~= 3V with Lithium battery). Find two leads to bridge with ~= Vdd on. Other two probably at Vdd/2 above ground. It is likely there are 4 wire effectively so each of the red wires on one side may be conncted tpo one on the other side - an Ohm-meter will tell you. Connect meter on LOW V range between other two and see if reading varies with weight change. Report back.

As jwpat7 says - you may need to repower sensors off HX711 supply to get correct readings.

HX711 looks nice. Under $1/module in modest volume on Alibaba and under $US/0.50 / IC in hundreds.

What Fig1? I know where is GND and VDD on HX711 module, and where goes the signal wires(A-,A+,B-,B+). That is clear. I dont know which colors of wires from sensors is GND VDD and Signal. I will do this. I will put back the power on the scale (3v from battery) and I will try to measure wires to determine what is what (i will put some load on the scale). I have a multimer so i will try to determine which wires are signal, and which wires are GND and VDD. I will report back. Tnx Russell. –

See fig of **HX711 Data sheet** for larger view of this image.

# Answer
> 1 votes
The sensor you have in your scale are a simple voltage dividers. Each consist of one resistor and one extensiometer, both connected in series. One wire (E+) is VDD another (E-) is GND and the third is divider output(S). You can not directly use it with HX711 which needs a bridge sensors not just dividers. You can try to set a 1/2vdd on S- and connect the signal from the sensor to S+. In case you get a negative weight, simply swap these connections. Your assumption that your scale uses full bridge, because it has four sensors, is completly wrong. You can read the signals from the scale sensors using analog inputs in you arduino (without HX711) but you should amplify it before to get reasonable resolution. Good luck! Greg

---
Tags: arduino-uno, serial, sensors
---


# Question
Title: Arduino countdown timer for repeating actions
I have tried to find simple library for triggering timer after some time. The idea is to retry network connection (RF24 network library).

I have following code now

```
while(!mesh.write(message, headerType, memSize)) {

}

```

This code will try to send packet until success

But I need to give up after for instance 10 seconds

I wanna to have something like this

```
bool timerTriggered = false;
Timer myTimer = new Timer(10000);
myTimer.setCallback(countedDown);

void countedDown() {
   timerTriggered = true;
}

```

And start timer before network request

```
myTimer.start();

while(!mesh.write(message, headerType, memSize) || !timerTriggered) {

}

```

Please suggest the best way to implement this.

Thanks.

**EDIT**

I have found problem as far as delay(); uses timer internally it conflicts with libraries or simple timer.

The solution is to use `Alarm.delay(400);` instead.

Maybe someone knows better solution ?

# Answer
Something like this would work as a non-blocking, general purpose timer:

```
unsigned long startTimestamp;
unsigned long timestamp;
const unsigned long timer_length = 10000; //10 seconds

startTimestamp = millis();
timestamp = startTimestamp;

while ( (timestamp - startTimestamp) < timer_length)
{
    // keep doing thing

    timestamp = millis();
}

// stop doing thing now

```
> 1 votes

# Answer
To expand on the other answer and combine it better with your situation:

Just check the current time in your while loop:

```
unsigned long startTime = millis();
while((!mesh.write(message, headerType, memSize)) && ()millis() - startTime) < 10000)) {
}

```

That is, while it's not transmitted properly, and the difference between now and when you started transmitting is less that 10 seconds, keep trying.

There is no need for any special libraries or asynchronous timers - it can all be done by examining `millis()`.
> 1 votes

---
Tags: arduino-nano, interrupt, timers
---


# Question
Title: Negative voltage output Or Controling negative voltage
I've got an RGB led strip I'm trying to control. It's a 12v, 4 pin strip. Pin layout seems rather odd to me as 1 pin takes 12v of power and 3 pins (that go to ground) control the colors. In other words, **the LED colors are controlled by limiting outgoing voltage**.

* **White**\- +12v
* **Green**\- Green in negative voltage
* **Red** \- Red in negative voltage
* **Blue** \- Blue in negative voltage

I've already made a similar setup that uses n-channel MOSFETS (or at least I think that's what they are) between the colored cables and the ground and Arduino power the MOSFET gates as necessary.

**So my question is:** is it possible to hook these LEDs up directly to arduino and control the negative voltage without aditional electronics?

As a slightly off topic question: Is there a specific name for elements that are controlled with negative voltages.

---

By the way, I'm using Arduino nano, although I don't think it is relevant at this point and I've got Mega and Uno aswell if needed.

# Answer
> 2 votes
No, it's not possible, since the voltages and currents involved (12V) are too high. It will damage your board.

Your arrangement with N-channel MOSFETs is the correct arrangement.

By the way, you are not working with "negative" voltages at all - it's all positive - you just happen to be between the "load" and ground.

This is called a **Low Side Switch** since it is on the "low" (i.e., between the load and ground) side of the circuit.

The LEDs you have are in an arrangement called **Common Anode** in that the anodes (+ pins) of the LEDs are all tied together (common) and you control the cathode (- pins) of the LEDs. It means you can use cheap N-channel MOSFETs that are (as you have seen) easy to control with a microcontroller. The other arrangement, *Common Cathode*, where all the cathodes (- pins) are tied together and you switch the power to the anodes (+ pins) requires P-channel MOSFETs *and* N-channel MOSFETs to switch the P-channel MOSFETs, which increases costs.

---
Tags: arduino-nano, rgb-led
---


# Question
Title: Connect ethernet cable wires directly to pins
Is it possible to uncrimp a RJ45 plug and connect the wires directly to the Arduino pins? I guess I'd have to decrypt the ethernet signal then on my Arduino which might not have enough processing power at command for such a task.

I don't want to do it with an Ethernet shield, so please don't link any in the answers.

# Answer
> 1 votes
Electrically, you don't have to worry about anything, as the previous answer stated, but Ethernet (Even 100Mbps FastEthernet, much less Gigabit) is way too fast for the Arduino to read. `digitalRead()` is roughly 100x too slow, it takes roughly 4 microseconds, and even doing direct port reads is 5x too slow. This doesn't take into account another operations, much less the fact that the clocks on the Arduino's don't run that fast.

100Mbps FastEtherent runs at roughly 31MHz, or 31,000,000 Hz. That is FAST compared to our Arduino's, which have a clock speed of only 16MHz.

To answer your question in a word, no, it is not possible to do what you ask.

# Answer
> 2 votes
As others have stated, it's not physically possible for an Arduino to encode or decode standard Ethernet protocol messages over CAT5 cable with wires at one end connected directly to the Arduino pins, and the other plugged into a standard Ethernet device. Standard Ethernet runs at least 10 Mbit/s for 10BASE-T, each bit Manchester encoded, so effectively 20 Mbit/s. See "TCP/IPv4 and Ethernet 10BASE-T/ 100BASE-TX Debugging" for a lot of photos of what the standard Ethernet protocol looks like on an oscilloscope screen. An Arduino running at 16 MHz can't sample a pin at 20 Mbit/s.

However, Arduinos can easily transmit and receive messages using a variety of other, slower communication protocols. Devices that use such protocols can often be wired directly to the Arduino pins, with the Arduino programmed appropriately with that protocol.

Occasionally people use CAT5 cable (commonly called "ethernet cable") to carry those non-Ethernet messages from one device to another.

Sometimes people wire a RJ45 socket (also called a 8p8c socket) directly to an Arduino and corresponding RJ45 socket wired directly to the other device (often with a big "THIS IS NOT ETHERNET" warning on both sockets), and use standard off-the-shelf CAT5 patch cables with standard RJ25 plugs (also called 8p8c plugs) to carry those non-Ethernet messages between the sockets. (For example, the connection between the Arduino-compatible "Motherboard 1.2 Generation 3" and the "Stepper Motor Driver 2.3 Generation 3" used in some early RepRaps; the TechZone Thermocouple A-D converter and other 1-wire devices that use the 1WRJ45 standard; etc. As far as I can tell, none of the many CAT5 cables Nate connected to various Arduinos in "Lessons from Rebuilding Illumitune" actually carry any Ethernet messages.)

Sometimes people cut and strip the ends of CAT5 cable, using them as a convenient bundle of wires that can be used pretty much like any wire.

Hooking wires directly between two Arduinos (or an Arduino and some other device using some non-Ethernet protocol) often seems to work when both are plugged into the same power supply and connected by a short cable. The "extra hardware" people use to interface between an Arduino and a Ethernet network or CANbus or RS485 bus or MIDI or etc. helps avoid a variety of problems that happen when two devices are plugged into different power supplies or have long cable runs between them or both.

# Answer
> 1 votes
I am by no means an expert on this, this answer is ~20 minutes of me googling things, but I would say that *in theory* it is probably possible to do this with an arduino, at least at the lower transfer rates anyway, and certainly from a "will it kersplode my board" point of view - probably not since ethernet runs at +/- 2v (ish) and ~10mA (ish). *However*:

The ethernet protocol is exceedingly complex, with many layers needed to actually communicate with anything useful, all of which you would have to implement from scratch (there won't be a library to just drop in) and I'm not completely convinced that an entirely software-based implementation of the stack would fit on the arduino (but I could definitely be wrong there - and actually, on further thought, this probably is wrong, but I reckon *I* couldn't write it so it fit, but I'm a reasonably average human being).

Arduino is all about hacking and re-inventing wheels just for the fun of it but I am absolutely certain that there is no fun to be had re-engineering Ethernet and TCP/IP and all of the stuff in betweeen from scratch (obviously my opinion, I enjoy all sorts of things others don't, so YMMV).

My suggestion would be - if you don't like ethernet shields, look into getting a 'raw' ethernet controller chip (like the one soldered onto an ethernet shield) and build it directly into whatever device you're trying to make *first*, that'll give you plenty of exposure to how ethernet works at that level, then you can decide if you're still up for re-inventing the brain that invented the wheel. Good luck!

---
Tags: pins, ethernet, wires
---


title: exit(0) function shows up an error

text:
# Question
Title: exit(0) function shows up an error
So I have been trying to write a code where I use the `millis()` function to print the milliseconds of on-time of the board using `Serial`. But the condition is I want to stop printing the value once it reaches 10 seconds (10000ms).

I have been trying to use the `exit()` function but I get no output then.

```
#include<stdlib.h>

void setup()
{

  Serial.begin(9600);          //  setup serial

}

void loop()

{

unsigned long timer1;

while(timer1%10000!=0)

{

timer1=millis();

Serial.println(timer1);

}

    exit(1);

}

```

# Answer
> 2 votes
The AVR library documentation for exit() is great help. It explains that the interrupts are turned off and an infinite loop is entered. As the interrupts get turned off the last characters in the Serial buffer are not transmitted.

You can use Serial.flush() to wait for the transmission to complete before calling exit().

Cheers!

---
Tags: arduino-uno, programming, c
---


# Question
Title: Problem in RS485 Communication between Arduino and PC
I'm trying to sending and receiving data via RS485 communication. Interfacing Arduino and PC(laptop) using SN75176 RS485. I wrote a program to send a string "Hello" from arduino via Tx pin. My intention is to receive the "Hello" string in my PC's hyperterminal. After uploading the program im receiving junk data. The baud rate i've mentioned in my program and i gave in hyperterminal are same. I've checked the wire connection, it is ok. Then, what is the problem?

Code:

```
#include <SoftwareSerial.h>
int Txpin = 1;
int ditpin = 5;  //for 1st rs485
int ditpin1 = 2; //for 2nd rs485
void setup()
  {
          // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(Txpin,OUTPUT);
    digitalWrite(ditpin, HIGH); //For transmit data from arduino
    digitalWrite(ditpin1, LOW); //For receive data to hyperterminal
  }

void loop()
  {
    Serial.println("Hello\r\n");
    delay(1000);
  }

```

Wire connection:

# Answer
> 0 votes
You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on MAX3222.

Cheers!

---
Tags: rs485, rs232
---


title: What's wrong with my IR sensor

text:
# Question
Title: What's wrong with my IR sensor
I bought some 'lucky dip' IR sensors from China, no idea what they are, but they appeared to get lost in the post so instead I bought some of these from a reputable place in the UK that come with a datasheet.

The next day, both items arrived together!

I'm trying to build a very simple proximity sensor for a robot, I built the following circuit:

simulate this circuit – Schematic created using CircuitLab

and stole this code to test it out:

```
#define IRledPin 8
#define D13ledPin 13
#define IRsensorPin 9

void IR38Write() {
  for(int i = 0; i <= 384; i++) {
    digitalWrite(IRledPin, HIGH);
    delayMicroseconds(13);
    digitalWrite(IRledPin, LOW);
    delayMicroseconds(13);
  }
}

void setup(){
  pinMode(IRledPin, OUTPUT);
  digitalWrite(IRledPin, LOW);
  pinMode(D13ledPin, OUTPUT);
  digitalWrite(D13ledPin, LOW);
}

void loop(){
  IR38Write();
  if (digitalRead(IRsensorPin)==LOW){
    digitalWrite(D13ledPin, HIGH);
  } else {
    digitalWrite(D13ledPin, LOW);
  }
}

```

If I hold my hand in front of it, nothing happens (LED on-board arduino should light up), *however* if I point a TV remote at it and press a button, the LED lights up. I tested 2 of the 'fancy' sensors that I got and both behaved the same.

Then I tried one of the 'lucky dip' sensors, swapped it straight in and the whole thing works perfectly - point a TV remote and the LED lights, hold my hand ~10cm in front of it and the LED lights!

So, where have I gone wrong?

# Answer
See page 5 of your datasheet - that 'fancy' sensor suppresses "• Continuous signals at any frequency".

So you'll need to pulse your 38.4kHz signal for the sensor to produce an output.
> 4 votes

# Answer
The answer I've accepted is the correct answer, but I wanted to add this extra bit for completeness. I reworked my code to use non-blocking delays for the IR LED so the sensor actually gets a chance to see it before it stops transmitting and it works! Range is quite a bit shorter than the 'lucky dip' sensor (~ 2cm).

```
#define IR_LED 8
#define LED 13
#define SENSOR 9

unsigned long burst_timer;
unsigned long gap_timer;

unsigned long timestamp;

char led_state;
char burst_count;

const char BURST_MAX = 20;

void setup()
{
  pinMode(IR_LED, OUTPUT);
  led_state = LOW;
  burst_count = 0;
  digitalWrite(IR_LED, led_state);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);

  pinMode(SENSOR, INPUT);

  timestamp = micros();
  burst_timer = timestamp;
  gap_timer = timestamp;
}

void toggle_led()
{
  if (led_state == LOW)
  {
    led_state = HIGH;
  }
  else
  {
    led_state = LOW;
    burst_count++;
  }

  digitalWrite(IR_LED, led_state);
}

void loop()
{
  timestamp = micros();
  if (timestamp - burst_timer > 13 && burst_count < BURST_MAX)
  {
    toggle_led();
    burst_timer = timestamp;
    gap_timer = timestamp;
  }

  if (burst_count >= BURST_MAX && timestamp - gap_timer > (13*2*BURST_MAX) )
  {
    burst_count = 0;
    burst_timer = timestamp;
    gap_timer = timestamp;
  }

  if (digitalRead(SENSOR) == LOW)
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}

```

Every time I use `delay()` (or `delayMicroseconds()`) I find a new reason not to!
> 3 votes

---
Tags: ir
---


# Question
Title: Light up multiple LEDs with standard Arduino Uno
I am trying to find out if it is possible to light up multiple LEDs with a standard Arduino Uno. Say I have 500 LEDs and logically I give each one of them a number from 1 to 500. In my test scenario I'd like to say something like "LED No 275 On" and as a result only have this single LED turning on while all others remain off.

Is there a way to do that at all? Or will I have to use many different Arduino Unos for that?

# Answer
> 1 votes
Probably the simple answer is to use 63 8-bit shift registers, with a LED and resistor attached to each shift register output pin. There are many good examples of using shift registers to add output ports on the internet.

The shift register solution will let you turn on just one LED at a time, or if your power supply can stand it, all 500 at once.

This question shows how to go about the expansion Is there a way to have more than 14 Output pins on arduino? It also gives some other valid options.

# Answer
> 1 votes
Rectangular matrices and strips of dozens or hundreds of LEDs are available from places like Adafruit and Sparkfun, with added circuitry to allow you to address and manipulate single LEDs easily. Some are single color, some are RGB. Adafruit in particular has many products like this and many tutorials on how to use them.

---
Tags: arduino-uno, led, pins
---