# Question
Title: Rc switch library transmit using protocol 5
I'm trying to transmit using mode 5 with the rc switch library, but my reciever tells me that the data is using protocol 2. I'm using the RecieveDemo\_simple example as a sniffer for 433 MHz and I'm recieving data with protocol 5 from a wireless electric plug that I want to replicate.

I am able to send the data, but it is using the wrong protocol most of the time.

Here's some output from the reciever:

```
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 5

```

The code:

```
/*
  Example for different sending methods

  https://github.com/sui77/rc-switch/

*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {

  Serial.begin(9600);

  // Transmitter is connected to Arduino Pin #10
  mySwitch.enableTransmit(10);

  // Optional set pulse length.
  // mySwitch.setPulseLength(320);

  // Optional set protocol (default is 1, will work for most outlets)
  mySwitch.setProtocol(5);

  // Optional set number of transmission repetitions.
  // mySwitch.setRepeatTransmit(15);

}

void loop() {

  /* Same switch as above, but using decimal code */
  mySwitch.send(15885740, 24);
  delay(1000);
  mySwitch.send(15766156, 24);
  delay(1000);

}

```

# Answer
> 1 votes
I would expect your sending protocol 5 just fine.

But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.

This is the definition of the two protocols from the code:

```
{ 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
{ 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

```

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted. The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses. Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.

---
Tags: rf
---


# Question
Title: Crosspack instead of Arduino IDE, how to include Arduino.h
I quit using the Arduino IDE, instead I am now using Crosspack via the command line on my Mac.

It is working totally fine. I use "make" to compile it, "make flash" to upload it to the Arduino.

This is the Makefile I got right now:

```
# Name: Makefile
# Author: <insert your name here>
# Copyright: <insert your copyright message here>
# License: <insert your license reference here>

# This is a prototype Makefile. Modify it according to your needs.
# You should at least check the settings for
# DEVICE ....... The AVR device you compile for
# CLOCK ........ Target AVR clock rate in Hertz
# OBJECTS ...... The object files created from your source files. This list is
#                usually the same as the list of source files with suffix ".o".
# PROGRAMMER ... Options to avrdude which define the hardware you use for
#                uploading to the AVR and the interface where this hardware
#                is connected. We recommend that you leave it undefined and
#                add settings like this to your ~/.avrduderc file:
#                   default_programmer = "stk500v2"
#                   default_serial = "avrdoper"
# FUSES ........ Parameters for avrdude to flash the fuses appropriately.

DEVICE     = atmega328p
CLOCK      = 16000000    # 16 MHz for Arduino
PROGRAMMER = #-c stk500v2 -P avrdoper <-- leave this commented since we already specified the default programmer above
FUSES      = -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efuse:w:0x05:m # arduino defaults
OBJECTS    = main.o

# ATMega8 fuse bits used above (fuse bits for other devices are different!):
# Example for 8 MHz internal oscillator
# Fuse high byte:
# 0xd9 = 1 1 0 1   1 0 0 1 <-- BOOTRST (boot reset vector at 0x0000)
#        ^ ^ ^ ^   ^ ^ ^------ BOOTSZ0
#        | | | |   | +-------- BOOTSZ1
#        | | | |   +---------- EESAVE (set to 0 to preserve EEPROM over chip erase)
#        | | | +-------------- CKOPT (clock option, depends on oscillator type)
#        | | +---------------- SPIEN (if set to 1, serial programming is disabled)
#        | +------------------ WDTON (if set to 0, watchdog is always on)
#        +-------------------- RSTDISBL (if set to 0, RESET pin is disabled)
# Fuse low byte:
# 0x24 = 0 0 1 0   0 1 0 0
#        ^ ^ \ /   \--+--/
#        | |  |       +------- CKSEL 3..0 (8M internal RC)
#        | |  +--------------- SUT 1..0 (slowly rising power)
#        | +------------------ BODEN (if 0, brown-out detector is enabled)
#        +-------------------- BODLEVEL (if 0: 4V, if 1: 2.7V)
#
# For computing fuse byte values for other devices and options see
# the fuse bit calculator at http://www.engbedded.com/fusecalc/

# Tune the lines below only if you know what you are doing:

AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE)
COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE)

# symbolic targets:
all:    main.hex

.c.o:
    $(COMPILE) -c $< -o $@

.S.o:
    $(COMPILE) -x assembler-with-cpp -c $< -o $@
# "-x assembler-with-cpp" should not be necessary since this is the default
# file type for the .S (with capital S) extension. However, upper case
# characters are not always preserved on Windows. To ensure WinAVR
# compatibility define the file type manually.

.c.s:
    $(COMPILE) -S $< -o $@

flash:  all
    $(AVRDUDE) -U flash:w:main.hex:i

fuse:
    $(AVRDUDE) $(FUSES)

# Xcode uses the Makefile targets "", "clean" and "install"
install: flash fuse

# if you use a bootloader, change the command below appropriately:
load: all
    bootloadHID main.hex

clean:
    rm -f main.hex main.elf $(OBJECTS)

# file targets:
main.elf: $(OBJECTS)
    $(COMPILE) -o main.elf $(OBJECTS)

main.hex: main.elf
    rm -f main.hex
    avr-objcopy -j .text -j .data -O ihex main.elf main.hex
    avr-size --format=avr --mcu=$(DEVICE) main.elf
# If you have an EEPROM section, you must also create a hex file for the
# EEPROM and add it to the "flash" target.

# Targets for code debugging and analysis:
disasm: main.elf
    avr-objdump -d main.elf

cpp:
    $(COMPILE) -E main.c

```

I cannot just include "Arduino.h", but I need (want) to use it anyway.

My question is how I would go about doing that? I know where Arduino.h is located, but I cannot just copy that file to the project folder because it needs other files too.

If more info is needed, please let me know.

# Answer
You need to compile all the core `.c`, `.cpp` and `.S` files into `.o` files (optionally archiving them into a `.a` file) then link them with your main program. Your main program will then become a sketch where you use `setup()` and `loop()` instead of `main()` since the `main.cpp` file in the core has `main()` in it. Of course you need to include `Arduino.h` in your source files as well or nothing will work.

The same goes for libraries. You need to compile and link the source code with your code as well as including the header file(s) in your code (and providing the paths to them with `-I...` directives).
> 2 votes

---
Tags: arduino-uno, arduino-ide, library
---


title: Arduino, 74HC595N, magic

text:
# Question
Title: Arduino, 74HC595N, magic
Good day

I'm playing with Arduino and shift register chip 74HC595N and already tried many different ways to solve my problem, but still to luck :(

So that is my current simple scheme:

Arduino 2,3,4 ports connected to data, clock and latch pins of 74HC595N. I've connected only first two output pins of chip to make minimum power consumption and to simplify this example as much as possible.

That is my sketch:

```
const int latchPin = 4; //Pin connected to ST_CP of 74HC595
const int clockPin = 3; //Pin connected to SH_CP of 74HC595
const int dataPin = 2;  //Pin connected to DS of 74HC595

void setup()
{
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  Serial.println("ON");
  digitalWrite(13, HIGH);
  send(B10000001);
  Serial.println("OFF");
  digitalWrite(13, LOW);
  send(B01000010);
}

void send(byte d) {
  Serial.println(d);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, d);
  delay(1000);
  digitalWrite(latchPin, HIGH);
}

```

And the problem is: sometimes leds are blinking but very unstable. Sometimes it's not working at all, sometimes only first led is blinking, but second one is not. Sometimes opposite - second led is blinking, first one is not. Sometimes one of led is blink very fast (just flash instead of 1 second delay). If I touch wires and elements on breadboard - something changing. Even without touching anything - situation changing. It seems like problem is somewhere in connection or power supply and I've already tried to except it: tried few different breadboard, two different 595 chips, different wires and resistors, tried Arduino Uno, Mega and nano. Even tried atmega328p standalone, tried power it from USB, from 9v battery, old mobile charger (5.4V, 650 mA), tried to power arduino with external source (12V, 1A). In all cases the problem still exists.

I've already read a lot about power supply for Arduino, but I think at least few of the ways I've already tried to supply power is good enough for 595 chip and two LEDs - isn't it?

Please, advice me what else can I try?

# Answer
Even this is quite old, to help others as well:

As you already did, pin 13 (output enable, active low) to ground and pin 10 (master reset, active LOW) to HIGH, to disable reset.
> 0 votes

---
Tags: arduino-uno, shift-register
---


# Question
Title: How to read Ultrasonic sensor value to use and drive servo motors
I would like to know how i can use my ultrasonic value in an if else statement, so i can use the value that the servo motors stop running and go in another direction when the ultrasonic sensor gets close to an object.

```
/*
  Digital pin 2 is connected to a switch
  Digital pin 3 is connected to a switch
  Digital pin 7 is connected to the echo port of the ultrasonic sensor
  Digital pin 8 is connected to the trig port of the ultrasonic sensor
  Digital pin 9 is connected to a servo
  Digital pin 10 is connected to a servo
  Digital pin 13 is connected to a LED

 */

#include <Servo.h> // include a special file that is needed for servo motors, do this only once

Servo motor1; // create a servo object for each motor
Servo motor2;

int echo = 7; //declare echo from ultrasonic sensor
unsigned long duration;
void setup() {
  // initialize the LED pin as an output:
  pinMode(13, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(2, INPUT);
    // switch 2 initialize
    pinMode(3, INPUT);
  // initialize the servo on pin 9
  motor1.attach(9);
  // motor 2 initialize
  motor2.attach(10);
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    //echo pin of ultrasonic sensor
    pinMode(echo, INPUT);
    //trig pin of ultrasonic sensor
    pinMode(8, OUTPUT);

}

void loop() {
      // the trigger pin sends a pulse
       digitalWrite(8, LOW);
       delayMicroseconds(2);
       digitalWrite(8, HIGH);
       delayMicroseconds(10);
       digitalWrite(8, LOW);
       duration=pulseIn(echo, HIGH);
      // the echo pin measures how long it took for that pulse to come back
       Serial.println(duration);
      // delay in between reads for stability
       delay(50);
       duration=pulseIn(echo, HIGH);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if(duration <=400) {
    // turn LED on:
    digitalWrite(13, HIGH);
    // turn the motors off for 2 seconds
    motor1.write(90);
    motor2.write(90);
    delay(2000);
    //turn motor 1 on for 2 seconds to make a turn
    motor1.write(180);
    delay(2000);
  } else {
    digitalWrite(13, LOW);
    //motors run when vehicle is not near objects
    motor1.write(0);
    motor2.write(180);
  }
}

```

