# Question
Title: Where are the Special Function Registers located? (Atmega 328)
I'd like to program my Arduino using Assembler. We have to learn this at college. The problem is that I can find a documentation for the instruction set but I can't find the Special Function Registers.

Something like this would be great or similar to make a sheet like this by myself.

# Answer
There are several options for programming the AVR in assembly, but since you have an Arduino and the Arduino IDE bundles the gcc toolchain, using this toolchain is probably the easiest way. Besides, if you learn assembly in the GNU syntax, you will be able to use it together with C++ and the Arduino libraries.

The gnu compiler will run through the C preprocessor any assembly program having the `.S` extension (in uppercase). You would then start your program with

```
#include <avr/io.h>

```

in order to get all the SFR definitions from avr-libc. That include file is intended to work both in C and in assembly. The SFRs so declared should be considered as opaque identifiers. To get their addresses, you should use the macros `_SFR_IO_ADDR()` or `_SFR_MEM_ADDR()`. I personally find those names too cumbersome to type, so I tend to `define` my own shortcuts.

Just to get you started, here is a minimal “blinky” program in assembly for the Arduino Uno (ATmega328P with the LED on PB5):

```
; Blinky in assembly.

#include <avr/io.h>
#define io(reg) _SFR_IO_ADDR(reg)

.global main
main:
    sbi io(DDRB), PB5  ; PB5 as output
0:  sbi io(PINB), PB5  ; toggle PB5

    ; delay 16 * 65536 * 5 cycles ~ 0.31 s
    ldi  r26, 16
1:  sbiw r24, 1
    sbci r26, 0
    brne 1b

    rjmp 0b ; restart

```
> 2 votes

# Answer
> Where are the Special Function Registers located? (Atmega 328)

Please see Chap. 36 Register Summary, pp. 612, in http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P\_datasheet\_Complete.pdf

The registers are available "by name" in the AVR IO header files.

Cheers!
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: (SOLVED more or less) Direct reading/writing to PORTD, unexpected readback, how does the serial library use it?
**TL;DR** When Serial is invoked on a rev3 Uno, the UART uses the Tx and Rx pins on PORTD regardless of what you try to do to PORTD I/O directly. The warnings on arduino.cc about avoid those bits appears to be wrong. Readbacks from PORTD on those pins reflects the last user input, not the state of those pins. **/TL;DR**

I have extensive assembler (other platforms) and python experience, but no C and am still on the lowers lopes of the Arduino learning curve. I am using the Arduino/C IDE at the moment for simplicity, though I have a feeling that once I bite the bullet (not for this project if possible), I am going to find the direct AVR route suits my style more.

I'm developing a charliplexed LED driver application on Uno hardware which uses most of the I/O pins, so am having to use portD. I'm using direct writes to DDRD and PORTD rather than digitalWrite(), for a number of reasons not all related to speed.

I am aware of the use of pins 0 and 1 for serial comms, so am using the recommended DDRD |= Bxxxxxx00 format when setting to 1, and DDRD &= Bxxxxxx11 when setting to 0.

I hadn't intended reading back the port, though I'm knee-deep in debug readbacks, so did it eventually. When I read back DDRD, it's Bxxxxxx00 every time. But my readbacks are working, so serial communication using the Serial.println(xx) format and the monitor in the IDE, continues to work.

I would have expected the Tx direction bit to be 1. Is it the case that the Serial library grabs the port when it needs to transmit, and then reverts it? So is it actually 0 when I read it, or am I reading wrongly, or I can't read it? As I expect DDRD &= Bxxx to work, I should be able to read it.

I'm comfortable working with the bare metal, where I have total control, and with python where it's all magic, but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

Here's the code

```
const byte portD_1_mask = B11111100;
const byte portD_0_mask = B00000011;

#define DEBUG_LEN 20
char debug_str[DEBUG_LEN+1];
#include "debug_formats.h"

byte counter;

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

  // send an intro:
  Serial.println("\n\ndebug portD demo:");
  Serial.println();
}

void loop()
  {
    counter += 3;
    Serial.println(counter);
    drive_LEDs(counter);
    delay(100);
  }

void drive_LEDs(int a)
{
    // create port programming variables, initialised to 0
    byte D_dir = 0;
    byte D_data = 0;

    // prepare bytes to be written to the ports
    // the anode gets driven by ORing into both data and direction
    D_dir |= 4;  // constant for this demo
    D_data |= 4;
    // the cathode(s) get driven by ORing into the direction only
    D_dir |= a;   // wave these around

    Serial.println("generated programming bytes");
    Serial.print("direction - data - ");
    debug_format(D_dir, D_data);
    Serial.println(debug_str);

    // finally write all pins to their new values
    // D port needs to pussyfoot around not changing the TxRx pins

    // reset D port 7-2 to all 0s
    PORTD &= portD_0_mask;
    // and then set the ones we've got in the 7-2 positions
    D_data &= portD_1_mask;
    PORTD |= D_data;

    // and the same for D direction
    // switch D 7-2 to inputs first
    DDRD &= portD_0_mask;
    // then set the outputs
    D_dir &= portD_1_mask;
    DDRD |= D_dir;

    // and see what we have written to port
    Serial.println("what the hardware has been set to");
    Serial.print("direction - data - ");
    D_dir = DDRD;
    D_data = PORTD;
    debug_format(D_dir, D_data);
    Serial.println(debug_str);
}

```

and the results it produces on the monitor

```
debug portD demo:

3
generated programming bytes
direction - data - 00000111..00000100..
what the hardware has been set to
direction - data - 00000100..00000100..
6
generated programming bytes
direction - data - 00000110..00000100..
what the hardware has been set to
direction - data - 00000100..00000100..
9
generated programming bytes
direction - data - 00001101..00000100..
what the hardware has been set to
direction - data - 00001100..00000100..
12
generated programming bytes
direction - data - 00001100..00000100..
what the hardware has been set to
direction - data - 00001100..00000100..

```

The hardware is doing what I'd expect, LEDs are flashing.

Now I'm not concerned that the 'generated programming bytes' have LSBs set and they don't appear in the readback, as I'm doing a data &= portD\_1\_mask which clears the LSBs before ORing into the port.

What I am questioning is the fact that the two LSBs on DDRD are always read back as 0. If the Serial library grabbed and kept those pins continuously, then I would expect the Tx pin to be an output, whenever I read it. But it's not reading back that way. So does that mean Serial only makes the Tx an output when it's transmitting, and then puts it back to input when not? Or is my read of the DDRD Tx bit not working for some reason, though it seems to be working for the other bits?

OK, so I've got the 'scope out, put a resistor network on the Tx pin so I can see whether it's high or low Z, and it stays low Z even when not transmitting, so the UART does 'retain' the port. This means the readback of the DDRD contents is a lie. Section 19.6 of the AVR doc 8161 does say the port pins are *overridden* by the UART, which this seems to confirm.

So if they are overridden, all this warning on the arduino.cc site tutorials about not stomping on the pins is incorrect. The following code bashes the bejaabers out of PORTD while using it to receive and send.

```
  int count;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // send an intro:
  Serial.println("\n\ndebug portD demo:");
  Serial.println();
}

// the loop function runs over and over again forever
void loop() {
  count += 1;
  if ((count&1)==0) DDRD = 0; else DDRD = 0xff;
  if ((count&2)==0) PORTD = 0; else PORTD = 0xff;

  PORTB = 0xff;
  byte dd = DDRD;
  byte pp = PORTD;
  Serial.println();
  Serial.println(count);
  Serial.println(dd);
  Serial.println(pp);
  PORTB = 0;
  delay(2000);

  if (Serial.available() > 0)
  {
    byte inByte = Serial.read();
    Serial.print("got >");
    Serial.println(inByte);
  }
}

```

and this fragment of output captured from the monitor shows it keeps working. I used a sufficiently long delay so I'd be able to hit all phases of the write to data and direction on PORTD.

```
9
255
0
got >49

10
0
255
got >114

11
255
255
got >99

12
0
0
got >115

13
255
0
got >115

```

Lessons

a) When Serial is in use, the UART hardware does override the Tx Rx pins, at least on a rev3 Uno.

b) It does hang on to the hardware between active transmissions

c) The warnings on arduino.cc tutorials about writes to PORTD and DDRD don't seem to be valid, it appears the hardware just ignores them

d) Reads back from PORTD and DDRD show what you last wrote in pins 0 and 1 when the UART is in use, not what's on the pins.

# Answer
> 1 votes
See the datasheet: **14.3.3 Alternate Functions of Port D**

> * TXD/PCINT17 – Port D, Bit 1 TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
> PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
> * RXD/PCINT16 – Port D, Bit 0 RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.
> PCINT16: Pin Change Interrupt source 16. The PD0 pin can serve as an external interrupt source.

So basically if you turn on the USART the pins are configured as input/output regardless of DDRD.

---

> but get a bit uneasy when I'm not sure whether I expect magic to be happening under the hood or not.

It's not the IDE - it's the underlying hardware.

---

> This means the readback of the DDRD contents is a lie.

No it isn't. The hardware is ignoring DDRD in those bits. See this example:

```
void setup()
{

DDRD = 0;
byte a = DDRD;
DDRD = 0xFF;
byte b = DDRD;

Serial.begin (115200);

DDRD = 0;
byte c = DDRD;
DDRD = 0xFF;
byte d = DDRD;
Serial.end ();

Serial.begin (115200);
Serial.print ("a = ");
Serial.println (a);
Serial.print ("b = ");
Serial.println (b);
Serial.print ("c = ");
Serial.println (c);
Serial.print ("d = ");
Serial.println (d);
}

void loop()
{
}

```

Output:

```
a = 0
b = 255
c = 0
d = 255

```

The code is setting DDRD and reading it back as set. However the hardware is ignoring those bits because of the alternative use of those ports.

---
Tags: serial
---


# Question
Title: AVR timer overflow interrupt not working
My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0\_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:

```
void timer0_init( void )
{
    cli();
    TCCR0B |= 3;    //clock select is divided by 64.
    TCCR0A |= 2;    //sets mode to CTC
    OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
    TIMSK |= 2;     //Enable overflow interrupt
    sei();          //enable global interrupts
}

```

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.

```
ISR(TIMER0_OVF_vect)
{
    cli();
    //ticks ++;
    PORTB |= ( 1 << PORTB0 );
    sei();
}

```

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with `PORTB |= ( 1 << PORTB0 );` which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on. Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement `PORTB |= ( 1 << PORTB0 );` in my infinite loop and confirmed the LED came on)

For further explanation, here is my main.c:

```
/*================================= main.c =================================*/

#define F_CPU   8000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "timer.h"
#include "hardwareInit.h"

int main(){

    //Initialize hardware HERE
    DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

    SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

    timer0_init();          //set up timer0 for 1 ms overflow

    while(1)
    {
        /* if( getTicks() > 0 )
        {
            PORTB |= ( 1 << PORTB0 );
            _delay_ms(1000);
            PORTB &= ~( 1 << PORTB0 );
            _delay_ms(1000);
        } */

    }
    return 0;
}

```

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.

Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.

# Answer
You are misunderstanding what an overflow interrupt is. That is called when the timer overflows (ie. it reaches TOP which in the case of an 8-bit timer is 255). Since you are counting to 124 that will never happen, and thus the interrupt will not fire.

You want the "compare A vector" which is called when the "A" register compares to the limit. Example code:

```
void timer0_init( void )
{
    TCCR0B = bit (CS01) | bit (CS00);    //clock select is divided by 64.
    TCCR0A = bit (WGM01);     //sets mode to CTC
    OCR0A = 0x7C;             //what to count to
    TIMSK = bit (OCIE0A);     //Enable compare match A interrupt
}

ISR(TIMER0_COMPA_vect)
{
    PINB = bit (PINB0);   // toggle pin 5
}

int main(){

    DDRB |= bit (DDB0);    //set this pin as an output for an LED
    timer0_init();         //set up timer0 for 1 ms overflow
    sei ();                // allow interrupts
    while(true) { }        // forever
    return 0;
}

```

I changed it to toggle pin 5 (which happens extremely quickly) so it will seem to be on but a bit dim. You can see on an oscilloscope or logic analyzer that it is toggling rapidly.

You don't need to turn interrupts off or on inside an ISR. You are better off using the bit names rather than "magic numbers" in your code, as my example shows.
> 5 votes

---
Tags: c, interrupt, attiny, avr
---


title: Arduino and industrial stepper driver

text:
# Question
Title: Arduino and industrial stepper driver
For a project I need to use an industrial stepper driver with an arduino. There it is: http://www.omc-stepperonline.com/bipolar-stepper-motor-driver-max-4a-current-40vdc-input-16-subdivision-st6600-p-246.html

The motor: https://prototypes.haydonkerk.com/ecatalog/hybrid-linear-actuators/en/linear-actuator-57F42-3.25-099#

I'm not familiar with this driver, so can I use it with the Arduino Stepper Library?

I didn't see a lot of tutorial for this driver compared to many other popular driver.

Thanks!

# Answer
Absolutely you can. Looking at the picture, this is set up for bipolar and a unipolar motor. There you have to wire according to the wire diagram.
> 1 votes

---
Tags: arduino-mega, stepper
---


# Question
Title: How to use web data from GSM Sim900 to be used as input for Arduino?
I have a GSM Sim900 connected to an Arduino Uno. I'm successfully able to use HTTP READ commands to show data from the web on the Arduino's serial monitor. It is showing complete HTML from that URL on the serial monitor.

Now, how should I filter data from the web? I mean I just want to display selected numbers in the serial monitor and not the complete HTML.

And secondly, how should I store these numbers into a variable so I could use them as input data for Arduino?

Thank you.

# Answer
You should read the manual. More specifically the "Sim900 AT reference". I've found it on a russian server (https://www.google.nl/url?sa=t&source=web&rct=j&url=http://wiki.amperka.ru/\_media/%25D0%25BF%25D1%2580%25D0%25BE%25D0%25B4%25D1%2583%25D0%25BA%25D1%2582%25D1%258B:gprs\_shield:gprs-shield\_sim900\_at\_commands.pdf&ved=0ahUKEwinze2Tp7fQAhWBMSYKHQFkBh0QFghEMA0&usg=AFQjCNGKd5Uohe7CmcJcIc1Am-SKdRsWXg&sig2=XIsvvkLWHs60sTo7FZ7tWw) but you may want to try and get it directly from the manufacturer.

In the datasheet, it will explained what values are allowed with the "at+httpread" command. You can actually specify which part you want to read. This is usefull when your Arduino can't parse the complete page.

If you have control over the page, you may also generate a device-friendly page consisting of key-value pairs, instead of it being a whole HTML page.
> 1 votes

# Answer
What about RapidXml? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments so might work here. Boost software license means source is freely available. http://rapidxml.sourceforge.net.

The other way to go is just parsing out the numbers with string manipulation.
> 0 votes

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


# Question
Title: 4 IR sensors on Arduino pro micro. 2 are working other aren't
```
#include <Keyboard.h>
int IRpin = 5;
int IRpin2 = 6;
int IRpin3 = 8;
int IRpin4 = 9;
int led = 13;

void setup() {
  Serial.begin(9600);
  //start the serial port
  Keyboard.begin();
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  float volts = analogRead(IRpin);
  Serial.println("volts1:");
  Serial.println(volts);
  delay(1000);
  if (volts>500.00){
    Keyboard.press(KEY_RIGHT_ARROW);
    Keyboard.releaseAll();
  }
  float voltss = analogRead(IRpin2);
  Serial.println("volts2:");
  Serial.println(voltss);
  delay(1000);
  if (voltss>600.00){
    Keyboard.press(KEY_LEFT_ARROW);
    Keyboard.releaseAll();
  }
  float voltsss = analogRead(IRpin3);
  Serial.println("volts3:");
  Serial.println(voltsss);
  delay(1000);
  if (voltsss > 500.00) {
    Keyboard.press(KEY_UP_ARROW);
    Keyboard.releaseAll();
  }
  float voltssss = analogRead(IRpin4);
  Serial.println("volts4:");
  Serial.println(voltssss);
  delay(500);
  if (voltssss > 600.00) {
    Keyboard.press(KEY_DOWN_ARROW);
    Keyboard.releaseAll();
  }
}

```

I connected 4 IR infrared sensors to Pro micro and only 2 of them are working. The other 2 are sending random values. Connection for all 4 IR sensors.: IR VCC-\>Arduino VCC IR GND -\> Arduino GND Output-\> 5,6,8,9

# Answer
Pin 5 is not analog pins.

On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.

Just use the A0-5 pins instead, as that will work on any Arduino.
> 1 votes

---
Tags: arduino-ide, pwm, arduino-pro-micro
---


# Question
Title: Can an AT89S52 be programmed using an Arduino as ISP?
Since the AT89S52 controller is ISP programmable is it possible to use an Arduino UNO as a programmer to upload the hex file to the 8952 ?

I've tried various programmer softwares such as progisp, 8051 loader and ISP Prog v1.4 but the Arduino doesnt show up as a programmer on any of these. I've uploaded the ArduinoISP sketch on the UNO and then tried to program the 8952 without any luck.

According to my understanding the ISP programmers use an ATMega8 ,so is what I'm trying to do possible or do I need to purchace an ISP programmer ?

# Answer
> 1 votes
You should be able to use the Arduino as an ISP since an ISP is basically just a serial to SPI interface. If you are trying to use the arduino software to upload your program, you will need to edit your boards.txt file to be able to talk to the chip. If you are just using avrdude you will need to update your avrdude.conf. AVR Freaks has a post on someone trying something similar and may be of some help. Without knowing your environment it's difficult to give more specific advice

# Answer
> 1 votes
You might be able to use the programmer sketch I wrote a while back (it runs on a Uno). You need an SD card interface so it can read the .hex file for programming. See: http://www.gammon.com.au/uploader

You connect things up roughly like this (Atmega328P shown, your wiring would be different at the target chip side):

You would need to modify the sketch to add the details for the AT89S52. As far as I can make out from the datasheet:

* Signature: 0x1E 0x52 0x06
* PROGMEM: 8k bytes
* RAM: 256 bytes
* Pinouts: Depending on the chip package. You need to identify MOSI/MISO/SCK/RESET along with Vcc and Gnd.
* Fuses: None that I can see
* Flash page size: 256 bytes

Thus you could modify the table of chips to add that one, along these lines:

```
// see Atmega datasheets
const signatureType signatures [] PROGMEM =
  {
//     signature        description   flash size   bootloader  flash  fuse
//                                                     size    page    to
//                                                             size   change

  // AT89S52
  { { 0x1E, 0x52, 0x06 }, "AT89S52",   8 * kb,           0,   256,   NO_FUSE },

// ... other ones here ...

```