# Answer
> 1 votes
First, I would make sure I have continuous servo motors that can rotate 360 degrees. Your servos will just rotate to the degree you entered if they are not continuous. Additionally, it would be more helpful if you named your pins. For example:

```
int echo = 7;
void setup(){
    pinMode(echo, INPUT);
}

```

This will help us read the code better.

I also see that you have "pulseIn" in your if statement. You must save the value to a variable with the data type of unsigned long.

```
//before the setup
unsigned long duration;

//keep your setup as it is

void loop(){
   digitalWrite(8, LOW);
   delayMicroseconds(2);
   digitalWrite(8, HIGH);
   delayMicroseconds(10);
   digitalWrite(8, LOW);

   duration=pulseIn(echo, HIGH);

   if(duration<=400){//check for the value
       // turn LED on:
        digitalWrite(13, HIGH);
        // turn the motors off for 2 seconds
        motor1.write(90);
        motor2.write(90);
        delay(2000);
        //turn motor 1 on for 2 seconds to make a turn
        motor1.write(180);
        delay(2000);
   }else{
        digitalWrite(13, LOW);
        //motors run when vehicle is not near objects
         motor1.write(0);
         motor2.write(180);
       }
   }

```

Overall: check your servos and save the value of pulseIn to a variable. You might also want to convert to centimeters by dividing duration by 58.2.

---
Tags: sensors
---


# Question
Title: How to make PCA9685 work with Arduino Due?
I have Arduino Due and PCA9685.

I use this library: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library

The board does not do anything with servo connected. I tried to use SDA/SCL pins and SDA1/SCL1 pins, I tried to use or not use pullup resistors. The board does not react in any case.

The PCA9685 is 100% working, because it operates properly when I connect it to my Arduino Mega using the same library, it works without pullups.

Also I noticed the following indicium, when I tried to use this scanner http://playground.arduino.cc/Main/I2cScanner I have no detected devices on SCL1/SDA1 but have detected 2 devices at 0x40 and 0x70 when I connect the board SDA/SCL pins.

# Answer
> 0 votes
I made it working by this way: despite PCA9685 datasheet recommendations, we do not need to connect OE pin to VCC. Also we do not need to connect OE to ground as it recommended in some instructions related to other Arduinos.

So we should leave OE pin unconnected. Also we should use 4,7K pull-up resistors to connect SDA and SCL to VCC.

The board can be used without level converters.

No special program/libraries changes needed. So it was a hardware problem.

---
Tags: arduino-due, i2c, wire-library
---


title: Applause reactivity

text:
# Question
Title: Applause reactivity
I'm making a pretty basic light circuit and I'd like to have it react to applause or laughter, but NOT during regular speech, amplified over speakers.

I'm wondering if anyone has already made a function for this that I could use in this design!

Your help is greatly appreciated! Thanks for being awesome people who help educate, assist, and elevate others in their creative journeys. You're the best!

Ryan

# Answer
Not really an applause detector, but I have written a sound meter program you could use as a starting point for your own project. It is available here: Arduino sound meter. It works as follows:

* the analog input is read at a constant rate of about 9600 samples per second, which is normally fine for telephone quality audio processing
* the DC offset from the microphone is removed
* the readings are squared in order to get the instantaneous sound intensity; note that this is not immediately usable, as it fluctuates furiously
* this is run through a first order low-pass filter with a time constant of 26.6 ms in order to get a usable sound intensity reading
* the readings are decimated to keep only one every 26.6 ms
* they are sent to the PC through the serial port.

The program does not use the `analogRead()` function, because it is really not suited for this kind of real-time sampling. Instead, it directly accesses the ADC, it configures it in the so called “free running mode” and uses the ADC interrupt to retrieve the samples. This limits the portability of the program, which has been written for an Arduino Uno.

If you want to make an applause detector form this, I suggest the following approach:

1. Use the program as is, to record and plot the sound intensity as a function of time.
2. Test various types of sounds: applause, laughter, speech, noise...
3. Look carefully at the plots and try to see how the sounds you want to detect are different from those you do not want: high peaks? short peaks? fast rise times? You will have to make up some criteria to tell them apart. This is the most difficult part, as it will require some creativity.
4. Write some code to apply your criteria. Keep in mind that your code will ultimately have to run in real time, i.e. process one intensity sample at a time. It will not have the whole record to start with.
5. Test your code on your computer, on the data previously recorded.
6. Debug, fine-tune... until you are happy with your detection algorithm.
7. Modify my sound-meter program: remove the last statement (transmitting the data to the host computer) and replace it with your detection code.

Good luck!
> 4 votes

---
Tags: arduino-uno, adafruit, audio, sound, neopixel
---


# Question
Title: What's the difference between #define and const int when declaring a pin?
Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the `#define` command to declare pins, while some others simply use `const int` for the same.

My question is, what's the difference between the two, and which one should be preferred for use?

# Answer
"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.

"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.

Example:

```
#define A 5
int dummy_integer = A

```

... will be preprocessed as...

```
int dummy_integer = 5

```

... and the compiler will read this statement.

However, if I remember good, you can always overwrite a preprocessor directive as follows:

```
#define A 5
int dummy_integer = A
//some code here
#undef A
#define A "my_string"
std::cout << A

```

That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").
> 1 votes

---
Tags: programming, c++, ide
---


# Question
Title: Is it possible to run Python embedded in Arduino?
I know how to program in C but I'm more productive in python, so, I would like to know if there is a way to run a python code into arduino.

# Answer
You can use other kind of board called MicroPython

But yes, is possible using some kind of TX-RX Python class...
> 0 votes

---
Tags: python
---


# Question
Title: Delay In receiving data when SoftPWMBegin(); is used from SoftPWM.h library
when i use `SoftPWMBegin()` function in setup there is some delay while receiving data over bluetooth. And if i pressed o and 1 fastly (see in below given code), some time it receives data and sometime not receives. when i not using `SoftPWMBegin()` it receives data fastly . I think `SoftPWMBegin()` function creating some problem. I want use `SoftPWM.h` library for controlling RGB led brightness. So please give me any solution for that...

```
#include <"SoftwareSerial.h">
#include <"SoftPWM.h">

SoftwareSerial Genotronex(0, 1);

int redPin = A5;

int greenPin = 3;

int bluePin = A0;

int BluetoothData;

void setup()

{

 Genotronex.begin(57600);

  SoftPWMBegin();

  }

void loop()
{

if (Genotronex.available())

   {

      BluetoothData=Genotronex.read();

   if(BluetoothData=='0')

   {

  SoftPWMSet(redPin, 0);

   }

   else if(BluetoothData=='1')
{

    SoftPWMSet(redPin, 20);

   }

}

}

```

# Answer
Maybe you need to change the class that contains the `SoftPWMBegin()` or `Genotronex.read()` methods. I don't know this library, can you give the link for donwload it and to try it...?
> 1 votes

# Answer
Software PWM is quite complex and uses interrupts to emulate PWM using a timer. SoftwareSerial also uses interrupts. You can't have two things happening at once, so one wilk take precedence over the other. In this case the timer interrupt is taking precedence over the Pin Change interrupt, so the reception is delayed, which breaks SoftwareSerial since it relies on a prompt response to the interrupt to work.

You basically have to avoid the use of both software emulations together. Either switch to using the hardware UART, or hardware PWM or, even better, ditch both and go for 100% hardware driven.
> 0 votes

---
Tags: arduino-uno, arduino-mega, programming, sketch, programmer
---


# Question
Title: Is it possible to charge a battery using a water flow sensor?
Is it possible to use a water flow sensor to charge a battery? Since the water flow sensor measures water flow using pulses, could I charge a battery using these pulses(instead of using it to read water flow).

Heres an example of the product? https://netram.co.za/1200-g-12-water-flow-sensor-13mm.html

Thank you

# Answer
> 3 votes
> Is it possible to charge a battery using a water flow sensor?

No, it is basically a hall-effect sensor that requires power and generates a low effect pulse.

Look for a generator. Something like this; https://netram.co.za/1199-36v-micro-hydro-generator.html

Cheers!

---
Tags: battery
---


# Question
Title: ESP8266 - How to know if incoming connection is from AP or station network?
I have an ESP8266 module connected with my Arduino configured as a server, with both AP and station modes (AT+CWMODE=3) activated, and I want to know if an incoming connection comes from the AP's network or the station's network. This is the package I'm receiving, and it's exactly the same whether it comes from one or another network:

```
+IPD,0,437:GET /?uuid=7be547af980d13c5&cmd=10 HTTP/1.1
Host: 192.168.0.222:51813
Connection: keep-alive
Cache-Control: max-age=0
Accept: */*
Origin: http://127.0.0.1:8020
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
DNT: 1
Referer: http://127.0.0.1:8020/domo_ctrl/www/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: es-419,es;q=0.8,en;q=0.6

```

At first I thought that it would reject packages addressed towards another IP (AP's IP is different from station's IP), but since this IS the gateway, it receives ALL incoming traffic. Please help!

EDIT:

This is the firmware and other stuff shown by `AT+GMR`:

```
AT+GMR

AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
Ai-Thinker Technology Co. Ltd.
Jun 13 2016 11:29:20
OK

```

# Answer
> 1 votes
I don't think the default AT firmware allows to automatically reject packets because that would probably require a higher degree of control, but looking at the Expressif documentation about the AT command set I've discovered you can actually retrieve the remote address rather than the local one, just by using the same command you were using but with a different parameter

```
AT+CIPDINFO=1

```

Not sure though this actually might solve your problem.

---
Tags: esp8266, wifi
---


title: Problems with Ultrasonic Sensor

text:
# Question
Title: Problems with Ultrasonic Sensor
I want to check my understanding on how to use `digitalWrite` for `5V` and `Grd` and why this code isn't working.

This is for the Makeblock sensor

Consider the image here which says to plugin a wire to 5V, Grd and a signal pin.

My code does the following

```
#define h  22
#define l  24
#define sig 26

void setup() {
   Serial.begin(9600);
   pinModde(h, OUTPUT);
   pindMode(l, OUPUT);
   pinMode(sig, OUPUT);

   digitalWrite(h, HIGH);
   digitalWrite(l, LOW);
}

void loop() {
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

```

When I run this code duration is always `0`. If I unplug `22` and `24` and use the board's `5V` and `Grd` I get duration is `30001` no matter how far away an object is from the sensor. Meaning it's not sensing anything, just returning this number.

Full disclosure that I'm using solder-less wires but I don't that would make this much of a difference?

So to summarize: why are 22 and 24 resulting in a 0 readout and not acting as 5V and Grd? My only thought is maybe too much voltage and a resister is needed?

Secondly: why is the sensor not working even when using 5V and Grd pins?