I haven't got an AT89S52 to test it on, so I can't say for sure I got those parameters right. I am assuming that the programming instructions for ICSP programming are the same as for the other chips in their range.

---

# Answer
> -1 votes
If you haven't been successful yet, Try this.(assuming it's still not solved.)

I'm using Arduino to successfully program the AT89S52. Need 2 tools: Arduino program and an AT89S52 programmer software. Here's a complete tutorial on how to do it. Works on Windows, not so sure about linux. http://www.instructables.com/id/ARDUINO-AS-A-8051-PROGRAMMER/?ALLSTEPS

---
Tags: arduino-uno, isp, programmer, arduinoisp
---


title: Simultaneous output from sonar array

text:
# Question
Title: Simultaneous output from sonar array
I am working on a project that records the elevation changes of a 1 foot wide section using sonar distance measurement. I have 10 HC-SR04 sensors arranged in a straight line over this 1 foot section.

The issue I am having is that when I send an output from my sonar sensor, I must wait until the return signal is recorded before I can trigger the next sonar sensor to take a measurement. This is rather slow and decreases the sampling frequency significantly. I need each sonar sensor to take 1000 measurements per second for my project.

Is there a way to have the HC-SR04 sensors simultaneously output and listen for the return signal? I would want all 10 sensors to send a 40 kHz pulse at the same time, and then when a return signal is recorded, another 40 kHz pulse is sent out.

The average distance to the 1 foot wide section is about 11 inch. If the Arduino is limited and there are other control boards that can accomplish this, it would help a lot if you can point me in the right direction.

# Answer
> 7 votes
1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.

According to SRF-04 Documentation,

**(1)**

> If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, **time slot for each reading is 36 mS** ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = **360 Sec**.

**(2)**

> I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. **But**,  According to the timing diagram, 1 cycle minimum period consist of :

1. 100 us Trigger pulse ==\> 0.0001 s
2. 8 Cycle burst at 40 kHz = (1/40000)\*8 s ==\> 0.0002 s
3. 100 us Echo pulse ==\> 0.0001 s
4. 10 ms delay time ==\> 0.01 s

Total for 1 cycle is 0.0104 s, so for **1000 readings x 10 sensors (object to detect is present) will be 104 s**.

All sensor burst at the same frequency, great idea. **However** it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

1. 100uS for 10 sensors trigger pulse at once ==\> 0.0001 s
2. 8 Cycle burst at 40 kHz = (1/40000)\*8 s ==\> 0.0002 s
3. 100 us (minimum) Echo pulse --\> 0.0001 s x 10 sensors ==\> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
4. 10 ms delay time ==\> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, **1000 readings : 11.3 s**

**(3)**

"How about changing the beam pattern?"

> **Changing beam pattern and beam width**
> You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.

---
Tags: arduino-uno, hc-sr04
---


title: arrange vector in descending order

text:
# Question
Title: arrange vector in descending order
im trying to arrange the vector in descending order but its not happening..

```
int fibonacci[15]={0, 1};
int a=0;

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

  for (int i=0; i<=14; i++) //loop to create the array
  {
    fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
  }

  //Now arrange in descending order
  for (int i=0; i<16; i++)
  {
    for (int j=i+1; j<16; j++)
    {
      if (fibonacci[i]>fibonacci[j])
      {
        a=fibonacci[i]; //mux number
        fibonacci[i]=fibonacci[j];
        fibonacci[j]=a;
      }
    }
  }

  for (int k=0; k<16; k++)
  {
    Serial.println(fibonacci[k]);
  }
}

void loop() {
}

```

# Answer
> 2 votes
I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :

```
/*
  SORTING IN DESCENDING ORDER
*/

const int nbElem = 15; // 24 max
int fibonacci[ nbElem ] = { 0, 1 };

void createFibonacciArray( int inputArray[], int arraySize )
{
  fibonacci[ 0 ] = 0;
  fibonacci[ 1 ] = 1;
  for( int i=0; i<nbElem-2; i++ )
    fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
}

void displayArray( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize; i++ )
    Serial.println( inputArray[ i ] );
}

void displayArrayReverse( int inputArray[], int arraySize )
{
  for( int i=arraySize-1; i>=0; i-- )
    Serial.println( inputArray[ i ] );
}

void reverseArray( int inputArray[], int arraySize )
{
  for( int i=0; i<nbElem/2; i++ )
  {
    int fTemp = fibonacci[ i ];
    fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
    fibonacci[ nbElem-i-1 ] = fTemp;
  }
}

void inverseBubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] < inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

void bubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] > inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

void setup()
{
  Serial.begin( 115200 );

  // Create and display Fibonacci array
  createFibonacciArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI ARRAY\n" );
  Serial.print( "===============\n" );
  displayArray( fibonacci, nbElem );

  // Solution 1: Display array starting from the end
  Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
  Serial.print( "=====================================\n" );
  displayArrayReverse( fibonacci, nbElem );

  // Solution 2: Reverse array
  reverseArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
  Serial.print( "========================\n" );
  displayArray( fibonacci, nbElem );

  // Solution 3: Inverse bubble sort array
  createFibonacciArray( fibonacci, nbElem );
  inverseBubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
  Serial.print( "====================================================\n" );
  displayArray( fibonacci, nbElem );

  // Ascending order sort array
  bubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
  Serial.print( "=================================\n" );
  displayArray( fibonacci, nbElem );
}

void loop()
{}

```

# Answer
> 1 votes
You can use it using bubble sort algorithm (which is most simple but inefficient)

```
int fibonacci[15]={0, 1};
int a=0;

int arraysize=2; // variable to store size or array

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

  for (int i=0; i<=14; i++) //loop to create the array
  {
    fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
    arraysize++;
  }

  //Now arrange in descending order using bubble sort
  for (int i=0; i<arraysize; i++)
  {
    for (int j=0; j<arraysize-1; j++)
    {
      if (fibonacci[j]<fibonacci[j+1])
      {
        a=fibonacci[j+1]; //max number
        fibonacci[j+1]=fibonacci[j];
        fibonacci[j]=a;
      }
    }
  }
  //------------------------------------------------

  for (int k=0; k<16; k++)
  {
    Serial.println(fibonacci[k]);
  }
}

```

---
Tags: array, vector
---


# Question
Title: Same code in setup() and loop() give different results
As the answers to this question and this one state, `setup()` and `loop()` are identical in the way they execute code (apart from the obvious looping function of `loop()`).

However.

I get different results with following two pieces of code:

### Code run once, in `setup()`

```
/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

void setup() {
    LED.setOutput(13); // Digital Pin 13

    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
}

void loop() {
}

```

### Code run once, in `loop()`

```
/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

bool hasBeenSet = false;

void setup() {
    LED.setOutput(13); // Digital Pin 13
}

void loop() {
  if (hasBeenSet == false){
    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
    hasBeenSet = true;
  }
}

```

### The difference:

The code run in `setup()` makes the LED *flash once* with the desired color.
The code run in `loop()` makes the LED *stay lit* with the desired color.

With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the `loop()` version I can even disconnect the data line after the color has been set, and it will stay lit.

I can only conclude the same code is executed differently in both cases.

Is there some sort of (soft) power reset after `setup()`? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

---

Link to the library used: http://github.com/cpldcpu/light\_ws2812

# Answer
After some discussion it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

* There was some initial confusion (see the edits) where the `hasBeenSet` flag was initialized the wrong way around.
* I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
* Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
* Possibly faulty WS2812 chip - try with another one.
* Possibly faulty Arduino - try with another one.
* Possibly Arduino running at the wrong clock speed which would throw the timings out.
* Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
* Possible bug in the library. We eliminated that by trying with my library for Neopixels.

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.

We never really worked out why doing it in `loop` rather than `setup` made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.

I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.
> 2 votes

# Answer
As you can see in the source code there is really nothing going on between the setup call and the first loop iteration.

If I'm not mistaken, this type of LED needs a frequent "update" on which color to display, at a precisely timed interval (I suppose this gets more important the more LEDs you have, since they are "addressed" bases on this signal timing.)

I think you really should keep calling `sync()` in the loop even if you are not actually changing the desired color, to keep "refreshing" the LED. This is just based of a quick analysis of the library code and examples though.

Why you get different results in the samples below could simply be due to the LED randomly "settling" in two different states when no longer getting data. The chst conversation seems to indicate there may have been other reasons as well.
> 1 votes

---
Tags: arduino-ide, arduino-pro-mini, rgb-led, neopixel
---


# Question
Title: Arduino code for continuous rotation for 3 servos with Bluetooth
This code is working, any ideas?

Please check the code - Bluetooth is connecting but the servo motors are not varying with respect to the app sliders.

```
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo2 = realservo;
      servo2 = map(servo2, 1000, 1360, 0, 360);
      myservo2.write(servo2);
      Serial.println("servo 2 On");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo3 = realservo;
      servo3 = map(servo3, 1000, 1360, 0, 360);
      myservo3.write(servo3);
      Serial.println("servo 3 On");
      delay(10);
    }
  }
}

```

# Answer
> 1 votes
pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1 and then use software serial as well.

If you do want to use softwareserial try this code https://gist.github.com/emil01/afedff4c3ba4625ebc75 Here i am using pins 2 & 3.

If you do not want to use software serial you can try this code https://gist.github.com/emil01/9a89800e383ec7f95b3f

In your code

```
  if (bluetooth.available() >= 2 )
  {
   unsigned int servopos = bluetooth.read();
   unsigned int servopos1 = bluetooth.read();

```

You are performing 2 consecutive read functions, this is not ideal as there can be data loss. A more ideal solution would be send a string with known string terminators and then parsing this string to get your required data.

For e.g. you could send

> S1:90\nS2:180\n

from this string you can clearly figure out the start and end of the string and accordingly manipulate the data for your need

# Answer
> 1 votes
As pointed by @evolutionizer , you can't do SoftSerial + Serial (native) from pin 0 and pin 1. So the setup should be like this:

```
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 2;
int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup USB serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

```

As for the movement for the servo, more information about data sent from Android is needed.
If the app is sending continuous value instead of sending only if the value is changed, you can do this trick:

```
unsigned int lastpost;
void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360 && realservo!=lastpost) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10); //delay to wait servo rotate to desired position
      lastpost = realservo;
    }
...
  }
...
}

```

---
Tags: arduino-uno, bluetooth, servo
---


# Question
Title: SPI Overflow in 328 slave with i2c sensor
I am working on creating sensor poller that is going to be polling multiple sensors and then, on request, provides its data to the master.

The master polls the slave (SPI) at 50hz and the slave is polling it's sensor (BNO055) (I2C) at 100hz.

The transaction works most of the time but every once in a while it returns an overflow.

Any ideas why this might occur?

Slave code:

```
/*************************************************************************
 *
 * objeeAirlines
 * __________________
 *
 *  Written by Julian Blanco
 *
 *  Spi slave code written by
    Nick Gammon
    February 2011
 */

#include "Adafruit_BNO055.h"

float yawInput=0;
float yawOffset=0;
float pitchInput=0;
float rollInput=0;

int calibration=0;

volatile byte command = 0;
Adafruit_BNO055 bno = Adafruit_BNO055();

void setup (void)
{

  if(!bno.begin())while(1){};
  bno.setExtCrystalUse(true);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  union first_union{
    float f;
    byte b[4];}
  data;

  byte c = SPDR;

  data.f = yawInput;

  command = c;

  switch (command)
  {
  // no command? then this is the command
  case 0:

    SPDR = 0;
    break;

  // incoming byte, return byte result
  case 'a':

    SPDR = data.b[0];
    break;

  // incoming byte, return byte result
  case 'b':

    SPDR = data.b[1];
    break;

  // incoming byte, return byte result
  case 'c':

    SPDR = data.b[2];
    break;

  // incoming byte, return byte result
  case 'd':

    SPDR = data.b[3];
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect
float tiempo=millis();
void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH) command = 0;

    if(millis()>(tiempo+10))
    {
      tiempo=millis();
      SampleGyro(bno);
    }

}  // end of loop

void SampleGyro(Adafruit_BNO055 &gyroIMU){
    /* Display the floating  point data */
    imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
    yawInput=euler.x()-yawOffset;

    if (yawInput >= 360)
    {
          yawInput -= 360;
        }
    else
    {if (yawInput < 0)yawInput += 360;
    }
    pitchInput=euler.y();
    //rollInput=fmod((euler.z()+(360+90)), 360)-180;
    rollInput=euler.z();
    uint8_t system, gyro, accel, mag = 0;
    gyroIMU.getCalibration(&system, &gyro, &accel, &mag);
    calibration=system;
}

```

Master Code:

```
#include <SPI.h>

#define SS 10
void setup (void)
{
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(SCK, OUTPUT);
    pinMode(SS, OUTPUT);

  Serial.begin (115200);
  Serial.println ();

  digitalWrite(SS, HIGH);

  SPI.begin ();

  SPI.setClockDivider(SPI_CLOCK_DIV8);
}

  byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (10);
  return a;
}

  union first_union{
    float f;
    byte b[4];}
  data;

void loop (void)
{

  digitalWrite(SS, LOW);

  transferAndWait ('a');

  data.b[0] = transferAndWait ('b');
  data.b[1] = transferAndWait ('c');
  data.b[2] = transferAndWait ('d');
  data.b[3] = transferAndWait (0);

  digitalWrite(SS, HIGH);

  Serial.print("data.f = ");Serial.println(data.f);

  //Serial.print("data.b[0] = ");Serial.println(data.b[0]);
  //Serial.print("data.b[1] = ");Serial.println(data.b[1]);
  //Serial.print("data.b[2] = ");Serial.println(data.b[2]);
  //Serial.print("data.b[3] = ");Serial.println(data.b[3]);

  delay(10);
}

```

# Answer
It is likely that your SPI interrupt on the slave is firing in the middle of updating your global `yawInput` variable. This would cause the value to be partially updated when you send it back to the master. You might even be sending part of the old value and part of the new value back to the master. It depends on when the interrupts fire.

You need to lock your `SampleGyro` function somehow. The easiest way would be to disable interrupts when modifying any interrupt accessible variables (i.e. `yawInput`).

Something like this should tell you if the interrupt timing is the issue:

```
void SampleGyro(Adafruit_BNO055 &gyroIMU){
    /* Display the floating  point data */
    imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
    uint8_t system, gyro, accel, mag = 0;
    gyroIMU.getCalibration(&system, &gyro, &accel, &mag);

    // Disable interrupts while modifying the global variable
    noInterrupts()
    yawInput=euler.x()-yawOffset;
    if (yawInput >= 360) {
          yawInput -= 360;
    } else if (yawInput < 0) {
          yawInput += 360;
    }
    pitchInput=euler.y();
    //rollInput=fmod((euler.z()+(360+90)), 360)-180;
    rollInput=euler.z();
    calibration=system;
    // re-enable interrupts once your global variable
    // modification is done.
    interrupts();
}

```

It's also worth noting that you want to put as little code between the `noInterrupts()` and `interrupts()` calls as possible. Things like I2C and SPI and basically any other communication will likely not work inside of that block. I rearranged your `SampleGyro` function to put all calls to the gyro outside of the lock. This is to prevent the sensor reading from failing.
> 1 votes

---
Tags: arduino-uno, sensors, i2c, spi, debugging
---


# Question
Title: Simulation of IoT based systems in Software
Thank you for reading this.

Generally there are libraries for GSM and Ultrasound sensors for the software called Proteus and you can simulate them along with you MCU and the interfacing peripherals and simulate .

I have big problem at my hand , I want to simulate ESP8266 or any other relevant wifi module with my Arduino (Simulation Libraries for Arduino are available ) and get the data from sensor , all in software . Then , I want the wifi device (in software ) to show an ip address , so that I can log the data to an online cloud .

The software and module does not have to be specific , I want to know , If there are any professional software that let you simulate IoT based systems.

I'am new to IoT designing and I'am always comfortable with simulating everything.

If you have any other similar guide on how to design and simulate IoT systems , Let me know .

Have a great day

# Answer
There are tools to simulate Arduino, but it's not meant for anything beyond basic (i.e. simple circuit). Support is limited, you can't just simulate any and every sensor and shields (e.g. LAN, Wireless). Furthermore, ESP8266 is so cheap that hardly anybody has actual use-case to simulate them. I suggest you work on a real device =)

If you need to simulate data stream into your cloud or IoT platform, I suggest you just spin up a machine and run some code to generate data.
> 2 votes

# Answer
I don't know of any simulators, but you might be able to do it yourself.

What you could do is to add a hardware abstraction layer to your code. When you are running on hardware this just passes the calls to the hardware, i.e. `HAL_digitalRead(D0)` calls `digitalRead(D0)`. When you want to simulate the hardware then you #ifdef the simulated code in and it calls {return DigitalPins\[GetIndexFromPinName('D0')\]; }

The theory is very simple but I don't think its an easy task. I am surprised someone hasn't done it already, because debugging in Visual Studio or GDB in pure software would be much easier than doing it on the hardware.

I've never use Proteus, so I don't know if that will fit in with how that works at all.
> 0 votes

---
Tags: arduino-mega, wifi, simulator
---


# Question
Title: two dimensional array with 3 characters per entry?
my plan is to create a two dimensional array with 3 characters in each cell.

what i have tried:

```
char keys[3][8][8] = {
  {' ','4','5','6','x','/',' ',' '},
  {'x10','7','8','9',' ',' ',' ',' '},
  {'.','rcl','eng','(',')','sd','m+','^2'},
  {'0','(-)','..,,','hyp','sin','cos','tan','hyp'},
  {' ','br','wur','^2','^x','log','ln',' '},
  {' ',' ',' ',' ',' ','mode','log',' '},
  {'=',' ',' ',' ',' ',' ','^3',' '},
  {'=','1','2','3','+','-',' ',' '}
};

```

unfortunatelly this gives me the error:

> error: too many initializers for 'char \[3\]\[8\]\[8\]'

so what is wrong?

# Answer
> 1 votes
> error: too many initializers for 'char \[3\]\[8\]\[8\]'

The order is wrong:

```
char keys[8][8][3]

```

But then some of the literals are larger than int and give a warning as they are truncated.

Easiest is to define as string literals:

```
const char* keys[8][8] = {
  {" ","4","5","6","x","/"," "," "},
  {"x10","7","8","9"," "," "," "," "},
  {".","rcl","eng","(",")","sd","m+","^2"},
  {"0","(-)","..,,","hyp","sin","cos","tan","hyp"},
  {" ","br","wur","^2","^x","log","ln"," "},
  {" "," "," "," "," ","mode","log"," "},
  {"="," "," "," "," "," ","^3"," "},
  {"=","1","2","3","+","-"," "," "}
};

```