# Answer
You've set `pinMode(sig,INPUT);` and never changed this back to `OUTPUT` before triggering next measure:

```
void loop() {
   pinMode(sig, OUTPUT);    // ensure sig is configured as an output
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

```

And for example PING))) (which is basically the same module) has power consumption about 30mA-35mA in datasheet. Output pin might be strong enough to power it, but I'd recommend at least GND connect directly to arduino GND. And using transistor for powering it up would be even better
> 1 votes

---
Tags: arduino-mega, sensors, wires
---


title: Sending IR via a wire

text:
# Question
Title: Sending IR via a wire
So i have taken apart this old remote i found, and removed the IR-LED and replaced it with wires.

I thought that i would just be able to put the wire that used to go to the positive side of the IR-LED, to a pin on my Arduino UNO (and negative to GND), and just use the same IR decoding library to decode the signal, as if it was from an IR sensor.

But as it turns out, i receive undecipherable nonsense (or so it seems), like 5+ different codes from pressing the same button on the remote.

If i connect the 2 pins from the remote to the IR-LED on my breadboard, and an IR receiver to my Arduino i receive the signal you would expect, which in my case is "**24137D**" in HEX (1 on the remote) every time.

**So my question is: Why does this happen and is it even possible to do what i am trying to do. Why? Why not? And if possible how is this done?**

Here is the code i am using:

```
#include <IRremote.h> //https://github.com/z3t0/Arduino-IRremote

#define IR_Pin 7

IRrecv irrecv(IR_Pin);
decode_results results;

void setup() {
  Serial.begin(9600);
  pinMode(IR_Pin, INPUT);
  irrecv.enableIRIn();

}

void loop() {
    if(irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume();
  }

}

```

Maybe the answer is obvious and i just don't understand how IR works. If so feel free to link some documentation that can help me.

Thank you.

# Answer
> 3 votes
Your IR receiver is decoding the high frequency pulsed *On-Off-Keying* waveform for you. The Arduino doesn't do that.

An IR signal consists of high frequency (say 36KHz) on-off light pulsed at a lower (data) frequency (different combinations to make 1 and 0)

The receiver you have takes that high frequency signal, amplifies it, filters it, and gives you just the resulting 1 and 0 signals. From that the Arduino can use simple time measurements to work out the code.

Without the filtering that the receiver provides the Arduino will have to do all that work by itself - and while that may be technically possible, it's seldom done. You may be able to find a library that can do it, but it's unlikely.

---
Tags: arduino-uno, ir
---


# Question
Title: Making three led's blink at different times in Arduino
I have a breadboard connected to an Arduino Uno, 220k resistors connected to an led, of course it has a common ground and a pin connected to 5v. All pins are digital.

Now, I want led 1 to turn on for one second, the next led for two seconds and the next for three seconds, but that means, when the second led which has to be on for two seconds then the first led will come back on after one second has past on the second led, the third led would be on for three seconds, so the second led will also be on when two seconds pass and the first would be on when one second passes. So basically, all leds are on for their given duration.

How do I do this? I have been trying to do this since three days. It would be a pleasure if someone helps me out. Thanks.

```
int ledPin1= 2;
int ledPin2 = 4;
int ledPin3 = 7;

void setup(){
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  }

  void loop(){
  digitalWrite(ledPin1, HIGH);
  delay(500);
  digitalWrite(ledPin1, LOW);
  delay(500);

  digitalWrite(ledPin2, HIGH);
  delay(1000);
  digitalWrite(ledPin2, LOW);
  delay(1000);

  digitalWrite(ledPin3, HIGH);
  delay(1500);
  digitalWrite(ledPin3, LOW);
  delay(1500);
    }

```

So far this is the code. But it delays the whole program. Need leds on at given times.

# Answer
Using a 220k Ohm resistor will lead to approximatively 20µA to light the LED. This is not enough to light the LED, you should replace the resitor by one of value 330Ohm (220 to 470 could be OK depending of the LED)
> 3 votes

# Answer
Seems like you want a pattern like this ?

```
LED1 : 1 0 1 0 1 0 1 0 1 0 1 0 ... repeat
LED2 : 1 1 0 0 1 1 0 0 1 1 0 0 ... repeat
LED3 : 1 1 1 0 0 0 1 1 1 0 0 0 ... repeat

```

In which case you'll need something like this pseudo code

```
// set up the relevant pins as output etc
....
// set up a counter
counter = 0

loop
  toggle LED1
  if (counter modulo 2 == 0) then toggle LED2
  if (counter modulo 3 == 0) then toggle LED3

  counter++
  if counter > 11 then counter = 0 // your pattern repeats every 12 seconds

  delay for 1 second

```

Toggling the LED is just a case of checking if it is high or low and setting it to the opposite value.
> 1 votes

---
Tags: arduino-uno, arduino-ide, hardware, electronics, electricity
---


# Question
Title: Serial Communication Not Receiving Entire String
I have an Arduino connected to a pico motor driver that is supposed to take a number of steps for a specific number of triggers that gets from a source (i.e. waveform generator). I've setup the code so that it would ask the user to input number of steps and number of triggers. For example, if I want the motor to take 10 steps once it got 60 triggers, I should input s10; and t60; separately into Serial Monitor.

In addition, I want to be able to change the number of steps and triggers any time that I want. However the problem is that sometimes Arduino doesn't receive the input string entirely for the first time. Sometimes it works on the second try. Or even not at all. I really appreciate if someone can give a hint on why this is happening.

This is a simple version of the code (without the parts that move the motor):

```
#include<String.h>

long int steps;
long int num_triggers;
long int newtrigger;
long int newstep;
long int oldtrigger;
long int oldstep;

const int main_control = 0;
int triggers_count;
bool motor_trigger = true;

void setup() {

 Serial.begin(19200);
 Serial.println("Please enter chosen number of steps and triggers.");
 Serial.println("Example: \n If you want the pico-motor to take 10 steps per 40 triggers,");
 Serial.println(" write 's10;' and press enter then do the same for 't45;'(Order doesn't matter).");
}

void loop() {

  while (num_triggers == 0 || steps == 0) {

    getcommand(&steps, &num_triggers);

  }

  attachInterrupt(main_control, trigger, RISING);  // it starts looking for trigger

  if (motor_trigger == false) {

    getcommand(&steps, &num_triggers);
  }

  else if (motor_trigger == true) {

    motor_trigger = false;
    detachInterrupt(main_control);

    if (triggers_count <= (num_triggers - 1)) {

      getcommand(&steps, &num_triggers);

    }

    else {

      for (int i = 0; i < steps; i++) {

        oldstep = steps;
        oldtrigger = num_triggers;
        getcommand(&steps, &num_triggers);

        if (  num_triggers != oldtrigger || steps != oldstep) {
          break;
        }
      }
    }
  }
}

void trigger(void) {

  motor_trigger = true;
  triggers_count++;
}

void getcommand (long int *newstep, long int *newtrigger) {

    char   char_input;
    String string_input;
    String output_1;
    String output_2;

  while (Serial.available()) {

    char_input = Serial.read();
      if (char_input == ';'){
    Serial.println("done");

      }
      else{
    string_input += char_input;
    delay(500);
    }
  }

  Serial.println("Getting input...");
  Serial.println(string_input);
  Serial.println("Input printed.");

  int inputlen = string_input.length();
  output_1 = string_input[0];

    for ( int i = 1; i < inputlen; i++ ) {
      output_2 += string_input[i];
    }

      if ( output_2.toInt()<=0 && inputlen>0 ){   // check if there's an error

        Serial.println("Error with input number");
        delay(5000);
        Serial.println("Reading the input string");
        Serial.println(Serial.readString());
        Serial.println("Done reading the input string");
        }

    if (output_1 == "s") {

      *newstep = output_2.toInt();

    }

    else if (output_1 == "t") {

      *newtrigger = output_2.toInt();
    }

  }

```

# Answer
> 2 votes
I can see several issues:

* If the Serial buffer contains more than one command already, you'll read it too. For example serial buffer contains `"s43;t25;"` and the `input_string` would be something like `"s43t25"`. This is highly to happen if you send those characters in less than 3seconds (as you have `delay(500)` for each appended character). You have to stop reading from buffer if you detect ';'.
* Parsing of commands is also pretty weird. You are blocking for some time, so you can detect 's'/'t' and then use `Serial.parseInt();` with `Serial.setTimeout(1000);` to do similar but much faster get command.
* Variables set inside of ISR (function trigger is called from ISR) must be volatile. Otherwise it might be optimized out or into register by compiler.

Anyway, if you want to read whole commands try the `serialEvent()` example. Just change checking for `'\n'` to `';'` and then you can parse that command in your way when it's complete.

---
Tags: serial, string
---


title: ATtiny serial.print() crash with INTs

text:
# Question
Title: ATtiny serial.print() crash with INTs
I'm trying to print some data to and from an **ATtiny85** via serial, using the `SoftwareSerial` library. So far I've tried these setups with no results:

* 1/8MHz clock
* baud rates from *9600* to *57600* (library doesn't seem to support higher rates)
* printing to a newline or a single one
* packing up a `char` array just as much as a `String` and then printing it
* `Tx`ing/`Rx`ing through an Arduino Nano/Uno/Mega or a cheap USB-Serial port

Reading up on the subject seemed to suggest that some values I was passing (such as '1000') might have been erroneously interpreted as EOL characters breaking the code, but attempts with different values (i.e. 845) returned the same failures.

As you might have guessed I'm writing code with the ArduinoIDE, and no errors are returned when compiling and uploading. Many other parts of the project involving serial work just fine, and I can communicate with the ATtiny on pretty much any of the above setups (actually packing up the `String` or `char[]` crash the whole thing). The 'Ready' at the end of the setup is also printed fine, and the loop runs as long as it won't encounter any of the above issues.

Here's the code:

```
int VALUE = 1000;
int ANOTHER = 12;

#include <SoftwareSerial.h>
SoftwareSerial tSerial(3,4);

void _serialEvent() {
  if (tSerial.available()) {
    char mode = tSerial.read();
    if (mode == '?') {
      tSerial.println("someTextHere 1.23moreText");
      tSerial.print("value:");
      tSerial.print(VALUE);
      tSerial.print(";another:");
      tSerial.println(ANOTHER);
    }
    else if ...
  }
}

void setup() {
  tSerial.begin(57600);
  ...
  tSerial.println("Ready");
}

void loop() {
  ...
  _serialEvent();
}

```

# Answer
It is much better to store string literals in the FLASH only. In Arduino there is `__FlashStringHelper` class and `F()` macro ensures that correct version of `print` method is used and that the string literal is not copied into the ram before it's printed.

Basically if you don't have enough memory, using lots of string literals results in stack overflows, coruption and/or returning to random adresses and it looks like crashes/resets.
> 2 votes

---
Tags: softwareserial, attiny
---


title: Making three LED's blink at given times

text:
# Question
Title: Making three LED's blink at given times
I have a breadboard connected to an Arduino Uno, 220k resistors connected to an led, of course it has a common ground and a pin connected to 5v. All pins are digital.

Now, I want led 1 to turn on for one second, the next led for two seconds and the next for three seconds, but that means, when the second led which has to be on for two seconds then the first led will come back on after one second has past on the second led, the third led would be on for three seconds, so the second led will also be on when two seconds pass and the first would be on when one second passes. So basically, all leds are on for their given duration.

How do I do this? I have been trying to do this since three days. It would be a pleasure if someone helps me out. Thanks.

```
int ledPin1= 2;
int ledPin2 = 4;
int ledPin3 = 7;

void setup(){
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  }

  void loop(){
  digitalWrite(ledPin1, HIGH);
  delay(500);
  digitalWrite(ledPin1, LOW);
  delay(500);

  digitalWrite(ledPin2, HIGH);
  delay(1000);
  digitalWrite(ledPin2, LOW);
  delay(1000);

  digitalWrite(ledPin3, HIGH);
  delay(1500);
  digitalWrite(ledPin3, LOW);
  delay(1500);
    }

```

So far this is the code. But it delays the whole program. Need leds on at given times.

# Answer
> 1 votes
You could start by drawing a time graph, like this:

```
LED 1   # # # # # # # # # # # # # # # # # #
LED 2    ##  ##  ##  ##  ##  ##  ##  ##  ##
LED 3      ###   ###   ###   ###   ###   ###
        <-period 1-><-period 2-><-period 3->

```

As you see on the graph, the whole sequence repeats itself every 12 seconds. Then, you can just write down all the pin toggles for 12 seconds and let the loop repeat itself:

```
void loop() {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin3, LOW);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin3, LOW);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(1000);
}

```

This was the simple, albeit tedious solution.

The smart solution is to go through the Blink Without Delay Arduino tutorial. You will see that, once you start using `millis()` instead of `delay()` for managing your timings, blinking three LEDs instead of one is completely trivial.

# Answer
> 0 votes
EDIT: I just love Finit State Machines and templates to do some simple tasks:

```
class FSM {
  public:
    using Handler = void(*)(FSM &);

    FSM(Handler hnd) : m_func{hnd} {}

    void check(uint32_t ts = millis()) {
      if (m_next < ts) {
        m_func(*this);
      }
    }

    void delay(uint32_t _delay) {
      m_next += _delay;
    }

    void nextState(uint8_t state) {
      m_state = state;
    }

    uint8_t state() { return m_state; }

  protected:
    Handler   m_func;
    uint8_t  m_state = 0;
    uint32_t  m_next = 0;
};

template <uint8_t PIN, uint32_t HIGH_DELAY, uint32_t LOW_DELAY> void pin_fsm(FSM & fsm) {
  switch (fsm.state()) {
    case 0:
      pinMode(PIN, OUTPUT);
      // fall through
    case 1:
      digitalWrite(PIN, HIGH);
      fsm.delay(HIGH_DELAY);
      fsm.nextState(2);
      break;
    case 2:
      digitalWrite(PIN, LOW);
      fsm.delay(LOW_DELAY);
      fsm.nextState(1);
      break;
  }
}

FSM fsms[] = {{&pin_fsm<2,500,500>}, {&pin_fsm<4,1000,1000>}, {&pin_fsm<7,1500,1500>}};

void setup() {

}

void loop() {
  auto ts = millis();
  for (FSM& fsm : fsms) fsm.check(ts);
  delay(1);
}

```

---

The code should be working, so as mentioned before in that duplicate thread, `220k` is far bigger than it should be. So just use `220R` (`= 220 Ohms`) instead of `220k Ohms` (`= 220000 Ohms`).

And if it's not working even with correct resistor, your LED is connected in reversed direction. Try the builtin LED on pin 13. That one must be working. Anyway you should read something about LEDs.

# Answer
> 0 votes
How about this? Basically each loop is 1sec, and each LED has it's own counter which increases. If the counter is higher than the LED number/onTime, the LED is off for that loop and the conter reset, otherwise LED is on.

```
uint8_t LED[3] = { 2, 4, 7 };
uint8_t LED_COUNTER[3] = { 0, 0, 0 };

void setup() {
  for (int i = 0; i < 3; i++) {
    pinMode(LED[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    if (LED_COUNT[i] = i) { LED_COUNT[i] = 0; }
    else {
      digitalWrite(LED[i], 1);
      LED_COUNT[i] += 1;
    }
  }
  delay(1000);
}

```

---
Tags: arduino-uno
---


# Question
Title: Motor running slowly when connected to digital pins, but fine with 5V pins
I am trying to connect a Dagu DG01D motor to my Arduino Uno. First I tried connecting the black wire to `GND` and the red wire to digital pin `7`. My code:

```
void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, HIGH);
}

void loop() {
}

```

When I connected the motor, it wouldn't turn, but would rotate a little when turned in one direction. However, when I connected the red wire to `3.3V` or `5V`, the motor turned quickly as expected. **Why didn't writing `HIGH` to pin `7` work?**

I already verified that I can connect and run code on the Arduino by turning on the LED by replacing pin `7` with `13`. I also tried running the same code on a SparkFun RedBoard, with similar results.

# Answer
> 2 votes
> No Load Current: 190mA (250mA MAX)

You're not getting that out of a ATmega328P GPIO. Use a driver instead.

---
Tags: arduino-uno, motor
---


# Question
Title: Use an electromagnet for reading induction as well
I have an electromagnet that I wish to use to pull a neodyne magnet closer.

I'm thinking of having the electromagnet sensing when the magnet is close, but when the magnet is running I'm pushing 12 volts through it and I don't want to fry my Arduino. How can I do the wiring to achieve this?

I only have to be able to use the magnet as a sensor while it's turned off.

# Answer
You can use a hall sensor from an old computer fan.

If the magnet is not moving you are not going to be able to sense it with the coil of your electromagnet. You can also decouple de input of your arduino with a cap in series with the coil, but again if the magnet is not fast enough you will have to use a bigger cap.

You can also make a voltage divider between your coil and sense from there. When the 12V are applied just add some code to offset the input signal.
> 0 votes

---
Tags: arduino-uno, sensors, inductive
---


# Question
Title: Sending textual and nontextual data simultaneously across a serial port
I am currently using an Arduino Uno and creating an LCD simulator that works by sending LCD data through the hardware UART (serial interface). This LCD data is very short in length; in this case, it's 2 bytes. The LCD simulator has already been made, and it is capable of detecting these LCD packets on the serial port and using them to control the simulated LCD.

However, I don't want to disturb the other traffic passing through the serial port; in this case, it's just text. The problem is that most serial monitors are able to pick up the LCD packets, which aren't supposed to be printed out because they appear as gibberish.

For now, I'm prefixing these short LCD packets with two magic numbers for it to be detectable by the LCD simulator alongside non-LCD traffic, and perhaps removable by a modified serial monitor.

I thought about using ASCII control characters to inform regular terminals that following data must not be printed, but there does not seem to be a specific control character to "hide" text/data; the closest thing there is is the `BS` character. All other control characters seem to give an inconsistent result among terminals - i.e. ESC doesn't actually hide text with the Windows console host, but it does with mintty.

My goal is to not have to integrate my own serial monitor and force others to use it if there is traffic present that can only be read by the LCD simulator. I want to allow others to use their own terminals and serial monitors to exchange textual data with the Arduino while seamlessly having LCD packets being sent invisibly and "under the hood."

Is this possible? Can I mix different types of data across the same serial port? If not, what are my options, or am I essentially forced to "reinvent the wheel" by making my own protocol that can mix the two types of traffic?

# Answer
> 1 votes
The idea that sundry terminal programs can cleanly deal with binary data intended for your LCD simulator doesn't seem realistic. Instead, look for a method to suppress the binary data when the Arduino isn't talking to an LCD simulator.

For example, during startup the Arduino could send some fixed text and a number to the host, and if the simulator is running, it would reply to the Arduino with some other fixed text and the 9's complement of the number. If the Arduino doesn't get such a reply within a couple of seconds, it turns off LCD-simulation data transmission.

# Answer
> 0 votes
I would simply send the data as ASCII, in the form of hex bytes. It wil make your two bytes become four, plus the two "leader" characters to uniquely identify them becomes six. This minor overhead can probably be absorbed.

If you have much more binary (non-ASCII) data, you could look at using a different encoding format such as Base64. This only has a 2 character overhead for every 6 bytes of binary data.

You don't mention what data rate you use, either in baud rate or "packets per second", but if you're reading it on a serial monitor it can't be very much.

# Answer
> 0 votes
If I were to do something like this on Linux, I would probably have the LCD simulator sit between the Arduino and the serial monitor, like this:

```
                    +---------------------------------------------------+
                    |                    host computer                  |
+-------------+     | +-------------------+         +-----------------+ |
|             |     | |                   |         |                 | |
| Arduino  UART-----tty  LCD simulator    ptmx----pts  Serial monitor | |
|             |     | |                   |         |                 | |
+-------------+     | +-------------------+         +-----------------+ |
                    +---------------------------------------------------+

```

For this, you have to:

1. open the serial port connected to the Arduino (“tty” on the figure)
2. create a pair of pseudo-terminals (ptmx/pts)
3. open the master side of the pair (ptmx)
4. ask the user to open the slave side (pts) with his serial monitor
5. forward all traffic but the LCD control messages between the Arduino and the pseudo-terminal.

I don't know how this works on MacOS, but since the whole pseudo-terminal concept is a standard Unix feature, I would expect it to work in a similar way on MacOS and Linux. But then I have no idea how hard it would be to port this to Windows.

---
Tags: serial
---


# Question
Title: Atmega328p programming with Arduino libraries
I'm trying to use the serial communication to work between a naked AVR Atmega328p and a computer (OS X and Linux Ubuntu).

I can program the atmega (using a pololu programmer), I make it blink a LED on a breadboard, it works fine.

I am using the Arduino libraries to facilitate the task. And they seem to work fine (using delay, digitalRead, digitalWrite, etc).

I use a USB-to-TTL CH340 chip bought on internet. The CH340 works fine, it is recognised both on Ubuntu and OS X, and the loopback test works (Put a jumper between the TX and RX line, launch `screen`, type something and it comes back in the terminal), so I assume the CH340 is properly recognise and works.

Then, I plug the CH340 on my board. The 5V on the + column of the breadboard, the GND to the - column. The circuit works, my LED blinks as requested. The loop function looks like this:

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

void loop() {
  digitalWrite(9, HIGH);   // sets the LED on
  delay(30);                     // waits for a second
  digitalWrite(9, LOW);    // sets the LED off
  delay(70);                     // waits for a second
  Serial.println("loop end");
}

```

As you can see, at the send of the loop I send a string on the serial line. Now, I see the blue LED blinking on the USB-to-TTL converter, so it is definitely receiving data. But when I try to connect like so:

```
screen /dev/cu.wchusbserialfd110 9600

```

on OS X, or

```
screen /dev/ttyUSB0 9600

```

on Ubuntu, nothing is displayed. I just get a black terminal.

Is the Arduino Serial works with Atmega328 ? I suppose so, as it is the same microcontroller than on the Arduino. Any idea of what I am doing wrong?

**Update:**

More details to answer Christ Stratton question:

My low fuse is 62: 01100010. So, according to the specifications, the internal clock is used and set at 1MHz.

I programmed the Atmega using my own test bed, a Pololu programmer (as described in the book Practical AVR Microcontrollers: Games, Gadgets, and Home Automation with the Microcontroller Used in Arduino) and avrdude (through the use of platformio). This is the command line used by platformio to flash the ROM:

```
/Users/[user]/.platformio/packages/tool-avrdude/avrdude -v -p atmega328p -C /Users/[user]/.platformio/packages/tool-avrdude/avrdude.conf -c avrispv2 -B 10 -e -b 115200 -P "/dev/cu.usbmodem00149121" -U flash:w:.pioenvs/pololu/firmware.hex

```

According to avrdude documentation, `-B 10` means bitclock is set to 10us (microseconds) so a clock at speed 100Khz.

Now if I set this -B option to 1 (1Mhz), I can't program the Atmega anymore. Avrdude just timeout:

```
avrdude stk500v2_ReceiveMessage(): timeout

```

# Answer
The clock rate of your board must match the clock rate defined in the board file you used to compile your sketch. If it does not, the baud rate will differ by the same factor.

If the actual baud rate so achieved is a valid one, you can temporarily achieve communication by setting the computer to that baud rate, but all delays and other clock-rate related functions will be off.

You should use or create a board file entry that matches your board, or use a standard clock source / clock divier setting for which there already is an entry.
> 1 votes

---
Tags: avr, serial
---


# Question
Title: Arduino Uno outputs 8V when pin is set to HIGH
I am doing the following in setup:

```
 pinMode(13,OUTPUT);
 digitalWrite(13, HIGH);

```

When I check with the multimeter, I get an output voltage of 8V rather than 5V. What may be the problem and how do I troubleshoot it?.

# Answer
You have a badly calibrated multimeter.

Try it on something where you know what the voltage should be, such as a 9V battery and see what it reads.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How do I convert a program made on Notepad to my Arduino on Proteus
I had the Arduino IDE but I accidentally deleted it. I have no internet connection, so I could not download it again. I do not currently possess the Arduino hardware itself but I do have Proteus and the Arduino library in it.

So I want to program my Arduino. Previously I would simply write the sketch and compile it and go to where I compiled it and simply add it on my Proteus Arduino and run it. Since I don't have the Arduino IDE, I tried using Notepad and tried to save it as a `.hex` file and run it on Proteus and there was an error created saying `Error reading hex file`.

So how can I program my Arduino on Proteus with the given materials (Notepad, Proteus)? Can it be done? Or is there any other way?

# Answer
> 3 votes
Besides displaying source code and letting you edit it, the IDE uses `avr-gcc` (and half a dozen other `avr-` utilities, like `avr-objcopy, avr-ar, avr-nm`) to compile and link the code and convert it to an `elf` or `hex` form, then uses `avrdude` to download it. Using proteus, you can get by without `avrdude`, but not without a suitable compiler and linker.

If you have a micro-SD slot on your phone, perhaps you can download the IDE to a card and then move the card to your computer to install the IDE.

---
Tags: sketch, simulator
---


# Question
Title: controlling LEDs, few pin outputs lots of LEDs
We need to control many leds, about 40 with arduino (UNO) and we need some remain turned on and other off at the same time. Muted or pinned vary constantly. What should I use to do this, I have several Multiplexers CD4051 but with these I can just light a LED at a time.

I do some calculation and then need to turn LEDs 1,2,5,7 and need to be pinned to the following calculation. In the following calculation I need to turn leds 4, 5, 10, 12 pinned and need to follow. What I need is something like that

With the multiplexer I can turn the LEDs I need and with minimal delay and it seems they are apprehended while, but I want to know if there is another alternative to do so

# Answer
> 3 votes
The most common technique for doing this is called "multiplexing". You arrange the 40 LEDs into 8 "columns" and 5 "rows" with common anodes and cathodes, and then you switch the columns or rows on or off individually, activating only the LEDs you want lit for that column or row. If done quickly enough it appears to the human eye that the LEDs are always lit due to persistence of vision. Note that the *physical* display does not need to be a rectangle; this is simply the *logical* arrangement used in order to simplify the circuit.

*(note that the cathode side of the above image is wrong; the cathode needs to be **low** when you want the LED to light)*

(source)

A naive implementation with 8 columns and 5 rows would use 13 pins to connect them all. However, since you don't need more than one column at a time what you can do is use a 74HC138/238 to use 3 inputs to control which of the 8 columns you want to activate. This drops the number of required pins to 8, which is low enough for anything larger than a ATtinyX5. Use of a 74HC595 for the 8 pins further drops the required MCU pins to 3, which is low enough for even a ATtiny4/5/9/10, but the timing is harder to get right due to the shift register.

# Answer
> 0 votes
Check out NeoPixels. Make sure to check out the datasheet, as a single Arduino Uno might not be able to provide the required current.

---
Tags: led
---


# Question
Title: Arduino box stops working: Reading RFID tag and sending data over network
This is a simple Arduino program which reads RFID tag and sends the data over a network (lora).

The program works fine in as i run it, the arduino reads RFID and sends it over the network (lora)

but

after a few hours it stops responding it neither reads nor sends the data over network (lora network).

I am very new to arduino and have no idea what causes the box to stop responding, kindly help.

When i restart the boxes or upload the code to it again, it starts behaving normally for a few hours and then goes back to not responding.

```
    /*
   Typical pin layout used:
   -----------------------------------------------------------------------------------------
               MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
               Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
   Signal      Pin          Pin           Pin       Pin        Pin              Pin
   -----------------------------------------------------------------------------------------
   RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
   SPI SS      SDA(SS)      10            53        D10        10               10
   SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
   SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
   SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
   Red LED                  A0
   Green LED                A2
   Blue LED                 A3
*/
/***********************************************************************************************/
//#include <SPI.h>
#include <MFRC522.h>
//#include <HID.h>

// Cooking API libraries
//#include <arduinoUtils.h>
//#include <arduinoUART.h>
//#include <arduinoMultiprotocol.h>
#include <arduinoLoRaWAN.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above
#define MAX             10         // Maximum Buffer size
#undef Debugg
/******** RFID Reader initialization**********************************************/
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
//char rfid_old[MAX];
byte *buffer;

/******************************LoRa Initialization********************************/
// Pin definition for LoRaWAN module error LED:
const int error_led =  7;
//////////////////////////////////////////////
uint8_t socket = SOCKET0;
//////////////////////////////////////////////

// Device parameters for Back-End registration
////////////////////////////////////////////////////////////
char DEVICE_EUI[] = "0000000097E471E1"; // 0000000097E471E1 / 00000000518AD184
char DEVICE_ADDR[] = "97E471E1"; // 97E471E1 / 518AD184
char NWK_SESSION_KEY[] = "00EBB4C1FCDFF52878B1725CBDFF0BA1"; // Configured for TTN
char APP_SESSION_KEY[] = "4EDC3AB4F79C565685109ECD4AF4604C"; // Configured for TTN
char APP_KEY[] = "70B3D57ED0000300"; //APP_EUI
////////////////////////////////////////////////////////////
// Define port to use in Back-End: from 1 to 223
uint8_t PORT = 1;

// variable
uint8_t error;
uint32_t cFreq[] = { 867100000, 867300000, 867500000, 867700000, 867900000 };
char rfid_arr[MAX];
char stampleErrorChar[] = "4AD6A6A65784AEBA2B"; // this data is sent from the WService When Stample Error-> Error
/* *******************************START Initialize Indication LEDs******************************* */
int greenPin = 6;
int redPin = 8;

void setup()
{
  Serial.begin(57600);
  //LoRaWAN example - Send Unconfirmed packets (no ACK)
  pinMode(error_led, OUTPUT);
  digitalWrite(error_led, LOW);

  LoRaSetup();
  RfidSetup();
}

//-----------------------------------------------------------------------------
// Name.: RfidSetup
// Descr:
//
// In...:
// Out..:
// Ret..:
//-----------------------------------------------------------------------------
void RfidSetup()
{
  SPI.begin();                        // Init SPI bus
  mfrc522.PCD_Init();                 // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
}
void LoRaSetup()
{
  LoRaWAN.ON(socket);
  LoRaWAN.factoryReset();

  // Channel parameters
  for (uint8_t i = 3; i < 8; i++) {
    LoRaWAN.setChannelStatus(i, (char*)"on");
    LoRaWAN.setChannelFreq(i, cFreq[i - 3]);
  }
  for (uint8_t i = 0; i < 3; i++) {
    LoRaWAN.setChannelDutyCycle(i, 302);
  }

  for (uint8_t i = 3; i < 8; i++) {
    LoRaWAN.setChannelDutyCycle(i, 99);
  }

  LoRaWAN.setPower(5); // [N/A, 14, 11, 8, 5, 2] dBm
  LoRaWAN.setADR((char*)"off"); // Adaptive data rate
  LoRaWAN.setDataRate(5); // [250, 440, 980, 1760, 3125, 5470, 11000];
  LoRaWAN.setDeviceEUI(DEVICE_EUI);
  //showErrorResult((char*)"2. Set Device EUI ", LoRaWAN.getDeviceEUI());
  LoRaWAN.setAppEUI(APP_KEY);
  //showErrorResult((char*)"3. Set APP EUI ", LoRaWAN.getAppEUI());
  LoRaWAN.setDeviceAddr(DEVICE_ADDR);

  LoRaWAN.setNwkSessionKey(NWK_SESSION_KEY);

  LoRaWAN.setAppSessionKey(APP_SESSION_KEY);
  //showErrorResult((char*)"6. Set App Session Key ",error);
  LoRaWAN.setRetries(3);
  LoRaWAN.saveConfig();
  LoRaWAN.joinABP();
}

void loop()
{
  // Look for new cards
  if (! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  else
  {
     error = LoRaWAN.joinABP();
     if (error == 0)
     {
       char* UId = GetUid(mfrc522);
       if(UId != NULL)
       {
          BlinkGreen(500);
          delay(100);
          // Send it!
          error = LoRaWAN.sendUnconfirmed(PORT, UId);
          Serial.println(error);
          delay(100);
          if(error == 0)
          {
             Serial.println(LoRaWAN._dataReceived);
             BlinkGreen(1000);
          }
          else
          {
             BlinkRed(1000);
          }
        }
        delay(2000);
     }
  }
}

char* GetUid(MFRC522 mfrc522)
{
    // Optional: Dump data about the cards
    //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    buffer = mfrc522.uid.uidByte;

    for (int i = 0; i < mfrc522.uid.size; i++)
    {
      sprintf(&rfid_arr[i * 2], "%02X", mfrc522.uid.uidByte[i]);
    }
    mfrc522.PICC_HaltA(); //command the card into sleep mode
    return rfid_arr;
}

void BlinkGreen(int delayTime)
{
  digitalWrite(greenPin, HIGH);
  delay(delayTime);
  digitalWrite(greenPin, LOW);
}

void BlinkRed(int delayTime)
{
  digitalWrite(redPin, HIGH);
  delay(delayTime);
  digitalWrite(redPin, LOW);
}
void showErrorResult(char* errorMessage, uint8_t error)
{
  if(error == 0)
  {
    Serial.print(errorMessage);
    Serial.println("OK!");
  }
  else
  {
    Serial.print(errorMessage);
    Serial.print(" Error: ");
    Serial.println(error);
  }
}

```

# Answer
> 1 votes
@Matt,

thanks guys. But if rfid\_arr size was an issue, wouldn't the box be giving problem the first time we use it? because it works for few hours before it goes into not responding state. The rfid tag data looks like below AEA00622 DE1CD403

# Answer
> 0 votes
The bad news is I can't see that much wrong with your code.

1. You need to set the Red and Green pinModes(). You've set error, but then don't use it. I'm guessing the green LED is a new feature. similarly you *could* refactor the blink green and blink red functions into one and pass in the pin number.
2. Are you sure that the `mfrc522.uid.size` is always less than 5? In `GetUid()` you assume that i\*2 will fit into the buffer rfid\_arr which is 10 bytes. sprint() always attaches a null onto the end of what it rights to the buffer so this will overflow if you write elements 9 and 10.

I really doubt either of those are the problem you are looking for, so would it be possible to stick loads of `Serial.println()` statements in and see where abouts it is crashing?

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


# Question
Title: WiFiClient.connect() does fail all the time (ESP8266 Core for Arduino)
I have one ESP(1) opening an AP and running a server on it. The other ESP(2) is running a client on it and is connecting to the AP and after that trying to connect to the host server. The connection to the AP does succeed but the connection to the host always fails and I cannot figure out what the problem is here. Testing the server via netcat and packetsender works fine. Connecting to it via telnet fails because the connections gets closed by the "foreign host".

*Server Sketch*

```
#include <ESP8266WiFi.h>

const char* ssid = "artex11";
const char* pw = "getmenow11";
WiFiServer server(80);
WiFiClient client;

void setup() {
  Serial.begin(115200);
  //setup AP
  WiFi.softAP(ssid, pw);
  Serial.println("AP started at: ");
  Serial.print(WiFi.softAPIP());
  server.begin();
  Serial.println("Server started...");
}

void loop() {
  client = server.available();

  if(client){
    Serial.println("Client connected!");
    Serial.print("HasClient: ");
    Serial.println(server.hasClient());
    char message = client.read();
    Serial.printf("Message: %c\n", message);
  }
}

```

*Client Sketch*

```
#include <ESP8266WiFi.h>

const char* ssid = "artex11";
const char* pw = "getmenow11";
const char* host = "192.168.4.1";
const int port = 80;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pw);
  Serial.println("Connecting to AP");
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
   }
  Serial.println(" connected");
}