This can be further improved (stored in program memory, etc).

Cheers!

---
Tags: string, array
---


# Question
Title: Connection between ATTiny85 and RaspberryPi3 with nRF24L01+
I'm hoping someone can help me since I've been struggling with this all weekend. I've got 2 nRF24L01+ breakout cards and I'm trying to send data from a ATTiny85 to a Raspberry Pi 3.

My setup is (the attiny85 breadboard has a 3.3V power supply):

And the code I'm testing is for the ATTiny85:

```
#define CE_PIN 3
#define CSN_PIN 4

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

const byte addr[6] = "00001";
int count = 0;

void setup() {
  radio.begin();
  radio.openWritingPipe(addr);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop(void){
  radio.write( &count, sizeof(count) );
  count++;
  delay(1000);
}

```

And for the Raspberry Pi 3:

```
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz
RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

// Radio pipe addresses for the 2 nodes to communicate.
const uint8_t addr[6] = "00001";

int main(int argc, char** argv){
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(1, addr);
  radio.startListening();

  // Dump the configuration of the rf unit for debugging
  radio.printDetails();

  int count = 0;

  while (1)
  {
    while ( radio.available() )
    {
      radio.read( &count, sizeof(count) );
      printf("Count: %d\n", count);
    }
    sleep(1);
  }

  return 0;
}

```

# Answer
> 2 votes
As Mikael Patel pointed out, my MOSI and MISO pins were switched.

On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.

---
Tags: nrf24l01+, raspberrypi
---


# Question
Title: Arduino UNO Chinese Clone LEDs not lighting up
Hi all,

In the screenshot of a circuit I've included, I'm attempting to light up 4 LEDs off of pin 2. In circuits.io, everything works great. 3 blue LEDs and 1 red LED light up and blink as planned. When I create this same circuit on a Arduino Uno Chinese clone, IF the LEDs are all blue, they all light up and blink. If I change one of them to red, yellow, or green, ONLY the red, yellow, or green one lights up. The three blue LEDs no longer light up. It also doesn't seem to matter, where the off blue LED is put.

Not sure what's wrong.

# Answer
Use one resistor per led, not one for all of them.

This is because different color leds have different forward voltages. Red requires a lower voltage to light up. So it will guzzle up all available current, while the blue leds are waiting for the voltage to go higher (which never happens).
> 7 votes

---
Tags: arduino-uno
---


# Question
Title: ArduinoUNO/MEGA, Is there a way to exceed 256 in analogWrite
I am using Arduino UNO/MEGA, I want to

```
analogWrite(pin, val);

```

where the value is 0-1023.

How can I make that ?

Thanks.

# Answer
> 12 votes
Section 16, "16-bit Timer/Counter1 with PWM" of *Atmel-8271J-AVR- ATmega-Datasheet\_11/2015* describes using Timer/Counter-1 for 16-bit PWM, including sample code in both C and assembler. It might take a couple of reads over that section to get familiar with the hardware and learn what else T/C-1 is used for, and that you might have to give up while using it for PWM, but the code is fairly straightforward.

Using this T/C would give you 2-bits more resolution in your PWM output than mapping onto an 8-bit counter, if that is what your project needs.

+1 for the question. Not having needed PWM output for anything more than a demo with my DMM (yet), it hadn't occurred to me to look for a higher resolution until now.

# Answer
> 9 votes
The simplest way is to change your value range to 0-255. You can't change analogWrite's range, since that is fixed in the core software.

```
analogWrite(5, val >> 2);

```

The `>> 2` bit-shifts the value two bits to the right, turning a 10-bit value (0-1023) into an 8-bit value (0-255). It's by far the most efficient way of dividing by 4.

On more complex 32-bit boards, like the Arduino Due, or the chipKIT range of boards, etc, you have the function analogWriteResolution() which can change the range, but that cannot be done on the 8-bit boards.

From what I have read online it looks like the ATMega chips may support higher resolutions for PWM - however there is no support in the core for that. If you need a higher resolution for some specific reason then you will need to program the registers manually yourself and not rely on the Arduino API to do the work for you. For that you will need to consult the datasheet for your chosen chip.

# Answer
> 5 votes
I agree with @Majenko's answer, though here is a more "beginner" friendly method of doing the same.

```
val = map(val,0,1023,0,255);
analogWrite(pin, val);

```

Not the most efficient, but still...

# Answer
> 2 votes
The other questions so far have correctly addressed one possible meaning of this question, "how can I increase the resolution?" Here's another possible interpretation.

# How can I increase the output magnitude?

It sounds like you might want to output a higher maximum voltage than what you get from using `analogWrite(pin,255)` on the Uno or Mega. This is not possible using the Arduino by itself, because PWM represents a fraction of the maximum output, not an absolute value.

On the Uno and Mega, that maximum output is 5V, so the approximate values come out to:

```
analogWrite(pin,0);   // (0 / 255) * 5V   (0% of 5V == 0V)
analogWrite(pin,127); // (127 / 255) * 5V (50% of 5V == 2.5V)
analogWrite(pin,255); // (255 / 255) * 5V (100% of 5V == 5V)

```

If you want to make a higher absolute voltage, you will need an external power source and a method of translating the 0-5V output into another voltage range. This is called "level shifting" and there are standalone ICs which can do this job. Motor drivers and H-Bridge devices utilize this principle as well.

If you use some sort of level shifting circuitry, then you can map the analogWrite to a different range, such as 0-20V:

```
analogWrite(pin,0);   // (0 / 255) * 20V   (0V)
analogWrite(pin,127); // (127 / 255) * 20V (10V)
analogWrite(pin,255); // (255 / 255) * 20V (20V)

```

---
Tags: arduino-uno, arduino-mega, pwm, frequency
---


title: Arduino and C++ Serial communication

text:
# Question
Title: Arduino and C++ Serial communication
I am using this header: http://playground.arduino.cc/Interfacing/CPPWindows

My main:

```
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"
#include <string>

int main(int argc, _TCHAR* argv[])
{
    Serial* SP = new Serial("\\\\.\\COM4");

    if (SP->IsConnected())
        printf("We're connected\n");

    std::string tryStr;
    int value;
    DWORD bytesSend;

    /* Loop */
    while(SP->IsConnected())
    {
         /* Take a value from user */
         printf("Value: "); scanf("%d",&value);

         /* Send Arduino */
         BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

        /* I have no idea what is this for? (SP->status.cbInQue) */
        ClearCommError(SP->hSerial, &SP->errors, &SP->status);

        /* Read string from arduino */
        DWORD bytesRead;
        tryStr.assign("");
        bool check = true;
        char tempCharacter;
        while (check==true){

            ReadFile(SP->hSerial, &tempCharacter, sizeof(char), &bytesRead, NULL);
            tryStr += tempCharacter;

            if(tempCharacter == '$'){
                check = false;
            }
        }

        /* Print the string */
        std::cout << tryStr  << std::endl << std::endl ;
    }
    return 0;
}

```

My Arduino Code:

```
int LedPin= 10;
int value;
String  incomingData = "hello$";

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

void loop (){

  while(!(Serial.available() > 0)){
    /*Wait until take data */
  }

  value=Serial.read();

  if (value == 20)
  {
      digitalWrite (LedPin, HIGH);
      incomingData.setCharAt(0,'o');
      incomingData.setCharAt(1,'p');
      incomingData.setCharAt(2,'e');
      incomingData.setCharAt(3,'n');
      incomingData.setCharAt(4,'n');

      Serial.print(incomingData);
  }
  else if (value == 15)
  {
      digitalWrite (LedPin, LOW);
      incomingData.setCharAt(0,'c');
      incomingData.setCharAt(1,'l');
      incomingData.setCharAt(2,'o');
      incomingData.setCharAt(3,'s');
      incomingData.setCharAt(4,'e');

      Serial.print(incomingData);
  }

}

```

This code works perfectly. Output:

> We're connected Value: 20 openn$
>
> Value: 15 close$
>
> Value: 20 openn$
>
> Value: 20 openn$
>
> Value: 15 close$
>
> Value: 15 close$
>
> Value: 20 openn$

But now I want to add another condition in my Arduino code:

```
int LedPin= 10;
int value;
String  incomingData = "hello$";

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

void loop (){

  while(!(Serial.available() > 0)){
    /*Wait until take data */
  }

  value=Serial.read();

  if (value == 20)
  {
      digitalWrite (LedPin, HIGH);
      incomingData.setCharAt(0,'o');
      incomingData.setCharAt(1,'p');
      incomingData.setCharAt(2,'e');
      incomingData.setCharAt(3,'n');
      incomingData.setCharAt(4,'n');

      Serial.print(incomingData);
  }
  else if (value == 15)
  {
      digitalWrite (LedPin, LOW);
      incomingData.setCharAt(0,'c');
      incomingData.setCharAt(1,'l');
      incomingData.setCharAt(2,'o');
      incomingData.setCharAt(3,'s');
      incomingData.setCharAt(4,'e');

      Serial.print(incomingData);
  }
  else{                                      // new line added
                                             // new line added
      incomingData.setCharAt(0,'g');         // new line added
      incomingData.setCharAt(1,'g');         // new line added
      incomingData.setCharAt(2,'g');         // new line added
      incomingData.setCharAt(3,'g');         // new line added
      incomingData.setCharAt(4,'g');         // new line added
                                             // new line added
      Serial.print(incomingData);            // new line added
  }                                          // new line added

}

```

But it didn't work. ScreenShot:

What went wrong? The led blinked correctly but the output string is wrong.

# Answer
> 1 votes
```
BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

```

You're writing `sizeof(value)` bytes to the Arduino. Since `value` is an `int`, which is typically 4 bytes in size for PC compilers/processors, when you send `20`, what actually gets to the Arduino is 0x00000014. Your processor is apparently little-endian so the order of bytes sent is `0x14, 0x00, 0x00, 0x00`.

You're reading a single byte in every `loop()` iteration. Your first sketch worked because you didn't provide any `else` clause for unrecognized bytes. The Arduino merely ignored those leading zeros. However, your second sketch handled unknown bytes (such as 0x00) by printing `gggg`. So what you get for every value you send to the Arduino is exactly what you'd expect and what you see in your shell -- the result you want (`openn` == 0x14), followed by 3 gibberish results (because of the leading zero bytes).

You can fix it by either declaring `value` as a `uint8_t` in your CPP code (after including `stdint.h`) or only reading chunks of 4 bytes on the Arduino and then parsing what you get. The former solution seems more reasonable/reliable.

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


# Question
Title: My RTC DS1307 isn't returning any information. It seems to be stuck in the isrunning() function. Does anyone have debugging tips?
I'm using an RTC DS1307 to keep track of time for long periods. It seems to be stuck in a function. I'm using the RTClib suggested by adafruit.

How can I get it unstuck and get values returned? Are there any debugging or troubleshooting tips that would be helpful?

Referencing this excerpt for the code I'm running.

```
void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

```

This is the example code modified slightly to increase logging, included with RTClib. It's for the DS1307.

Currently the output from the serial port is as follows:

> RTC is found.

I changed the code to the below:

```
    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

      Serial.begin(9600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      } else {
        Serial.println("RTC is found.");
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      } else {
        Serial.println("RTC is RUNNING.");
      }
    }

    void loop () {
        DateTime now = rtc.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" (");
        Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
        Serial.print(") ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();

        Serial.print(" since midnight 1/1/1970 = ");
        Serial.print(now.unixtime());
        Serial.print("s = ");
        Serial.print(now.unixtime() / 86400L);
        Serial.println("d");

        // calculate a date which is 7 days and 30 seconds into the future
        DateTime future (now + TimeSpan(7,12,30,6));

        Serial.print(" now + 7d + 30s: ");
        Serial.print(future.year(), DEC);
        Serial.print('/');
        Serial.print(future.month(), DEC);
        Serial.print('/');
        Serial.print(future.day(), DEC);
        Serial.print(' ');
        Serial.print(future.hour(), DEC);
        Serial.print(':');
        Serial.print(future.minute(), DEC);
        Serial.print(':');
        Serial.print(future.second(), DEC);
        Serial.println();

        Serial.println();
        delay(3000);
    }

```

# Answer
First thing I see is the Serial setup seems a bit backward:

```
  while (!Serial); // for Leonardo/Micro/Zero
  Serial.begin(57600);

```

First, begin Serial; then wait for it to become ready:

```
  Serial.begin(57600);
  while (!Serial); // for Leonardo/Micro/Zero

```

Next, is this while(1); inside the if statement:

```
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

```

Which says "if !rtc.begin(), then println and go into an infinite loop that does nothing".

Try:

```
while (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    //delay(500);  // depending on how fast you want this thing to retry/print
}

```

the final thing I see, is the next section of code appears like it might be "work code" but is in the setup() function and is missing any kind of a loop. So it's going to run the if statement once, then setup() exits (and loop() starts getting called).

Either replace the "if" with a "while" and wait for "rtc.running()"

```
while (!rtc.running()); // Waiting for RTC to be running
// Set the clock time

```

or move it out of setup() and put it inside loop()

```
void loop() {
  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    Serial.println("RTC is NOT running!");
    // Perhaps try and fix it?
  } else {
    // If the time hasn't been set; set it; then move on
  }
}

```
> 1 votes

# Answer
Wow, that was hard to figure out. My RTC DS1307 came with an extra pin. This tripped me up when wiring the circuitry. I was off by a pin on my breadboard. Thank you everyone for your help.

Specifically, I had the ground going to the empty pin, and the 5v line going to the ground. Perhaps the circuitry allowed some current to go from the ground up and triggered the "i am here" part of the circuitry.
> 0 votes

---
Tags: arduino-uno, rtc, oscillator-clock
---


title: Servos and Random Number

text:
# Question
Title: Servos and Random Number
I am new to coding and this website so I apologize if I make any mistakes. I am trying to get servos to move when a random number is generated. Like if I roll a 2 I want servos 1, 2 and 3 to open and then if I roll a 3 after I want servos 4, 5 and 6 to open. I am able to hold the previous values in the code now but can't get the servos to go with it. Any help is great! Thanks!

```
#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo     position
int x = 0;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious = 0;
int oldNumber;

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

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  Serial.print("Random Number ");
 Serial.println(randomNumber);
 if( xPrevious == 0) {
   randomNumber = randomNumber + 1;
 }

  // Only want it to do this on the first roll.
     xPrevious = randomNumber + xPrevious;
     Serial.print("xPrevious ");
     Serial.println(xPrevious);
    oldNumber = xPrevious;

 for (x = randomNumber; x <= xPrevious; x += 1) {
  myservo.attach(x);
  Serial.println(x);

  for (pos = 0; pos <= 180; pos += 1) { // goes     from 0 degrees to 180     degrees
 //in steps of 1 degree
    myservo.write(pos);              // tell servo to go   to position in variable 'pos'
    delay(15);                       // waits 15ms for the     servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes  from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go    to position in variable 'pos'
    delay(15);                       // waits 15ms for the  servo to reach the position
  }

 }
 }
 }

```

# Answer
> 1 votes
You planning to use multiple servo, but only declare one. I still don't get about the pattern, but maybe this will give some image:

```
Servo myservo[5]; // assuming you have 5-servo
                  // servo[0]--> pin 0
                  // servo[1]--> pin 1
                  // servo[2]--> pin 2
                  // servo[3]--> pin 3
                  // servo[4]--> pin 4
pos = 0;

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  pos+=randomNumber;
  Serial.print("Random Number ");
  Serial.println(randomNumber);
  Serial.print("Current pos ");
  Serial.println(pos);

 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].attach(x+pos);
  Serial.print("attach servo-");
  Serial.println(x+pos); }

//open (move from 0-180 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(180);
 }
 delay(2000);

//close (move from 180-0 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(0);
 }
 delay(2000);

//detach servo
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].detach();
 }
 delay(2000);
}
}

```

---
Tags: servo
---


title: DC motor not start?

text:
# Question
Title: DC motor not start?
My aim is to create a simple obstacle avoiding robot using Arduino.

I have used L293D motor shield to drive the DC motors and supply it all with 12 V. I am using a sonar module to detect the obstacles. I have used an IR Receiver to control the motors of the robot.

From the serial prints I can tell that every IR signal is received and the expected functions are called. Unfortunately, when I press the button to start the motor, the motor does not start.

When I remove IR Receiver and start robot the code works fine.

In my code posted below I have commented some code so that it only calls the `startFan()` function.

What is wrong with my code? And how do I fix it?

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

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
#define MAX_SPEED 75 // sets speed of DC  motors

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(3, MOTOR12_1KHZ);
AF_DCMotor motor3(2, MOTOR12_1KHZ);

Servo myservo;

boolean goesForward = false;
int distance = 100;
int speedSet = 0;

int DisObstaclePin = 0; // This is our input pin
int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 11
int power_status ;

IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'

//----( SETUP: RUNS ONCE )----//
void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");

  int power_status = 0;
  motor3.setSpeed(150);
  motor3.run(FORWARD);

  pinMode(DisObstaclePin, INPUT);
  myservo.attach(9);
  myservo.write(115);
  delay(1000);

  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  DisObstacle = digitalRead(DisObstaclePin);
  delay(100);

  irrecv.enableIRIn(); // Start the receiver

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Serial.println("Begin loop");
  delay(1000);
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    Serial.println("wada");
    translateIR();
    irrecv.resume(); // receive the next value
    delay(500);
  }

 /* else {
    if (power_status == 1) {
      Serial.println("POWER ON");
      int distanceR = 0;
      int distanceL =  0;
      delay(40);
      if (distance <= 25 || DisObstacle == HIGH)
      {
        Serial.print("Turning");
        moveStop();
        delay(100);
        moveBackward();
        delay(300);
        moveStop();
        delay(200);
        distanceR = lookRight();
        delay(200);
        distanceL = lookLeft();
        delay(200);

        if (distanceR >= distanceL)
        {
          turnRight();
          moveStop();
        } else
        {
          turnLeft();
          moveStop();
        }
      } else
      {
        moveForward();
        Serial.print("Forword");
      }
      distance = readPing();
      delay(50);
      DisObstacle = digitalRead(DisObstaclePin);
      delay(50);
    }if (power_status == 0) {
       Serial.print("POWER OFF");
    }
  }
  */

}/* --(end main loop )-- */