void loop() {
  WiFiClient client;
  Serial.println("Connecting to host");
  if(!client.connect(host, port)){
    Serial.println("...connection failed!");
    Serial.println("Retrying in 5 seconds...");
    delay(5000);
    return;
  }
  client.print("A");
  Serial.println("...TCP message fired!");
  delay(2000);
}

```

# Answer
The problem was this missing piece

`WiFi.mode(WIFI_STA);`

If omitted it seems the WiFi is starting in Station & AP mode - so I was able to connect to the other AP but not to connect to the host because of reasons.
> 1 votes

# Answer
If the server has a default IP address of 192.168.0.1 and the client has an IP address of 192.168.4.1 my guess is they won't be able to talk because you are using a 24 bit mask.

The subnet mask defines the number of bits that makes up the subnet, so if you were using the two addresses above and had a mask of 255.255.255.0 or 24 bits then the subnets you were using would be 192.168.0 and 192.168.4. To cross subnets you need some form of routing process (usually a router, switch that can route, etc).

So you need to either change the mask or, stick both devices on the same subnet. (Don't rely on defaults, when they change your code breaks)
> 1 votes

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


# Question
Title: AVR (Arduino Uno) Serial.print and Serial.println only printing 1 or 2 chars
I first used the Arduino IDE but now I'm using PlatformIO which is awesome. But I have some big trouble with `Serial.print()` and `Serial.println()`. To show this error I have the following example code:

```
#include <avr/io.h>
#include <util/delay.h>
#include "Arduino.h"
#include "main.h"

int main(int argc, char const *argv[]) {
  Serial.begin(9600);

  section5ex34();

  return 0;
}

void section5ex34() {
  // Initialization
  DDRC = 0b00000100; // Port C2 as output and the rest (including Port C3) as input. (Port C2 is used for a led that indicates when en bit is being read)

  uint8_t b = 0b00000000;

  // here the code reads bits from PORTC3
  for (int i = 0; i < 8; i++) {
    _delay_ms(1000);
    PORTC |= _BV(PORTC2); // Make Port C2 high (indicates a bit will be read)

    if ((PINC & (0b1 << 3)) != 0) {
      b |= (1 << i);
    }

    _delay_ms(100); // Wait for the user to prepare the next bit (because this is now done by hand)
    PORTC &= ~_BV(PORTC2); // Then make Port C2 low
  }

  Serial.println(b, HEX);
}

```

When I have the code like this, it prints the right Hexadecimal value corresponding with the 8 read bits.

When I add `Serial.println("test");` after the print, it doesn't print that.

Or when I change `Serial.println(b, HEX);` to `Serial.println(b, BIN);` it prints `11`.

When I replace those 2 prints with `Serial.println("Hi test test.");` it prints `Hi`, so it seems like it can only print 2 characters.

When I add `Serial.println("Hello world . hello . hi");` *four times* after `Serial.begin(9600);`, it prints `Hello world . h` and nothing more. So here it seems like it can print *more* than 2 characters, but not all. If I wait a few seconds it adds `ello` to this, so it says `Hello world . hello`.

In the initial code, when I replace the `if`-statement with

```
if ((PINC & (0b1 << 3)) != 0) {
  b |= (1 << i);
  Serial.println("1");
} else {
  Serial.println("0");
}

```

and when the input is connected to 5v (so high) it prints a `1` once and nothing else, not even a hexadecimal value when the reading is finished.

This problem drives me crazy.

I have an Arduino Uno and use a baudrate of 9600 , 8,N,1.

I hope someone can help me out with this.

# Answer
You have two issues here:

The first is that you are using the Arduino core library and failed to initialize it. This is done automatically if you rely on the core's supplied `main()`, i.e. you stick with the `setup()`/`loop()` style of coding. If you write your own `main()`, you should start by calling `init()` to initialize the core.

**Edit**: In this particular instance, you could get away by just enabling interrupts with `sei()`. But I consider it good practice to initialize the core if you are ever going to use it.

The second issue is the abrupt termination of main: `Serial.print()` and `println()` do not really print to the serial port. Instead, they put the characters to be printed in the output buffer, and let an interrupt take care of actually sending them through the UART.

Your program ends with

```
return 0;

```

This will stop it. It will stop the whole program, including interrupt-driven tasks. So you will see whatever characters did make it to the UART, and nothing more.

If you instead end the program with and endless loop

```
for (;;) ;

```

it should work as expected.
> 5 votes

# Answer
Arduino `main()` is not so simple as you think. If you use standard Arduino `loop()` and `setup()` functions it might be working much better.

But if you're not allowed to use Arduino libraries, you can use this:

**src/main.cpp**

```
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>

void section5ex34();
int uart_putchar(char c, FILE *stream);
void uart_init (unsigned long int baud);

int main(void) {
  uart_init(9600U);

  while(1) section5ex34();
  return 0;
}

void section5ex34() {
  // Initialization
  DDRC = 0b00000100; // Port C2 as output and the rest (including Port C3) as input. (Port C2 is used for a led that indicates when en bit is being read)
  PORTC = 0b11111011;

  uint8_t b = 0b00000000;

  // here the code reads bits from PORTC3
  for (int i = 0; i < 8; i++) {
    _delay_ms(100);
    PORTC |= _BV(PORTC2); // Make Port C2 high (indicates a bit will be read)

    if ((PINC & (0b1 << 3)) != 0) {
      b |= (1 << i);
    }

    _delay_ms(100); // Wait for the user to prepare the next bit (because this is now done by hand)
    PORTC &= ~_BV(PORTC2); // Then make Port C2 low
  }
  printf("0x%02X and something loooooooooooong\n",b);
}

int uart_putchar(char c, FILE *stream) {
  if (c == '\n') uart_putchar('\r', stream);
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = c;
  return 0;
}

// function to initialize UART
void uart_init (unsigned long int baud) {
    unsigned int baudrate = F_CPU/(baud*16UL)-1;
    UBRR0H = (baudrate>>8);             // shift the register right by 8 bits
    UBRR0L = baudrate;                  // set baud rate
    UCSR0B|= (1<<TXEN0)|(1<<RXEN0);     // enable receiver and transmitter
    UCSR0C|= (1<<UCSZ00)|(1<<UCSZ01);   // 8bit data format

    //// with static FILE variable:
    // static FILE uart0fd;
    // fdev_setup_stream((&uart0fd), uart_putchar, NULL,  _FDEV_SETUP_WRITE);
    // stdout = &uart0fd;

    //// or directly by using dynamically allocated FILE struct:
    stdout = fdevopen(uart_putchar,NULL); // uses malloc/calloc, it might be inconvenient
}