/*-----( Functions )-----*/
void translateIR() // takes an action based on the IR code received
{
  switch (results.value)
  {

    case 0xFF30CF: Serial.println("Movement-ON- 1");
      power_status = 1;
      break;
    case 0xFF18E7: Serial.println("Movement-OFF -2");
      power_status = 0;
      break;
    case 0xFF10EF: Serial.println("Fan-on-3");
      startFan();
      break;
    case 0xFF38C7: Serial.println("Fan-off-4");
      stopFan();
      break;
    default:
      Serial.println(" other button   ");
  }
  delay(500); // Do not get immediate repeat
} //END translateIR

int lookRight()
{
  myservo.write(50);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
}

int lookLeft()
{
  myservo.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
  delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if (cm == 0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  delay(100);
}

void moveForward() {

  if (!goesForward)
  {
    goesForward = true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);

    motor1.setSpeed(100); //set the speed of the motors, between 0-255
    motor2.setSpeed(100);
    delay(100);
    motor1.setSpeed(55); //set the speed of the motors, between 0-255
    motor2.setSpeed(55);
  }
}

void moveBackward() {
  goesForward = false;
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);

  motor1.setSpeed(100); //set the speed of the motors, between 0-255
  motor2.setSpeed(100);
  delay(500);
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(BACKWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void startFan() {
  motor3.setSpeed(150);
  motor3.run(FORWARD);
  Serial.println("FAN  start  ");
  delay(2000);

}

void stopFan() {
  motor3.run(RELEASE);
  Serial.println("FAN  stop  ");
  delay(2000);
}

```

==============After change pin attachment ============================= I will change my code as follow and remove , 0,1 pin attachment sensor. Now code like below.

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

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
#define MAX_SPEED 75 // sets speed of DC  motors

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor3(2, MOTOR12_1KHZ);
AF_DCMotor motor2(3, MOTOR12_1KHZ);

Servo myservo;

boolean goesForward = false;
int distance = 100;
int speedSet = 0;

int DisObstaclePin = 2; // This is our input pin
int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

int receiver = 13; // Signal Pin of IR receiver to Arduino Digital Pin 11
//int power_on;
int fan_status,power_on;

IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'

//----( SETUP: RUNS ONCE )----//
void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");

  power_on = 1;
  fan_status = 0;

  pinMode(DisObstaclePin, INPUT);
  myservo.attach(9);
  myservo.write(115);
  delay(1000);

  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  DisObstacle = digitalRead(DisObstaclePin);
  delay(100);

  irrecv.enableIRIn(); // Start the receiver

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Serial.println("Begin loop");
  delay(1000);
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    Serial.print("Start reciving");
    translateIR();
    irrecv.resume(); // receive the next value
  }

  //delay(2000);
  if (power_on == 1) {
    Serial.println("POWER ON");
    int distanceR = 0;
    int distanceL =  0;
    delay(40);
    if (distance <= 25 || DisObstacle == HIGH)
    {
      Serial.print("Turning");
      moveStop();
      delay(100);
      moveBackward();
      delay(300);
      moveStop();
      delay(200);
      distanceR = lookRight();
      delay(200);
      distanceL = lookLeft();
      delay(200);

      if (distanceR >= distanceL)
      {
        turnRight();
        moveStop();
      } else
      {
        turnLeft();
        moveStop();
      }
    } else
    {
      moveForward();
      Serial.print("Forword");
    }
    distance = readPing();
    delay(50);
    DisObstacle = digitalRead(DisObstaclePin);
    delay(50);
  }

  if (fan_status == 1) {
    startFan();
    delay(50);
  } else {
    stopFan();
    delay(50);
  }

 // irrecv.resume(); // receive the next value
}/* --(end main loop )-- */

/*-----( Functions )-----*/
void translateIR() // takes action based on IR code received
{
  switch (results.value)
  {
    case 0xFF30CF: Serial.println("Movement-ON- 1");
      //power_on = 1;
      break;
    case 0xFF18E7: Serial.println("Movement-OFF -2");
      //power_on = 0;
      break;
    case 0xFF10EF: Serial.println("Fan-on-3");
      fan_status = 1 ;
      break;
    case 0xFF38C7: Serial.println("Fan-off-4");
      fan_status = 0;
      break;
    default:
      Serial.println(" other button   ");
  }
  delay(500); // Do not get immediate repeat
} //END translateIR

int lookRight()
{
  myservo.write(50);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
}

int lookLeft()
{
  myservo.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
  delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if (cm == 0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  delay(100);
}

void moveForward() {
  if (!goesForward)
  {
    goesForward = true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);

    motor1.setSpeed(100); //set the speed of the motors, between 0-255
    motor2.setSpeed(100);
    delay(100);
    motor1.setSpeed(55); //set the speed of the motors, between 0-255
    motor2.setSpeed(55);
  }
}

void moveBackward() {
  goesForward = false;
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);

  motor1.setSpeed(100); //set the speed of the motors, between 0-255
  motor2.setSpeed(100);
  delay(500);
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(BACKWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void startFan() {
  motor3.setSpeed(30);
  motor3.run(FORWARD);
  Serial.println("FAN start  ");
  delay(100);
}

void stopFan() {
  motor3.setSpeed(RELEASE);
  Serial.println("FAN  stop  ");
  delay(100);
}

```

Now I notice the M1 motor is not working. My question is also same as this: Motor shield question But I couldn't understand how to resolve it using my code. Other trouble I notice, a lot of the time the IR Receiver receives my signal. It executes without noticing a new signal. Sometimes it catches my signal.

# Answer
> 3 votes
Based on this thread:

Both AFmotor library and IRremote are using timer feature. And in addition, IRremote also use TIMER\_RESET, which probably causing the motor not function as expected (on comment section)

So the solution available is :

1. Use another library to drive motor, or you can make you own. See this tutorial.
2. Edit the library (IRremote or AFmotor) timer configuration (as you can found in the last post of the link I posted)

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


title: 10 bit PWM on Arduino UNO

text:
# Question
Title: 10 bit PWM on Arduino UNO
I am using this code to make 10 bit PWM on port number 9, it seems like everything printed is 0,1022 rather than printing 0, 512, 1023. Is there a problem in my code ?

I wired pin9 to A3 to get the output and print it.

```
  void setup() {
  Serial.begin(9600);
  pinMode(A3,INPUT);
  // Set PB1/2 as outputs.
  DDRB |= (1 << DDB1) | (1 << DDB2);

  TCCR1A =
      (1 << COM1A1) | (1 << COM1B1) |
      // Fast PWM mode.
      (1 << WGM11);
  TCCR1B =
      // Fast PWM mode.
      (1 << WGM12) | (1 << WGM13) |
      // No clock prescaling (fastest possible
      // freq).
      (1 << CS10);
  OCR1A = 0;
  // Set the counter value that corresponds to
  // full duty cycle. For 15-bit PWM use
  // 0x7fff, etc. A lower value for ICR1 will
  // allow a faster PWM frequency.
  ICR1 = 0x03ff;
}

void loop() {
  // Use OCR1A and OCR1B to control the PWM
  // duty cycle. Duty cycle = OCR1A / ICR1.
  // OCR1A controls PWM on pin 9 (PORTB1).
  // OCR1B controls PWM on pin 10 (PORTB2).
  OCR1A = 0x0000;
  delay(500);
  Serial.println(analogRead(A3));
  OCR1A = 0x0200;
  delay(500);
  Serial.println(analogRead(A3));
  OCR1A = 0x03ff;
  delay(500);
  Serial.println(analogRead(A3));
}

```

The output looks like that:

```
  0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

```

no data between 0 and 1022 are presented.

thanks.

# Answer
On your code, you using `analogRead` but declaring the pin (A3) as output. Change it to `pinMode(A3,INPUT);`

Aside from that, PWM is basically a digital output which changing (HIGH and LOW) at specified frequency. When the result you got is

> 0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

There's nothing wrong. 0 --\> LOW, and 1021++ --\> HIGH
If you want "measure" something from the PWM, use `pulseIn()` instead, you can check the documentation here.

If you want to measure the PWM value, I suggest you read:
Can I connect a PWM pin on one Arduino to an analog input on another?
> 4 votes

---
Tags: arduino-uno, pwm, analogread, avr, analogwrite
---


# Question
Title: How accurate the an attiny timer function
I have an AT-Tiny (trinket) and I want to trigger LED on for 30 seconds every 24 hours. I'm using the timer library as follows

```
timer.setInterval(86400000, toggleit());

void toggleit()
{
  turnLightOn();
  delay(6000);
  turnLightOff();
}

```

How accurate will this be, if it's off by a few minutes each day that's fine, but will this drift over time? Also does it make a difference if I'm running it in 8 or 16 bit mode?

# Answer
The on-chip systemclock is not very accurate. You can calibrate it to some degree but it also depends on the temperature and load of the MCU. You will need a high quality quartz oscillator as external clock source to reduce it. But it will still have a drift. Switching from 8-bit to 16-bit won't make a difference.

In your case an RTC sounds like the way to go.
> 2 votes

---
Tags: attiny, timers
---


# Question
Title: How to have an Arduino communicate with 3 other Arduinos?
I was wondering how I can get 4 Arduinos in total to communicate with each-other through a wired connection. The goal is to have the master Arduino send a number 0-100 to each of the other Arduinos.

The master unit will be an Arduino Uno and the other 3 Arduinos will be Arduino Pro Minis.

# Answer
> 3 votes
You could use: U(S)ART, I²C or SPI. You should check this post for information on these protocols.

Some quick googling gave me this:

* SPI: mainly for high data rates, approx 25 MHz clock but only bus has to be on same voltage level, single master (can be done through software), data arbitration not possible.
* I2C: mainly for control and low data transfer (limited by bus capacity, etc...), but can be interfaced to different voltage levels and multimaster bus environment, inbuilt arbitration etc...
* UART: single P2P comm, 115 kbps max.

http://www.edaboard.com/thread53139.html

I don't fully agree with it. You can send via UART to multiple devices, but then you have to handle the addressing in software. But other than that, UART is very easy to debug as Arduinos often have an USB connection.

"I²C is somewhat complicated at the physical level, but all that complication is handled by the hardware (the TWI interface of the AVR chips). At the user level, it may be the simplest to use". I don't yet have a lot of experience with this protocol, but if you want to use it, check out the other answer.

SPI would be a fair shot as it does enable master with multiple slaves in its standard.

Summary:

All protocols have different pros and cons. It's not really up to us to choose one for you. And you should look them up and learn about them by yourself.

Then try to choose which one applies most to your needs, and get started with that protocol. They are well documented and if you really can't get out of it, you can post another question ;D

# Answer
> 2 votes
You can use the I2C communication protocol through the wire.h library. That will permit you to use the arduino uno as master device and the pro minis as slave. Briefly, you use a two wire's connected to the SDA and SCL pins of all the arduino board and then the master to interact ( meaning request data and send data) with the slaves uses there address (that is user defined in the slave software). So the normal routine in I2C goes like this:

1. The master sends the address plus the read write instruction on the bus.
2. All the arduino boards listen and if the address matches with there internal adress they perform the instruction.
3. If it is write command from the master the slaves prepare to receive. If it is read command from the master, the master waits until the slave send a byte.

Fr more information go on:

Arduino two wire communication

I2C official datasheet

# Answer
> 2 votes
You can use RS-485 connection between all arduinos using serial port of all. For a half duplex connection for 4 arduinos, the setup can be like this:

**What Do You Need:**

* 4 RS-485 line drivers (*like max485*). One for each arduino
* if the distance between arduinos are short (under 1 mt) these will br enough
* if the distance between arduinos are long (over 2mt) you'll need to use at least 24 AWG twisted pair cable between them and 2 120 ohm resistors. These resistors will be line terminators.
* You can check max485 datasheet to see how to connect them

**Setting Up:**

To use rs485 with arduino and half duplex, you'll need 3 pins. 2 pins for rx and tx. 1 pin for *transmit-enable*. In half duplex mode, normally all nodes are in listening mode. To configure transmit enable, connect "*drive enable*" and "*receive enable*" pins of rs485 driver together. This will be our "*transmit-enable*" pin.

**Connection:**

```
      |        |
c  RX |------->|RO     4
p  TX |------->|DI     8
u D13 |------->|TE&RE^ 5
      |        |

```

**Software:**

Download this library (Mertbus). This library implements a basic transport layer. It is in alpha stage but functional. There is sample code in it and also a .net library.

The logic is similar to TCP/IP. Give every node an address between 0 and 126. 127 is the broadcast id. Means if you send data to id 127 all nodes will receive it. If you send data to only one node (ex. 2 ...) only target node will receive.

Sample:

```
#include "MertBus.h" //include header

#define TXEN 13  //transmit-enable pin
#define SELF_ID 1  //id of this node

MertBus mb;  //communicator class

void setup() {
   Serial.begin(57600); //prepare the serial port as usual
   Serial.println("Begin init");
   //then initialize mertbus instance with port, pin and id
   mb = MertBus(Serial,TXEN,SELF_ID);
}

void loop() {
  if(mb.checkData()) {    //check if and valid data received
    // reply to sender char[] and length, 26 chars
    mb.reply("Incoming Data (SendData): ",26);
    // reply to sender the received data
    mb.reply(mb.Buffer,mb.ReceiveCount);
  } else {
    digitalWrite(13,HIGH);
    delay(400);
    digitalWrite(13,LOW);
    delay(400);
  }
}

```

To be a master, to send data (without replying to a message, starting a new one):

```
//buffer data to send, to_addr is target node address
//buffer_size is the size of data to send.
mb.sendData(char * buffer, uint8_t to_addr, uint8_t buffer_size)

```

# Answer
> 2 votes
If they are reasonably close to each other, by far the simplest would be to use serial comms, since you say you want to *send* a number (but do not mention receiving anything).

You could have the Tx pin on the master Arduino connected to the Rx pin of all the other Arduinos (plus a ground connection of course). Then send your numbers to your heart's delight. I suggest some sort of protocol like:

```
(42)

```

Where the opening and closing braces indicate to the receiver where the number starts and ends. If the distance is more than (say) 5 meters, an RS485 transceiver may be called for at each end, eg.

I have a description of the sort of thing on my RS485 communications page.

You can "drop" multiple transceivers off the same pair of cables.

RS485 is reasonably resistant to line noise because it is a balanced protocol.

These transceivers can transmit or receive but not at the same time. In your case you would have the master with Tx Enable active, and the slaves the Tx Enable not active.

If the chips are dropped off a long cable run you should have a termination resistor between A and /B at the end (say, 120 Ω).

SPI could be OK, but is really for short runs. I2C could be OK too, but may be unnecessarily complex. However if you go with I2C it does have a "broadcast" mode which might suit sending the same thing to multiple devices.

---

### References

# Answer
> 1 votes
PJON is a bit banged serial bus protocol for multiple nodes. You may find it useful.

> PJON™ (Padded Jittering Operative Network) is an Arduino compatible, multi-master, multi-media communications bus system. It proposes a Standard, it is designed as a framework and implements a totally software emulated network protocol stack that can be easily cross-compiled on many architectures like ATtiny, ATmega, ESP8266, Teensy, Raspberry Pi, Linux and Windows x86 machines. It is a valid tool to quickly and comprehensibly build a network of devices

---
Tags: arduino-uno, arduino-pro-mini, communication
---


title: Using ATTiny85 as a USB HID Mouse

text:
# Question
Title: Using ATTiny85 as a USB HID Mouse
Our project involves using an arduino compatible microcontroller to control a mouse on a computer with an accelerometer and flex sensor. We had narrowed down to the ATTiny85 due to its small size.

We found a particular tutorial on the Adafruit tutorial website, using the Adafruit Pro Trinket using the same ATTiny85.

Is there a reason to believe that this won't work?

Also, does anyone have suggestions as to which board to use apart from Micro as it isn't too available here?

# Answer
> 4 votes
Due to the lack of USB-Support of the ATtiny85 you will be forced to use something like V-USB as the tutorial does. This might have implications when you are targeting a commercial product.

Personally I'd suggest using the ATmega32u4. It has USB build right in.

But basically I don't see any reasons why it should not work.

# Answer
> 0 votes
@Kwasmich raises a good point about the 32u4. Here is a little more information about it.

* Works at 5V and 3.3V
* Compatible with the Arduino IDE
* Built-in USB
* Very close to the ATmega328

Here are a couple of cheap breakouts for it

---
Tags: usb, attiny, mouse
---


# Question
Title: Using an Arduino as a lithium ion charge controller
I have a trinket that I'm going to be powering off of a small lithium ion battery. I was also considering adding a small solar panel to the mix, and using the solar panel to charge the battery. I'm wondering if I can use the trinket itself as a smart charge controller to charge and monitor the battery.

# Answer
If you are going to design your own battery management system here are a few issues you will need to deal with:

1. You need to understand the methods to determine the End Of Charge (EOC). This could be monitoring cell temperature, measuring cell voltage or current for patterns, or integrating current over time (coulomb counter). Different battery chemistries usually dictate which approach to take.
2. You need to check with the specific battery manufacturer to determine what charge rate you should use for this specific battery. Knowing the chemistry is good. But it is usually best to use the charge rate data from reputable manufactures.
3. Some batteries can not be completely drained. If not already part of the LION battery, you will need to design a protection circuit to cut the battery off before this happens.
4. For such batteries, you need to add a trickle charging circuit in case the battery has been overly discharged. Such a circuit only allows a small amount of current in. The current is usually so small that normal monitoring is not necessary. This is a last resort procedure built into most good chargers to recover overly discharged LION batteries.

...this is not a complete list. These are some of the issue which might be considered when designing a secondary battery charger. There is a lot more good information about batteries here if you would like to research this subject in greater depth.
> 2 votes

# Answer
If you have a small solar panel, you probably don't have to worry about limiting the charge current (as the battery will be able to handle more that the solar panel can supply).

So the only thing left to do is prevent over-charge (i.e. disconnect the solar panel if the voltage on the battery goes above 4.2V). Protected cell can do this for you. I'm not knowledgeable enough to know if it's a good idea to rely on this.

Also make sure the solar panel isn't connected when it's dark, as the solor panel will use current when it's not generating it. Though a simple diode will do this trick. But you'd get a 0.6V drop on the diode, so you might want to get some extra efficiency by detecting output and switching the solar panel using the Arduino.

The last problem is overdischarge, unless you have a protected cell. But that's a problem you have, even without the charging bit.
> 2 votes

# Answer
Try this. It's the Adafruit PowerBoost 1000 Charger - Rechargeable 5V Lipo USB Boost @ 1A - 1000C.

It's designed for Lipo, but I **think** it should work for Li-ION
> 0 votes

---
Tags: battery, solar
---