```
> 1 votes

---
Tags: c, avr
---


title: Why is LED lid when pin is set low?

text:
# Question
Title: Why is LED lid when pin is set low?
I made this simple piece of code, to make my LED flash.. Which it does when the pin is set low.. But how does that makes sense?

```
#include "pins_arduino.h"

void setup() {
  // put your setup code here, to run once:
  pinMode(BUILTIN_LED,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(BUILTIN_LED,LOW);
}

```

I am using the Wemos d1 - http://www.wemos.cc/

# Answer
> 0 votes
If the LED is ON when LOW and OFF when HIGH then chances are the LED is connected between +3.3V and the IO pin with a suitable resistor.

When HIGH the IO pin is at +3.3V, so the voltage across the LED is 0V (3.3 - 3.3 = 0) and it is turned off. When LOW the IO pin is at (nearly) 0V and the voltage across the LED (and its resistor) is 3.3V (3.3 - 0 = 3.3), so it lights up.

---
Tags: programming, led
---


# Question
Title: Use transistor to press button on external device
I have a small device with a simple push button. I'd like my Arduino to be able to make the device register button pushes. It seems like the best way to do this is to use a transistor to close the circuit for the button when my Arduino sends it a pulse from one of its pins. I've mapped out what I think the circuit should look like on a breadboard. I didn't include the device in this diagram, but it's powered by a CR2032 watch battery, which seems to give 220 mAh at 3Vs.

Basically, the two sides of the button would be connected to the transistor's collector/emitter leads. Then the digital pin on my Arduino would be connected via a resistor to the base lead on the transistor. When the pin sends some current to the base lead, the transistor will make current flow through it and the device will register a button press.

I made this by adapting the circuit here, which looks like this:

Basically I got rid of the motor/load and flyback diode, and hooked the two ends of the device's button up to the collector/emitter leads of the transistor.

I'm concerned that I've screwed up this circuit somehow, and will fry either the device or the Arduino or something else when I try and run it, otherwise I'd just test it right away.

Could anyone give me feedback if I'm on the right track here? I couldn't find other answers which dealt with quite this setup, where you are pressing a button on another device, though this question seemed related.

# Answer
> 1 votes
Yes, you have screwed the circuit up slightly.

You want to lose the red wire between the collector and +5V otherwise when you turn the output pin HIGH the transistor will explode.

Also you need to make sure that the ground of the Arduino (emitter of the transistor) is connected to the - of the target circuit and that the button you are "pressing" is an active-low system with internal pullup. If it's not then you will have to come up with another way.

An opto-isolator is a better choice than a transistor when you don't know the internal circuitry of the target device:

---
Tags: arduino-uno, button, transistor
---


# Question
Title: Object can't get the right value of its property
I'm doing a program for a robot and I got stuck at a weird problem: I have classes defined for my robot's internals, for example for a `StepMotor`. I also defined a class for a `Controller`, which is going to control the speed of each `StepMotor`.

Here's a fragment of my code:

```
    #include <SPI.h>
    #include <Tone.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    /SILNIKI KROKOWE:
    class StepMotor: public Device
    {
        public:
            int motorPin;
            int dirPin;
            int sleepPin;
            int ForwardState;
            volatile double Speed;
            volatile int ControlValue;  //the value sent to the motor
            int MaxControlValue = 4000; //maximum ControlValue
            String Name;

            void Init ( void )
            {
                //init
            }

            void SetSpeed ( int speed )
            {
              toneObject.play(speed);
            }

            void SetMode(bool IsOn)
            {
              if (IsOn)
                digitalWrite(sleepPin, HIGH);
              else
                digitalWrite(sleepPin, LOW);
            }

            void SetDirection ( Dir direction )
            {
    //code for setting direction
            }

        private:
          Tone toneObject;
    };

    StepMotor motor_right;
    StepMotor motor_left;

    class Controller
    {
      public:
        ControllerType controllerType;
        double Kp;
        double Ki;
        double Kd;
        double Tp; //czas próbkowania
        volatile double e;
        volatile double e_old;
        volatile double P_result;
        volatile double I_result;
        volatile double D_result;
        StepMotor Motor;

        int Calculate ()
        {
          int Result;
     //Serial.print(Motor.Speed); HERE's THE PROBLEM
    /********************************
    /********************************
    /*******************************
          e = MoveOrder::speed - Motor.Speed;  //Motor.Speed is always 0.00, although it's not true

             //the rest is not important
        }

        void Reset()
        {
          //reset procedure
        }

    };

    Controller controller_right;
    Controller controller_left;

    setup()
    {
       controller_right.Motor = motor_right;
       controller_left.Motor = motor_left;
    }

    ISR(TIMER5_COMPA_vect)
    {
        motor_right.ControlValue = controller_right.Calculate();
        motor_left.ControlValue = controller_left.Calculate();
        motor_right.SetSpeed(motor_right.ControlValue);
        motor_left.SetSpeed(motor_left.ControlValue);

    }

```

I have cut the less important parts. The rest works properly, because my robot can drive when I use `SetSpeed(somevalue);` The only problem is that place where I need to read current speed of my motor. In the `Controller` class, there's `Calculate()` method. In that method I want to calculate `e = MoveOrder::speed - Motor.Speed;` Unfortunately it can't be calculated properly, because Motor.Speed ALWAYS is `0.00` (when I display it with `Serial.print(Motor.Speed)` I see `0.00` all the time). It's very strange, because when I display speed of each motor (`Serial.print(right_motor.Speed)` or `Serial.print(left_motor.Speed)`) the value is correct (when the wheels are spinning, value is not 0.00).

The speed calculations are in a different function, which I didn't present here, because it would be too long - I'm sure it works, because, as I said, I can get speed values properly.

As you can see in `setup()`, I set each contorller's Motor porperty to the correct object. I also used volatile keyword for the properties that are used in the interrupt.

What is wrong with my code?

If the code I provided isn't enough, here's the full version: https://1drv.ms/t/s!Atl-jM\_xUkz1hc1f-qYYotj-pJIgUw

I'm not sure if anyone would want to dive into it, because it's not so short.

# Answer
> 2 votes
My guess: `controller_right.Motor = motor_right;` makes a copy of `motor_right`. So you don't have the same class instance.

Basically `Controller controller_right;` calls default constructor which includes also default constructor for the `StepMotor`. And later all variables are copied into it by using default assigment operator, but still, it's not the same instance.

---
Tags: interrupt, class
---


title: Help avoiding floating point math

text:
# Question
Title: Help avoiding floating point math
I'm using a Texas Instruments DRV2605 haptic controller in my project to drive a LRA vibration motor. I would like to calculate the LRA rated voltage during run time using the formula below as provided in the datasheet:

I'm successfully calculating the rated voltage, but the calculation requires floating point calculations and I would like to avoid that because I'm low on available flash space on my ATTiny85 micro controller. Here is how I'm currently calculating the rated voltage value:

```
uint8_t LRA_closed_loop_rated_voltage( uint16_t voltage ) {
   float RatedVoltage;
   uint16_t SampleTime = 300;
   uint16_t frequency = 175;

   RatedVoltage = ( (float) voltage ) * sqrt( 1 - ( ( 4 * SampleTime + 300 ) * 0.000001 ) * frequency );
   RatedVoltage = ( RatedVoltage * 255 ) / 5300;

   return RatedVoltage;
}

```

The function above is just a simplified version showing the calculation and the SampleTime and frequency variables are set to their defaults values here. The voltage argument is the actuator's rated voltage in millivolt.

EDIT: Even though SampleTime and frequency have fixed values in the function above, their values will be determined by reading the relevant registers in the final implementation. SampleTime may have one of the following values: 150, 200, 250, 300 and the frequency will depend on the manufacturers specifications for the actuator.

It was easy to overcome the floating point issue on the other calculations by simply scaling up the values by 1000 (fixed point arithmetic):

> ODClamp = ( Vpeak * 255) / 5.6 /\* Vpeak in volts \*/

TO:

> ODClamp = ( Vpeak * 255) / 5600 /\* Vpeak in millivolts \*/

How can I do the calculation in question without having to use floating point?

# Answer
As I said in my comment, it is all about computing an approximation of `sqrt(1-x)`. Assuming the typical resonance frequency is between 175 and 235 Hz, then we have

> (4 × 150 µs + 300 µs) 175 Hz ≤ x ≤ (4 × 300 µs + 300 µs) 235 Hz

i.e.

> 0.1575 ≤ x ≤ 0.3525

This range is small enough to try a simple polynomial approximation. A linear approximation is just a bit too crude for 8 bit resolution. Playing with quadratic polynomials, I found this approximation which is good to 3.1e-5 in the relevant range:

> √(1−x) ≈ 0.9983795 − x (0.480515 + x 0.1955)

This can be easily implemented in fixed point by scaling everything by a factor 216 = 65536. One has to take care that any product of two such fixed point numbers must be computed in 32 bits, and the result subsequently divided by 65536. Which gives the following implementation:

```
/*
 * Compute a fixed point approximation of f(x) = sqrt(1-x).
 * Valid for x in [.1575, .3525].
 * Argument and result scaled by 2^16.
 */
uint16_t f(uint16_t x)
{
    return 65430 - x * (31491 + x * 12812UL / 65536) / 65536;
}

```
> 1 votes

---
Tags: memory-usage, variables, code-optimization, float, mathematics
---


title: Arduino Due: multiple TCS sensors

text:
# Question
Title: Arduino Due: multiple TCS sensors
I am trying to run 2 `TCS3200`’s from one `Arduino Due`. Next, I must increase to 4 sensors. I need to read the data from the 2 digital pins but how do I read both within the same loop rather than in series to save time. The code reading one sensor tasoOutPin1 (pin 10) works but why can’t I place the second read command `int detectColor(int taosOutPin2)` before the `{` symbol?

```
int detectColor(int taosOutPin1) {

float white1 = colorRead(taosOutPin1,0,1);
float red1 = colorRead(taosOutPin1,1,1);
float blue1 = colorRead(taosOutPin1,2,1);
float green1 = colorRead(taosOutPin1,3,1);
}

```

Thanks,

Scott

# Answer
> 1 votes
Seems you have to run these serially, but not sure why it's an issue, a due is quick.

seems more programming related... 'detectColor' is a function, and this is run inside the loop i assume.

```
int taosOutPin1 = 10; //color detector 1
int taosOutPin2 = 2; //Pins are examples, change to actual pin...
int taosOutPin3 = 3;
int taosOutPin4 = 4; //color detector 4

typedef struct {
   float white;
   float red;
   float blue;
   float green;

} color;

void setup() {
  // put your setup code here, to run once:

}

void loop() {

color detectedColorForSensor1 = detectColor(taosOutPin1);
color detectedColorForSensor2 = detectColor(taosOutPin2);
color detectedColorForSensor3 = detectColor(taosOutPin3);
color detectedColorForSensor4 = detectColor(taosOutPin4);

Serial.print(detectedColorForSensor1.red);
Serial.print(detectedColorForSensor1.green);
Serial.print(detectedColorForSensor1.blue);
Serial.print(detectedColorForSensor1.white);

//etc for sensor 2,3,4............

}

color detectColor(int taosOutPin1) {

color detectedColor;

detectedColor.white = colorRead(taosOutPin1,0,1);
detectedColor.red = colorRead(taosOutPin1,1,1);
detectedColor.blue = colorRead(taosOutPin1,2,1);
detectedColor.green = colorRead(taosOutPin1,3,1);

return detectedColor;

}

```

---
Tags: programming, sensors, arduino-due, processing-lang
---


title: Using an LM339 IC as a motor driver

text:
# Question
Title: Using an LM339 IC as a motor driver
I have an LM339 IC from Radioshack that I am hoping to use as a motor driver.

I read many resources on how the L239D can be used as one. I don't have enough circuit experience to truly know the difference between the two and googling shows many wiki pages I couldn't fully understand.

Can the LM339 be used as a motor driver?

I did a quick comparison of the two circuits here LM339 and L239D

But I am still unsure. I don't want to fry my board so I am asking first.

# Answer
The LM339 is a comparator, not a motor driver. The L239D is a dual H-bridge motor driver.

They are completely different things. One is used for comparing two voltages (up to 4 times, it's a "quad"), the other is used for driving motors.

The LM339 can output an absolute maximum of 20mA. That's half what the Arduino itself can output on an IO pin!

You could use the LM339 as part of the control circuitry to *control* a H-bridge, but it cannot itself drive a motor in any way, shape, or form.
> 1 votes

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


title: How to determine Flash size?

text:
# Question
Title: How to determine Flash size?
I need to determine the flash size of my ESP8266 on my NodeMCU module in order to flash the AT firmware onto the board. Apparently different boards come with differently-sized flash memories. Can anyone tell me the easiest way to find the flash size?

# Answer
Arduino's ESP8266 support includes an example sketch called **CheckFlashConfig**. This probes the board, and prints the flash memory size.
> 10 votes

# Answer
The easiest way (windows at least) is to use Espressif's flash download tool \- don't select anything to flash to the device, select the appropriate com port, click start, and the details of the device will appear in the Detected Info window
> 7 votes

---
Tags: arduino-ide, esp8266, nodemcu
---


# Question
Title: Is it possible to hookup two ultrasonic sensors to one Arduino Uno unit?
I found a couple of projects using Ultrasonic Distance sensor with Arduino Uno. Is there a way to connect two or more sensors on the same Arduino Uno?

# Answer
Yes, it is certainly possible. There are a few things you need to be aware of:

1) The Arduino UNO is 5V by design. Many sensors (not all, but many) are 3.3V devices. So connecting them to a 5V pin could damage them. Since you seem to be just starting out, I'd recommend sticking with 5V tolerant sensors.

2) The Arduino UNO only has so many pins available....obviously. Different sensors require different amount of pins to 'work'. For example, a temperature sensor might work with the SPI interface. Another sensor might require 8 pins. So if you start running out of pins, you need to think about other challenges like using shift registers, multiplexers, etc.

3) Don't be afraid to experiment. I suggest buying a genuine Arduino UNO to support the project. Maybe buy some cheap Chinese ones to experiment on...in case you fry on of those.

In theory, the sky's the limit when it comes to "how many". In real life, if you start going over a handful, dozen, etc. then you might want to rethink your design.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Good voltage and resistor value for string of LEDs
I building multiple parallel strings of 4 LEDs in series.

Since the four LEDs in series have a combined forward voltage of 12.56V at 20mA, and it's powered by 2 AA batteries, I have added a voltage booster.

Now my question is, since I can both choose the output voltage of the boost converter, and the resistor added to each string of 4 LEDs, what would be a reasonable value for both?

I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 LEDs, as their forward voltage can differ slightly due to manufacturing differences.

On the other hand, I don't want to set the voltage too high, and wast a lot of power.

So what would be an acceptable voltage drop over a current limiting resistor?

# Answer
Since the relation between voltage and power is quadratic, the obvious answer is "as little as possible".

Allowing for 3% variance in VF gives us just under 13V, so that is a reasonable starting point. Solving for R gives 22ohms, a E24 value. This will result in a 8.8mW loss, which even a 0201 resistor can handle.
> 3 votes

# Answer
> I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 leds, as their forward voltage can differ slightly due to manufacturing differences.

While that is a completely true statement, by having multiple LEDs in a chain you effectively average out the forward voltages. The more LEDs you have in your chain the more "average" each chain gets.

It's still not good to rely on the forward voltage to set the current, since it also varies with temperature (as the LEDs heat up the current will rise, leading to more heat and therefore more current, until you get thermal runaway).

As Ignacio says, the less the better when it comes to the resistance, and has recommended 22Ω and 13V, which I would recommend too.

Another option is to use a low-side *constant current sink* on each chain. This will guarantee that the current is exactly what you want (within reason) with no thermal drift in either the LEDs or the resistor.

You can find some example circuits here: http://www.radio-electronics.com/info/circuits/transistor/active-constant-current-source.php

Or you can use constant-current sink LED driver chips, which also often gives you the advantage of being able to control each chain of LEDs individually - either on/off, or PWM.
> 0 votes

# Answer
Using a boost converter and a resistor to limit current seems rather inefficient. The resistor is used to approximate a constant current source, but it would be far more efficient to use a switch mode supply to generate a constant current.

There are dedicated LED controllers which do this, although usually used with higher power LED e.g. CREE LED.

It may be possible to modify the feedback circuit in the boost converter to regulate the current, monitored with a small series resistor.
> 0 votes

---
Tags: boost
---


# Question
Title: Pinball - "All Lanes Lit" Bonus score is not behaving as expected
I'm trying to build a (very basic) pinball machine with an Arduino Uno. This part of the code will detect when a ball passes 3 lanes. When a lane is passed, it will activate the lane(laneState), reward a score(+10) and light up an LED.

**The Expected Result:**

* When all 3 lanes are LIT, assign a score of the lane passage(+10), assign a bonus score(+100) and reset all laneStates to 0 and turn all leds to LOW.
* 110 points are being added in total

**Actual Result:**

* the last lane passed lights back up as active (while I set all of them to inactive)
* 120 points are being added in total (**instead of 110?**)

Any hints on why I see this behaviour are very welcome!

---

The sketch and board can be found here: https://circuits.io/circuits/2739062-poc-lane-passage-001/ Turn on 'Code Editor' and enable the Serial Monitor to see the scores.

---

More info: I looked into using interrupts, but that is not an option here (the Uno only has 2 pins for interrupts, I need 3)

Thanks!

EDIT: added the code here too:

```
// Scores
int totalScore = 0;
const int lanePassageScore = 10; // 10 points for passing a lane
const int allLaneActiveBonus = 100; // 100 points for activating ALL lanes

// Digital pins to detect the state of the buttons
const int laneButtonPin[] = {2,3,4};
const int laneStateLedPin[] = {10,11,12};

// all three lanes are 'inactive' at the start of the game
int laneButtonState[] = {0,0,0};
int lastLaneButtonState[] = {0,0,0};
int laneState[] = {0,0,0};

void setup() {
  Serial.begin(9600); // for debugging
}

void loop() {
  // detect if lanes 1 to 3 were activated
  detectLaneButtonPassage(0); // Lane 1
  checkAllLanesLit();
  detectLaneButtonPassage(1); // Lane 2
  checkAllLanesLit();
  detectLaneButtonPassage(2); // Lane 3
  checkAllLanesLit();

  Serial.println(totalScore); // for debugging

  delay(5);
}

void detectLaneButtonPassage(int laneId){
  // Check state of the button
  laneButtonState[laneId] = digitalRead(laneButtonPin[laneId]);
  if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
    if(laneButtonState[laneId] == HIGH){
      // The lane button change to an ON position, toggle the lane state
      if(laneState[laneId] == 0){
        // lane was not yet active, it becomes active now
        laneState[laneId] = 1;
        digitalWrite(laneStateLedPin[laneId], HIGH);
        rewardScore(lanePassageScore);
      }else{
        // lane was already active, it becomes inactive now
        laneState[laneId] = 0;
        digitalWrite(laneStateLedPin[laneId], LOW);
        rewardScore(lanePassageScore/2);
      }
    }
  }
  lastLaneButtonState[laneId] = laneButtonState[laneId];
}

void rewardScore(int score){
  totalScore += score;
}

void checkAllLanesLit(){
  // Check if ALL lanes are activated
  if(laneState[0]==1 && laneState[1]==1 && laneState[2]==1){
    // reset all buttons and states
    for(int laneId=0; laneId<=2; laneId++){
      laneButtonState[laneId] = 0;
      lastLaneButtonState[laneId] = 0;
      laneState[laneId] = 0;
      digitalWrite(laneStateLedPin[laneId], LOW); //Turn off led
    }
    rewardScore(allLaneActiveBonus);
  }
}

```

# Answer
There are 2 lines of code that need to be removed from the `checkAllLanesLit()` function in order for your code to work as desired:

```
  laneButtonState[laneId] = 0;
  lastLaneButtonState[laneId] = 0;

```

*Explanation:*
What is happening is that the `detectLaneButtonPassage()` is firing as normal. Then `checkAllLanesLit()` runs and clears the `lastLaneButtonState` flag.

The program loops around again and the lane button is still pressed. However, the `detectLaneButtonPassage()` fires again because `lastLaneButtonState` has been reset and it appears to the program as a rising edge. Hence the extra 10 points.

---

On a side note, the following 2 lines could be reduced down to a single line:

```
if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
    if(laneButtonState[laneId] == HIGH){

```

The above lines of code are detecting a rising edge. They can be expressed as:

```
if(laneButtonState[laneId] && !lastLaneButtonState[laneId]){

```

For the if statement to fire `laneButtonState` must be high and `lastLaneButtonState` must be low.
> 1 votes

# Answer
Looks like a timing issue.

Which ever order you hit the buttons in the last one always `stays` lit (and you get an extra 10 points added).

I set a breakpoint at:

```
rewardScore(allLaneActiveBonus);

```

...and just waited a sec and then continued and your code worked as expected.

So I think that you are setting all lines to LOW in `checkAllLanesLit()` and then only have a short delay (5mS) before looping round and checking again (at which point the button is still HIGH as you haven't taken your finger off it quickly enough) - resulting in the additional 10 points and that lane being lit again.
> 1 votes

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