body:
I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with

        char charVal[5];               //temporarily holds data from vals
        String stringVal = "";     //data on buff is copied to this string

        dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
        //convert chararray to string
        for(int i=0;i<sizeof(charVal);i++)
        {
        stringVal+=charVal[i];
        }
        GPS_string = GPS_string + "Car location: \nlat:" + stringVal;
        stringVal = "";

and it given me an error :

    error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,

title: How to append float value of into a string ?

Answers: 1

body:
This has been answered in the previous [question][1] but I can repeat it here:

    void loop()
    {
      ...
      float latitude = 33.546600;
      float longitude = 75.456912;
      String buf;
      buf += F("your location is \nlat:");
      buf += String(latitude, 6);
      buf += F("\nlong:");
      buf += String(longitude, 6);
      Serial.println(buf);
      ...
    }

An alternative is to use [dtostrf()][2] as in your snippet:

    void loop()
    {
      ...
      float latitude = 33.546600;
      float longitude = 75.456912;
      const int BUF_MAX = 64;
      char buf[BUF_MAX];
      const int VAL_MAX = 16;
      char val[VAL_MAX];
      strcpy_P(buf, (const char*) F("your location is \nlat:"));
      dtostrf(latitude, 8, 6, val);
      strcat(buf, val);
      strcat_P(buf, (const char*) F("\nlong:"));
      dtostrf(longitude, 8, 6, val);
      strcat(buf, val);
      ...
    }

Cheers!

  [1]: https://arduino.stackexchange.com/questions/20908/store-tinygps-latitude-value-into-a-variable-of-type-string-or-float
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga060c998e77fb5fc0d3168b3ce8771d42


body:
I'm using the Arduino Starter Kit so I have a Uno R3 and going through the examples I'm trying to read temperature data from my controller in Arduino Studio.

In essence my problem can be reduced down to

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

    void loop() {
        Serial.print("stuff");
    }

Which I'd expect to keep printing "stuff" on the serial monitor.

(In practice I'm running [this](https://codebender.cc/example/10.StarterKit/p03_LoveOMeter#p03_LoveOMeter.ino) exact code but all the temperature-reading going on feels irrelevant to my problem, I'm simply mentioning it because I can observe that mye LEDs light up when the temperature rises so I know the code is uploaded and running on the Duo).

I'm not seeing any errors in the studio console, and if I connect using `gtkterm` or `screen` I can see data being sent so the problem seems to be isolated to the AndroidStudio serial monitor itself.

I'm running Ubuntu 14.04 and I've connected via USB on `/dev/ttyACM3`.

I tried running
> stty -F /dev/ttyACM3 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as suggested [here](http://playground.arduino.cc/Interfacing/LinuxTTY) and I also tried with baud 115200, taking care to also change the value in my `setup` function.

I also ran
> chmod a+rw /dev/ttyACM3

But I'm still not seeing any errors or output. How do I proceed to debug this issue?

Running `ls -l /dev/ttyACM*` gives

> crw-rw---- 1 root dialout 166, 0 feb.  20 14:22 /dev/ttyACM0
>
> crw-rw---- 1 root dialout 166, 1 feb.  20 14:22 /dev/ttyACM1
>
> crw-rw---- 1 root dialout 166, 2 feb.  20 14:22 /dev/ttyACM2
>
> crw-rw-rw- 1 root dialout 166, 3 feb.  20 14:30 /dev/ttyACM3

title: I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04

Answers: 1

body:
By default, on a linux system without specific
udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB* and not to /dev/ttbACM*. I suspect that you were just looking in the wrong place.
I think it defaults to /dev/ttyUSB* for any usb to serial dongle:

    usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";


body:
I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):

***Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it [here](http://pastebin.com/RpELDBx2).***

There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an `int` and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.

The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.

So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.

Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.

So, any ideas on what could cause this?

----------

**Update:**

I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested [here](https://arduino.stackexchange.com/a/20989/17324)), which is kind of similar to the [NMEA 0183](https://en.wikipedia.org/wiki/NMEA_0183) protocol (basically a simplified version of that). The sender sends the data in the following format now:

 - A single `$` character to indicate the beginning of the data
 - The data itself (which is the textual representation of a single integer)
 - A single `*` character to indicate the end of the data
 - An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between `$` and `*` (not including those). Letters (if any) are always uppercase.
 - The packet is finished up with either `\n` or `\r\n`

An example would be `$178*3E\n`, where \n of course means a newline character.

The code running on the Arduino now is the following:

<!-- language: lang-cpp -->

    #include <Time.h>

    #define _analogWrite(a, b) analogWrite(a, 255-(b))
    #define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

    const PROGMEM int pwmPin = 3;
    time_t lastUpdate = 0;
    String incoming = "";
    int pwmValue = 0;

    inline void flushSerialBuffer() {
        while (Serial.available()) Serial.read();
    }

    void setup() {
        Serial.begin(9600);
        Serial.setTimeout(500);
        pinMode(pwmPin, OUTPUT);
        _analogWrite(pwmPin, 0);
    }

    void loop() {
        time_t currentTime = now();

        if (Serial.available()) {
            delay(250); // Just to make sure that all data has arrived in the buffer
            incoming = "";
            incoming = Serial.readStringUntil('\n');
            flushSerialBuffer();
            int b = incoming.indexOf('$') + 1;
            if (b == 0) return; // -1 was returned
            int e = incoming.indexOf('*', b);
            if (e == -1) return;
            int checksum = 0x0;
            for (int i=b; i<e; i++) checksum ^= incoming[i];
            String hexString = String(checksum, HEX);
            hexString.toUpperCase();
            if (hexString.length() < 2) hexString = String("0") + hexString;
            if (!hexString.equals(incoming.substring(e+1, e+3))) return;

            pwmValue = incoming.substring(b, e).toInt();

            if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
            lastUpdate = currentTime;
        }

        if (currentTime - lastUpdate > 30) pwmValue = 0;

        _analogWrite(pwmPin, pwmValue);

        delay(250);
    }

It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.

----------

**Update 2:**

Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.

title: Arduino Nano PWM output acting strange after running for a day or so

Answers: 3

body:
You have a
[race condition](https://en.wikipedia.org/wiki/Race_condition) in your
code: if you try to read a message while it's being sent, you may catch
only a partial message, and end up reading the wrong numbers. My bet is
that this is exactly what is biting you. Once this happens once, it is
bound to happen again for some time, since 5 seconds is a multiple
of your 100 ms delay.

The right thing to do would be to wait until you get the new-line
character (then you know you have a complete message) before trying to
parse the message. A quick and dirty hack is to just `delay(10)` after
`Serial.available()` but before `Serial.readString()`.

body:
Your problem may be related to the dynamic memory allocation of your String objects. Each time the Arduino receives data, you are creating two new String objects. Perhaps the memory is not being released properly, causing eventual exhaustion of your RAM.

You could make your Strings global and empty them out each time, but a far better solution would be to replace all your string manipulation with a call to Serial.ParseInt() so your big if block becomes

   `if (Serial.available()) {
        pwmValue = Serial.ParseInt();
        while(Serial.available() > 0 {
          Serial.read();    // flush anything after the integer
        // Save the current time
        lastUpdate = currentTime;
    }`

Serial.ParseInt also makes use of the timeout so you don't have to worry about partial values being read.

body:
After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.

Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.

You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the *, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.


body:
So, first of all I just want to point out this code is from: [Reading Rotary Encoders][1] and is not mine.

I have a magnetic shaft encoder mounted on a regular DC motor, my problem is that I cannot receive the exact angle of the motor. The encoder outputs `+1` each 90 degrees (I then multiply by 90). And is there any relationship between `valx`, `valy`, `valz` and the angle?

<!-- language: c -->

    #define encoder0PinA 2
    #define encoder0PinB 3
    int rounds= 0;
    volatile unsigned int encoder0Pos = 0;
    unsigned int tmp_Pos = 1;
    unsigned int valx;
    unsigned int valy;
    unsigned int valz;

    boolean A_set;
    boolean B_set;

    int enA = 9;
    int in1 = 10;
    int in2 = 11;

    void setup() {

      pinMode(encoder0PinA, INPUT);
      pinMode(encoder0PinB, INPUT);
      // encoder pin on interrupt 0 (pin 2)
      attachInterrupt(0, doEncoderA, CHANGE);

      // encoder pin on interrupt 1 (pin 3)
      attachInterrupt(1, doEncoderB, CHANGE);
      Serial.begin( 9600 );

      pinMode(enA, OUTPUT);

      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      analogWrite(enA, 225);
      Serial.begin (9600);
    }

    void loop(){
    //Check each second for change in position

      if (tmp_Pos != encoder0Pos) {
        Serial.print("Index:"); Serial.print(encoder0Pos * 90,DEC);
        Serial.println();
        Serial.print("valx:");Serial.print(valx,DEC);
        Serial.println();
        Serial.print("valy:");Serial.print(valy,DEC);
        Serial.println();
        Serial.print("valz:");Serial.print(valz,DEC);
        Serial.println();
        tmp_Pos = encoder0Pos;
      }
    }

    // Interrupt on A changing state
    void doEncoderA(){

      // Low to High transition?
      if (digitalRead(encoder0PinA) == HIGH) {
        A_set = true;
        if (!B_set) {
          encoder0Pos = encoder0Pos + 1;
          valx=analogRead(0);
          valy=analogRead(1);
          valz=analogRead(2);
        }
      }

      // High-to-low transition?
      if (digitalRead(encoder0PinA) == LOW) {
        A_set = false;
      }
    }

    // Interrupt on B changing state
    void doEncoderB(){

      // Low-to-high transition?
      if (digitalRead(encoder0PinB) == HIGH) {
        B_set = true;
        if (!A_set) {
          encoder0Pos = encoder0Pos - 1;
        }
      }

      // High-to-low transition?
      if (digitalRead(encoder0PinB) == LOW) {
        B_set = false;
      }
    }

  [1]: http://playground.arduino.cc/Main/RotaryEncoders

title: Shaft Encoder Accuracy

Answers: 1

body:
If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.

In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

> My project is a data loger where three analogue inputs are sampled
> each time a rotary encoder pulse steps clockwise. On an Arduino, time
> is of the essence to get this data sampled and saved somewhere (I have
> not included the 'saving somewhere' part of this project yet.) In
> order to save some processor cycles, I have slightly redesigned the
> interrupt system to maintain a pair of boolean states outside of the
> interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.


body:
I noticed that both the Uno and Wifi101 are FCC certified.  Does this mean that these components can actually be used in commercial applications?  This never really occured to me before I noticed the markings.

I'm sure there is more to a commercial product than just FCC certification but I know that the certification process isn't cheap!

title: FCC Certification

Answers: 1

body:
These products are not certified, they merely have been verified and issued a Declaration of Conformity. The WiFi module on the WiFi shield itself has been certified, as indicated by the FCC ID on its label.

To explain what that means, I am going to give a simplified explanation. If you are looking to make a commercial product and you are not sure what you need to do to be compliant, hire out a professional to help you through the process.

In the eyes of the FCC, devices fall into one of two categories, devices that are intentional transmitters, and devices that are not. Devices that are intentional transmitters need to be certified. Certification is a process of making sure that it is only transmitting on the frequency band it specified, that it is maintaining certain power limits, and that it will not cause interference with other devices. This is a very expensive testing procedure.

Devices that are not intentional transmitters, only need to get a verification. What this means is that the devices is not designed to transmit anything and is test to makes sure that it indeed does not. If you pass the verification you are issued a Declaration of Conformity basically stating that the device is not unintentionally transmitting any frequencies. This is usually a lot less expensive than than certification (but still in the few thousand USD range).

[![WiFi Shield Module][1]][1]

So taking the WiFi shield as an example, the module shown above circled in red is an intentional transmitter, i.e. it is designed to transmit on a particular frequency band (in this case 2.4 GHz ISM band). The device is certified to make sure that its emissions are within FCC specifications and it is issued an FCC ID.

Now at this point only the module is certified and is good to be used in a product, however, now that it is on a shield with extra circuitry added to it, the extra circuitry could be unintentionally transmitting. So now the whole shield is tested to make sure that the added circuitry does not have any emissions exceeding the FCC specifications and is issued a Declaration of Conformity.

So now fast forward to making your own thing, the module is certified, the WiFi shield and the Uno are verified, you add your own additional circuity around those components that may emit electromagnetic fields. You now may have to get your product verified to ensure that the added components to the system have not caused it to unintentionally emit radio frequencies.

The whole process, conditions, and requirements are a lot more nuanced than my description above. So this should in no way be used as the basis for product development or legal advice.

(Image borrowed from https://www.arduino.cc/en/Main/ArduinoWiFiShield101)

  [1]: https://i.stack.imgur.com/C5tH2.jpg


body:
I am trying to connect a CMOS flash memory Winbond W49F002U-12B to an Arduino Mega, but failing.

[![Winbond W49F002U-12B][1]][1]

What I did:

1. Read the Winbond W49F002U-12B datasheet. The key points are: CE - chip enabled; OE - output enabled; WE - write enabled and this table:

> [![Winbond W49F002U-12B Operating Modes][2]][2]

2. Wrote this code and uploaded to Mega2560:

        int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
        int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
        int CE = 50;
        int OE = 49;
        int WE = 48;

        char ch;
        char addrs[5];
        unsigned long address;
        unsigned int result;
        void setup() {
          Serial.begin(9600);
          for(int i=0; i<18; ++i)
              pinMode(A_pins[i], INPUT);
          for(int i=0; i<8; ++i)
              pinMode(DQ_pins[i], OUTPUT);
          pinMode(CE, OUTPUT);
          pinMode(OE, OUTPUT);
          pinMode(WE, OUTPUT);
          digitalWrite(WE, HIGH);
          digitalWrite(OE, HIGH);
          digitalWrite(CE, LOW);

        }

        void func(unsigned long adr)
        {
          for(int i=0; i<18; ++i){
            if(adr & (1ul << i)){
              digitalWrite(A_pins[i], HIGH);
              Serial.print("A_pins[");
              Serial.print(i);
              Serial.println("] = HIGH");}
            else{
              digitalWrite(A_pins[i], LOW);}}
          digitalWrite(OE, LOW);
          delay(100);
          for(int i=0; i<8; ++i){
            if(digitalRead(DQ_pins[i]) == HIGH){
              result|=1<<i;
              Serial.print("DQ_pins[");
              Serial.print(i);
              Serial.println("] = HIGH");}
          }
          Serial.println(result);
          digitalWrite(OE, HIGH);
        }

        void loop() {
          if (Serial.available() > 0)
          {
           address = (unsigned long)Serial.parseInt();
           Serial.print("address = ");
           Serial.println(address);
           func(address);
           }
        }

What this code is doing is basically after reading serial:

 -> takes the value as address

 -> changes pins A0-A17 to select particular address cell

 -> changes OE to LOW

 -> reads DQ0-DQ7

 -> coverts those readings into int

 -> prints result out.

Example of Arduino IDE Serial Monitor inputs/ouputs stuff:

    address = 0
    0
    address = 1232
    A_pins[4] = HIGH
    A_pins[6] = HIGH
    A_pins[7] = HIGH
    A_pins[10] = HIGH
    0
    address = 131072
    A_pins[17] = HIGH
    0
    address = 245760
    A_pins[14] = HIGH
    A_pins[15] = HIGH
    A_pins[16] = HIGH
    A_pins[17] = HIGH
    0

> Arduino Mega board is 100% functioning. I don't think Winbond w49f002u-12b is not working. Where am I wrong?

**UPDATE:** Here is fixed code:

    int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
    int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
    int CE = 50;
    int OE = 49;
    int WE = 48;

    unsigned long address;
    unsigned int result;
    void setup() {
      Serial.begin(9600);
      for(int i=0; i<18; ++i)
          pinMode(A_pins[i], OUTPUT);
      for(int i=0; i<8; ++i)
          pinMode(DQ_pins[i], INPUT);
      pinMode(CE, OUTPUT);
      pinMode(OE, OUTPUT);
      pinMode(WE, OUTPUT);
      digitalWrite(WE, HIGH);
      digitalWrite(OE, HIGH);
      digitalWrite(CE, LOW);

    }

    void func(unsigned long adr)
    {
      result = 0;
      for(int i=0; i<18; ++i){
        if(adr & (1ul << i)){
          digitalWrite(A_pins[i], HIGH);
        }
        else{
          digitalWrite(A_pins[i], LOW);}}
      digitalWrite(OE, LOW);
      //delay(100);
      for(int i=0; i<8; ++i){
        if(digitalRead(DQ_pins[i]) == HIGH){
          result|=1<<i;
        }}
      Serial.println(result);
      digitalWrite(OE, HIGH);
    }

    void loop() {
      if (Serial.available() > 0)
      {
       address = (unsigned long)Serial.parseInt();
       Serial.print(address);
       Serial.print(": ");
       func(address);
       }
    }

**UPDATE:** Changed code using PORTs, Thanks to @MikaelPatel for reminding about PORTs:

    unsigned long address;

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

      DDRL = B00000000; // DQ7-DQ0 42-49
      DDRA = B11111111; // A7-A0 29-22
      DDRC = B11111111; // A15-A8 30-37
      DDRG |= B00000011; // A17-A16 40-41
      DDRB |= B00000111; // WE, OE, CE

      PORTB = B00000110; // WE - HIGH, OE - HIGH, CE - LOW
    }

    void func(unsigned long adr)
    {
      PORTA = adr;
      PORTC = (adr>>8L);
      PORTG = (adr>>16L);
      PORTB = B00000100; //OE - LOW
      Serial.println(PINL);
      PORTB = B00000110; //OE - HIGH
    }

    void loop() {
      if (Serial.available() > 0)
      {
       address = (unsigned long)Serial.parseInt();
       Serial.print(address);
       Serial.print(": ");
       func(address);
       }
    }

  [1]: https://i.stack.imgur.com/4rh9M.png
  [2]: https://i.stack.imgur.com/3YZyj.png

title: Connecting Winbond W49F002U-12B to Arduino Mega

Answers: 1

body:
> What this code is doing is basically after reading serial: ... -> reads DQ0-DQ7

But all the DQn pins are in OUTPUT mode and the A pins in INPUT mode. Seems to be a mix up. BW: it is the same with all of the pins. The pin mode is from the Arduinos point of view and not the memory chip.

Cheers!


body:
Often I put a bunch of `Serial.print( F("debugging messages") )` in my Arduino sketch.

Normally those messages go up a USB cable to a host PC so those messages can be seen on the serial monitor.

I want to install this Arduino as part of a stand-alone system far from any PC and plug the "host" end of the USB cable into a wall-wart USB charger.

Without anything to accept those messages, the buffer on the Arduino eventually fills up, right?
Do I need to do anything to keep the Arduino from overflowing and crashing when it's not connected to a host PC?

Does it make any difference if I'm using a (1) "single-chip" Arduino-compatible where the processor includes on-chip USB, vs. (2) an Arduino-compatible with separate "USB interface chip" and "processor chip"?
(By "single-chip Arduino-compatible", I mean things like the Arduino Leonardo, Arduino Yún, LilyPad Arduino USB, Arduino Micro, the Teensy-LC, etc.)

title: Is it OK to Serial.print(message), when the USB cable is not connected to a host PC?

Answers: 1

body:
It is OK to write out serial data with nothing connected.

In case (2) "Arduino + USB interface chip", the arduino has no idea if anything is connected or listening to the serial port. The code will transmit the bytes and act exactly the same whether plugged in to anything or not.

In case (1) "arduino with built in USB" it has some idea, but just drops bytes that are going to be transmitted when the USB port is not connected.

Hardware serial (case 2) has an output buffer, but that just makes the program a little faster. When the buffer is empty, a call to `serial.{print, write}` will place bytes in the buffer and move on. When it's full, `Serial.{print,write}` will wait until there is enough room to put the rest of the message in the buffer and move on. The hardware UART and interrupts it generates will keep taking bytes out of the buffer and transmitting them at a constant rate whether something is plugged in or not. In any case, the buffer is a fixed size and will never overflow.

As far as I can tell USB-Serial (case 1) only buffers incoming data. Since the calls to `Serial.{print, write}` do nothing when not connected, they may take less time than they would otherwise. If your code is really unsafe about timing, that could cause a problem, but I doubt it will.

Many examples that come with the Arduino IDE have the following bit of code that pauses native USB Arduino-compatibles until the USB connection is initialized:

      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

This code stops the Arduino from doing anything until the USB cable is connected.
Comment out or delete those 3 lines if you want the Arduino to run "stand-alone" without a USB cable connection ([Arduino Cookbook][1] p. 117) --
after you delete those lines, if you later plug in a USB cable, the USB will initialize correctly, and *then* you will see on your serial monitor everything printed by any *later* Serial.print() commands that run. (Tested on a Teensy LC).

  [1]: https://books.google.com/books?id=3b3dDwAAQBAJ


body:
I recently bought an Arduino MEGA2560 and a [SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control][1].

I understand how to control a servo in the method described in [Sweep][2]. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

Please help me I am a beginner in robotics and I need this for a project.

[![enter image description here][3]][3]

  [1]: http://www.sainsmart.com/sainsmart-instabots-robot-controller-shield-for-arduino-mega2560-r3-robot-arm-control.html
  [2]: https://www.arduino.cc/en/Tutorial/Sweep
  [3]: https://i.stack.imgur.com/iVWnv.jpg

title: Code to control servo with shield

Answers: 3

body:
> However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

With the limited amount of info you have provided about the shield this will have to be a wild guess. I am assuming that the pins are S(ignal), V(cc) and G(nd) for pins 8-13. On an Arduino Mega these can be used for PWM and therefore Servo control.

Include the Servo library, attach the pin and set the angle.

    #include <Servo.h>

    Servo servo[6];

    void setup()
    {
      ...
      for (int i = 0; i < 6; i++)
        servo[i].attach(8 + i);
      ...
    }

    void loop()
    {
       ...
       servo[i].write(pos);
       ...
    }

Cheers!

NB: Do not forget to provide the correct power supply. If USB Port is left, then the upper pin is positive and the lower pin negative.

body:
The SVG connectors on your board appear to be lacking header pins:

[![Three pin header][1]][1]

These should have been supplied with the board. If not you will need to source some. Either way, you will need to solder them on. I don't understand why they are not already attached.

If you look at the other images of the board on the SainSmart web page, the header pins are clearly visible:

[![SainSmart shield with header pins][2]][2]

The S pin of each SVG is the same as the output pins, near the green light, but for ease of use, they are replicated in the SVG pins, so that a servo plug can be easily, and conveniently plugged in, with out the user having to wire up power and ground separately.  If you look at the plug attached to the end of the cable coming from your servo, you will see the servo connector, like so:

[![Servo connector][3]][3]

As the board has arranged the pins in the SVG order, that means that it will support the Futaba J type connectors (but not the Airtronics, as the power and ground pins are reversed):

[![Futaba and Airtronics connectors][4]][4]

Also, Hitec and JR Radio connectors are supported by your board, as they have the same pin out:

[![JR Radio and HiTec connectors][5]][5].

For more information, take a look at [Choosing RC Servos][6].

In addition, as Mikael says, you will also need to attach an external power supply to the green terminals

[![SainSmart shield showing green external power connector][7]][7]

as the on board power regulator of the Arduino can not supply enough power to the servos, via the shield, by itself, neither with the USB, nor an external wall wart PSU, supplying power to the Arduino. So, use a bench power supply, battery pack, or otherwise and supply that power directly to the board via the Green power terminals at the end of the board.

Once you have done all of that, and got the hardware out of the way, then the software provided in [Mikael's answer][8] will work perfectly.

  [1]: https://i.stack.imgur.com/Ofsli.jpg
  [2]: https://i.stack.imgur.com/o9yaD.jpg
  [3]: https://i.stack.imgur.com/mylsp.jpg
  [4]: https://i.stack.imgur.com/Sy2RH.gif
  [5]: https://i.stack.imgur.com/Kjs4s.gif
  [6]: http://www.hooked-on-rc-airplanes.com/rc-servos.html
  [7]: https://i.stack.imgur.com/XI6lw.jpg
  [8]: https://arduino.stackexchange.com/questions/20931/code-to-control-servo-with-shield#answer-20937

body: Sainsmart STILL refuses to supply documentation for this board.Supposedly, it can control 6 servos and two motors, up to 4 Amps, with digital encoder inputs. There is NO documentation on the hardware or the software for the mega to drive this.


body:
I am messing around with an ATmega328P hooked on a Raspberry Pi, communicating over I2C. The ATmega is the slave (details at the end). While testing the basics of the concept, I faced an interesting problem.

This is the code on the ATmega:

<!-- language: lang-cpp -->

    #include <Wire.h>

    #define SLAVE_ADRESS 0x1A
    #define LED 6

    int count = 10;
    void setup()
    {
        pinMode(LED, OUTPUT);
        /*for(int i=1; i<=3; i++)
        {
          digitalWrite(LED, HIGH);
          delay(100);
          digitalWrite(LED, LOW);
          delay(100);
        }*/
        Wire.begin(SLAVE_ADRESS);
        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
    }

    void loop()
    {
      delay(10);
    }

    void receiveEvent(int received_bytes)
    {
      while(Wire.available())
      {
        unsigned char i = Wire.read();
        if(1)
        {
          int j = 5;
          while(j>0)
          {
            digitalWrite(LED, HIGH);
            delay(300);
            digitalWrite(LED, LOW);
            delay(300);
            j-=1;
          }
        }
        delay(1);
      }
    }

    void requestEvent()
    {
      Wire.write(count);
    }

What you would expect it to do is blink the LED connected to pin 6 five times when the Pi sends a byte to the ATmega slave. (Things like `if(1)` are there because the code was much more specific originally.) The strange thing is that this is not the case:

*The LED only blinks 1 time.*

I honestly have no idea why. This "stdio-fitted" version of the problematic loop ran on the RPi as expected, prints 5*2 times:

<!-- language: lang-cpp -->

    #include <stdio.h>

    int main()
    {
      int j = 5;
      while(j>0)
      {
        printf("LED, HIGH\n");
        printf("LED, LOW\n");
        j-=1;
      }
      return 0;
    }

**Circumstances:**

 - I compile the code in the Arduino IDE on the Pi, then upload it
   using AVRDUDE to the ATmega with the Pi's GPIOs. No error messages
   over the process.
 - The ATmega gets 3.3 V supply voltage from the Pi, and operates on
   16.000 MHz. Only the LED and the Pi is connected to it.
 - The (Python) code I use on the Pi to write and read a byte is the following. Reading works well, and I know by tests that the ATmega actually receives the correct byte:

<!-- language: lang-python -->

    import pigpio
    import time

    pi = pigpio.pi()
    atmega = pi.i2c_open(1, 0x1A)

    for i in range(6):
        a = pi.i2c_read_byte(atmega)
        print a

    pi.i2c_write_byte(atmega, 0x05)
    time.sleep(1)

title: Loop behaves oddly in I2C receiveEvent

Answers: 1

body:
<!-- language-all: lang-C++ -->

    void receiveEvent(int received_bytes)
    {
      while(Wire.available())
      {
        unsigned char i = Wire.read();
        if(1)
        {
          int j = 5;
          while(j>0)
          {
            digitalWrite(LED, HIGH);
            delay(300);
            digitalWrite(LED, LOW);
            delay(300);
            j-=1;
          }
        }
        delay(1);
      }
    }

`receiveEvent` is an ISR (interrupt service routine). Don't do `delay` in an ISR. That will hang indefinitely. Thus the LED only blinks once. You could do `delayMicroseconds` for *testing*. In general an ISR should be **short**.

---

* [Interrupts](http://www.gammon.com.au/interrupts)
* [I2C](http://www.gammon.com.au/i2c)


body: I have a ICT a6-15scp-usd4-ii. I have all of the wires for it. I dont have the gambling machine it came out of and it was laying around. Is it possible to make a Light come on when a bill is put in? Can it be wired to the arduino to act as a switch per-say? If more info is needed let me know. I will make a tutorial for this if it works.

title: ICT Bill Accepter

Answers: 3

body:
Go to ICT's website to download the Installation manual (one used for many different models), there is info on the pinout for every pin on your model, along with recommended I/O interface circuit.

I am using a different model, but from what I know, if your model is a "Pulse" model, which means that when a bill is accepted, there are pulses that you can captured (the pulse width is pre-set by toggle switches, and the number of pulses depends on the value of the bill).

What I would do is to use interrupt to listen to these pulses. When the interrupt triggers, light up your LED.

body: So I know this is an old post, but I have interfaced with a BV20, and noticed most of the ICT validator's have a "busy" line that is asserted whenever the unit is transporting, validating, or storing/stacking a bill.  If you want to light something up when a bill is being handled, but not necessarily validated, that might be what you are looking for.

body:
ICT a6-15scp-usd4-ii is a pulse/parallel bill acceptor. [Here is the datasheet][1], the link in the comments is broken. A6 version uses pulse/parallel protocol (V6 version is MDB). The 110V version that you use has only pulse protocol.

Take care with the wiring, the acceptor uses dangerous  110VAC voltage.

I understand you want to make same kind of pay per time device like those used in kiddie rides machines.

There are many examples on the internet on connecting a pulse bill acceptor to Arduino. The theory is simple the bill acceptor has a PULSE output, usually in negative logic, high in idle, that send a low pulse for each monetary unit, 1 for 1$, 5 for 5$ and so on.

Sometimes, like in your case, the bill acceptor has an enable input through which you can enable or disable the acceptance. But in A6 110V this input must be connected to hot 110v lines so it's harder to handle through Arduino so you will need to use a relay or to leave-it active all the time by setting dip SW 8 to ON, see page 6 and page 9 in the manual.

**The electrical connections.**

See the connector pinout , page 5[![enter image description here][2]][2]

The credit (pulse) output uses an optocoupler so it has two lines CREDIT_RELAY_COM (pin 1) on the above connector that must be connected to Arduino GND and CREDIT_RELAY(N.O.) (pin 16) that must be connected to the digital input of Arduino that read the pulses, this digital input must have a pull-up resistor to 5V, it might be the built in pull-up activated by using pinMode(PIN, INPUT_PULLUP) but better an external resistor 1k to 4.5k.

And, of course, the main power supply , pin 4 and pin 20 to main 110 voltage and don't forget the earth ground, pin 21 for safety.

**Bill acceptor dip switch settings**

See the page 6 of the manual. For the moment just put SW8 to ON (acceptor enabled) and all other to OFF (all bills enabled, one pulse one dollar, 50ms/50ms pulses)

**The Arduino source code**

To count the pulses from a pulse bill acceptor or coin acceptor there are many examples on the internet but I did one myself, very easy to use, [find the source code here][3], that counts the pulses in background using timer1 interrupt. In this way the main loop is free for other tasks you need. You can strip the LCD part of the code if you don't use.

To work with ICT A6 you need to modify the some defines in the code: PULSE_WIDTH to 50 form 100 and PULSE_DELTA to at least 4 from 2 (because it's to small).

Connect Arduino A0 input to pin 16 (CREDIT RELAY) and to a pull-up resistor to 5V as I pointed above, and Arduino GND to pin 1 (CREDIT_RELAY_COM) and power the Arduino from some different source or through USB and the example should work now. Obviously the BILL_ACCEPTOR_ENABLE and BILL_ACCEPTOR_DISABLE macros will not work the acceptor is always enabled.

To actually make-it work as pay-per-time machine a suggestion of code will look like this:

    unsigned long finish_time = 0;
    #define MS_PER_DOLLAR 600000 //10 minutes
    //add to setup
    turn_off_the_light();// Switch a pin or something

    void loop(){
      unsigned long temp_millis;
      unsigned long temp_credits;
      temp_millis = millis()
      temp_credits = read_and_clear_pulses();
      if (finish_time < temp_millis) finish_time = temp_millis;
      finish_time += tempcredits * MS_PER_DOLLAR;
      if (finish_time > temp_millis)
         turn_on_the_light();
      else
         turn_off_the_light();
    // Do something else
    }

If you use the device uninterrupted for more than 49 days you will have the millis rollover issue  but you can find examples on the internet how to handle this.

  [1]: https://na.suzohapp.com/images/pdf/a6v6.pdf
  [2]: https://i.stack.imgur.com/TWGZ1.jpg
  [3]: https://digielservice.wordpress.com/2021/02/17/billyone-bill-acceptor-on-arduino-with-source-code-jammer-proof-easiest-way/


body:
Recently we purchased servos for use in an Arduino and began testing with servos. It turned out that the uSec for the servos differed from the online documentation and we had to find the min and maxes of the uSecs manually:

    while (Serial.available()) {
  char c = Serial.read();  //gets one byte from serial buffer
  readString += c; //makes the string readString
  delay(2);  //slow looping to allow buffer to fill with next character
 }

 if (readString.length() >0) {
  Serial.println(readString);  //so you can see the captured string
  int n = readString.toInt();  //convert readString into a number
  Serial.print("writing Microseconds: ");
  Serial.println(n);
  myServo.writeMicroseconds(n);
  readString = ""; //empty for next input
 }
The issue is that the servos don't travel the full 180 degree advertised price (more like 135-160) and that lack of angular distance is affecting performance of one of our products. **The servos can even mechanically travel a noticeable distance farther than 180, but not "programmatically" farther even when given a larger PWM uSec value that the observed "max" PWM value**

----------
**What I've found**

I looked around and apparently there are ["Servo Programmers"][1] to calibrate endpoints and midpoints, but cost an arm and a leg. I find it strange that I would have to "program" my servos. I was part of an First (FTC) robotics team using tetrix/nxt electronic control systems, and never noticed a problem with uSec values or not getting the full range of motion using the same brand of servos I currently am now.

----------

> How can I perform a low cost, easy way to simply **get the full range
> of motion I paid for**?

  [1]: http://www.instructables.com/id/Hitec-HFP-25-Programmer-How-to-Adjust-Hitec-Digita/

title: Get servo to travel full length

Answers: 1

body:
This is an **analog servo**, so there is no endpoint calibration **on the servo side**. This type of calibration is for digital servos (which can be tuned) and controllers.
On the servo description page, they talk about a stretcher. This is a translation tool to help with old controllers:  usually servos have a narrower band: 1000us to 2000us for 0° to 180°. Therefore old controllers can only do 1000us to 2000us, and would fail to achieve full range with this servo, which requires 600us to 2400us

Also, note that [RC servo input signal isn't really a PWM][1]: duty cycle doesn't matter, only lengh of the pulse does.

Your servo doc says: 600us to 2400us for -90° to +90°, which correspond to what the Servo lib does by default according to its documentation. You should be fine. What are the results of a super simple sweep-like code? eg:

    loop() {
      myServo.writeMicroseconds(600);
      delay(2000);
      myServo.writeMicroseconds(2400);
      delay(2000);
    }

  [1]: https://en.wikipedia.org/wiki/Servo_control#Pulse_duration


body:
I have a statement:
<!-- language-all: lang-cpp -->

    if(control > 100 && control < 130)
    {

      //count time 30 seconds and open pin1 for 3 seconds.

    }

How can I count 30 seconds and open a pin for 3 seconds?

title: How do I count time in seconds?

Answers: 4

body:
Rearrange the [Blink][1] example:

    if(control>100 && control<130)
    {
      //**count time 30 seconds and open pin1 for 3 seconds.**
      delay(30000);             // wait for 30 seconds
      digitalWrite(1, HIGH);    // turn the LED on (HIGH is the voltage level)
      delay(3000);              // wait for 3 seconds
      digitalWrite(1, LOW);     // turn the LED off by making the voltage LOW
    }

  [1]: https://www.arduino.cc/en/Tutorial/Blink

body:
What you can also use is non-blocking code, where `delay()` would block for the 30s. My suggesting makes use of `millis()`, one could say similar to blink without delay code example.

Here is an example of what you could place in the loop:

    //declared variable stuff here

    if(control > 100 && control < 130 && !toggled_bit){

     toggled_bit = true;  //to control the timing section
     start_time = millis();
    }
    else if (!(control > 100 && control < 130)){
     toggled_bit = false;
    }

    if (toggled_bit){
       test1 = millis()
     if(test1 - start_time > 30000){

      digitalWrite(1, HIGH);
       short_wait = millis();
       // wait for 3s after fist time
        if(short_wait - start_time > 33000)
         digitalWrite(1, LOW);
         toggled_bit = false;
        }
      }
    }

    // other code here

The code sets a 'flag', `toggled_bit`, which is checked by the `if()` later on in the loop, also it sets `start_time`. It then checks if 30s has passed and then waits an extra 3s to turn the output off after being turned on. It then resets the `toggled_bit`.

This will also allow you to check or do other things while waiting.

body:
A non-blocking version is often needed as there is often other tasks to be performed during the wait. The "blink-without-delay"-pattern is a solution but unfortunately it becomes tedious to use with several time periods and logic.

The [Timemark][1] library helps abstract the pattern and hide a lot of the details. The below sketch uses two timemarks and a simple state-machine to help reduce complexity.

    #include <Timemark.h>

    Timemark turnOnWait(30000L);
    Timemark turnOffWait(3000L);

    enum {
      IDLE,
      TURN_ON_WAIT,
      TURN_OFF_WAIT
    };
    int state = IDLE;

    const int pin = 4;
    int control = 0;

    void setup()
    {
      ...
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
    }

    void loop()
    {
      ...
      switch (state) {
      case IDLE:
        if ((control > 100) && (control < 130)) {
          turnOnWait.start();
          state = TURN_ON_WAIT;
        }
        break;
      case TURN_ON_WAIT:
        if (turnOnWait.expired()) {
          digitalWrite(pin, HIGH);
          turnOffWait.start();
          state = TURN_OFF_WAIT;
        }
        break;
      case TURN_OFF_WAIT:
        if (turnOffWait.expired()) {
          digitalWrite(pin, LOW);
          state = IDLE;
        }
        break;
      default:
        ;
      }
      ...
    }

Two timemarks are used for clarity. It is possible to use a single timemark and reinitiate it with a new time limit.

    #include <Timemark.h>

    const uint32_t TURN_ON_TIMEOUT = 30000L;
    const uint32_t TURN_OFF_TIMEOUT = 3000L;

    Timemark timemark;

    enum {
      IDLE,
      TURN_ON_WAIT,
      TURN_OFF_WAIT
    };
    int state = IDLE;

    const int pin = 4;
    int control = 0;

    void setup()
    {
      ...
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
    }

    void loop()
    {
      ...
      switch (state) {
      case IDLE:
        if ((control > 100) && (control < 130)) {
          timemark.limitMillis(TURN_ON_TIMEOUT);
          timemark.start();
          state = TURN_ON_WAIT;
        }
        break;
      case TURN_ON_WAIT:
        if (timemark.expired()) {
          digitalWrite(pin, HIGH);
          timemark.limitMillis(TURN_OFF_TIMEOUT);
          timemark.start();
          state = TURN_OFF_WAIT;
        }
        break;
      case TURN_OFF_WAIT:
        if (timemark.expired()) {
          digitalWrite(pin, LOW);
          state = IDLE;
        }
        break;
      default:
        ;
      }
      ...
    }

The [Scheduler][2] library allows the blocking version (delay) to be used. Non-blocking is achieved by context switching on yield() or delay(). Below is a rewrite using this style:

    #include <Scheduler.h>

    const int pin = 4;
    int control = 0;

    void setup()
    {
      ...
      Scheduler.start(setupController, loopController);
    }

    void loop()
    {
      ...
      delay(1000);
    }

    void setupController()
    {
      ...
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
    }

    void loopController()
    {
      ...
      if ((control > 100) && (control < 130)) {
        delay(30000L);
        digitalWrite(pin, HIGH);
        delay(3000L);
        digitalWrite(pin, LOW);
      }
      else {
        delay(100);
      }
    }

Cheers!

  [1]: https://github.com/mikaelpatel/Arduino-Timemark
  [2]: https://github.com/mikaelpatel/Arduino-Scheduler

body:
Well 30s equals 30,000ms and the arduino comes with a native function that counts in Milliseconds so the following code should work:

    Time = millis();  //time passed before entering loop…
    If((control > 100) && (control < 130))
    {
    While (millis() < Time + 30000) //counts to Thirty seconds
    {
    While (millis() < Time + 3000) // counts to three seconds
    {
    DigitalWrite(1,HIGH);
    };};};

  This way you can add some code in the while loops if u want to multitask.


body:
I am sending some data over an NRF24 link, using the [RF24Network][1]  library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as

    struct payload_t {                  // Structure of our payload
       unsigned long data;
       unsigned long datatype;
       char sensorid[20];
       unsigned long counter;
    };

As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.

At the moment I am using sensors without an internal ID, so in `loop()`, I am calling:

     writeToNetwork(voltage,'v',"nosid",packets_sent++);

My `writeToNetwork` function is defined as

     bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){

and within that, I am setting up the payload with

     payload_t payload = { data,type,sid, package };

Which gives me an

     error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]

Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the `sid` - pointer to get my array into the struct. How can I do that?

Or am I barking up the wrong tree? I tried to transfer the id as a string:

    #include <string.h>
    bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
    char sidchar[20];
    sid.toCharArray(sidchar,20);
    payload_t payload = { data,type,sidchar, package };

Which gives me the error

    array must be initialized with a brace-enclosed initializer

Which I do not understand. Doing

    char sidchar[20]={0};

gives me the same error.

  [1]: https://github.com/TMRh20/RF24Network

title: Dereferencing char into a struct

Answers: 1

body:
In your situation, your best bet is probably to use the standard C function [`strcpy`][1]:

    payload_t payload;
    char* source = "abcdef";
    strcpy(payload.sensorid, source);

Note that source string does not have to be declared as `char source[20]` and can be declared as the rather standard C string `char*`.

Also, since you are limiting the size of the string to be passed in `payload`, you may prefer to use [`strncpy`][2] which will ensure no more than 20 characters get copied:

    payload_t payload;
    char* source = "abcdef";
    strncpy(payload.sensorid, source, 20);
    // Explicitly add a string termination to the end of string
    payload.sensorid[19] = 0;

In the snippet above, please notice the last line, it is necessary in the situation where `source` string length is 20 or more non-null characters, as in this case, `strncpy` will copy all 20 characters but will not add the terminating 0 at the end of the string.

  [1]: http://www.cplusplus.com/reference/cstring/strcpy/
  [2]: http://www.cplusplus.com/reference/cstring/strncpy/


body: It's my understanding that when a Timer is used on an Arduino (in my case the Arduino Mega), it can disable analog write on some PWM pins, which pins depends on the Timer being used. For instance on the Mega, pins 44,45,46 are controlled by Timer 5.  If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

title: If a Timer is used, disabling some PWM pins, can I still use those pins for Digital write?

Answers: 2

body:
> If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

You can view the connection between the Timer and the pins as programmable. The connection is enabled by, for instance, analogWrite(). The Timer control registers have a setting for both the connection and control logic of the pin (clean, set or toggle on timer value match).

You can use the Timer to generate interrupts without connecting a pin. This is the case with micros() and millis() which get their values from a counter which is updated by an ISR on Timer 0 (overflow). analogWrite() on pin 5 and 6 connects to Timer 0 value match logic.

analogWrite() uses the Timer value match and connects the pins. Enabling only the Timer (as you suggest) will allow you to use the pins with digitalWrite(). You can also use the Timer ISR for overflow. The Timer prescale is set for analogWrite().

Cheers!

body:
When using an timer (other than by PWM) you can choose to enable it's output to a pin (which basically is what PWM does). So you can still use them as a digital pin (if you choose not to).

You could set up an PWM signal and enable timer interrupts afaik. But changing PWM, would also change the timer.

There is a difference in only using Arduino functions, or changing the registers directly.
Try to read the "timers" part of the datasheet and find some tutorials about avr/atmel/atmega register changing or/and setting up timers.


body:
I bought an Arduino Due, and I noticed unlike the other boards, the onboard LED does not flash after reset. I prefer this behavior, so I want to modify the bootloader to do this behavior when it starts. I have burnt bootloaders before, but I never modified one before.

How can I do this?

title: Modify Arduino Due's Bootloader to flash when reset

Answers: 2

body:
The Arduino Due bootloader is built-in. If you check the Arduino SAM core there are no bootloader files. There is a firmware file for the ATmega16u2 on the Programming Port. You might be able to modify this to do that (given that there is a LED to flash).

The alternative solution to a modified bootloader is modifing the init() of the Arduino SAM core. Please see https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/cores/arduino/main.cpp#L36 or https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/variants/arduino_due_x/variant.cpp#L372. Blink code as proposed by Majenko could be added there.

Cheers!

body:
You cannot.

The SAM3X's bootloader is hard-coded into ROM and can never be changed.

Ever.

Yes, I know, it sucks, doesn't it?

However, the bootloader only executes if the flash is empty (bit of an odd choice if you ask me, but there you go) so you could "emulate" the operation by flashing an LED as the first thing in your sketch.

    pinMode(13, OUTPUT);
    for (int i = 0; i < 5; i++) {
        digitalWrite(13, HIGH);
        delay(100);
        digitalWrite(13, LOW);
        delay(100);
    }
    pinMode(13, INPUT); // This will "reset" the pin to default.


body:
As told in this post:

http://forum.arduino.cc/index.php/topic,16612.0.html#

The arduino can achive up to 62.5khz with 8 bits resolution

adding this line in the setup:

    TCCR0B = TCCR0B & 0b11111000 | 0x01

sets the divisor of the timer to 1

    int output = 5;
    void setup() {
      // put your setup code here, to run once:
      TCCR0B = TCCR0B & 0b11111000 | 0x01;

    }

    void loop() {
      analogWrite(output,127);

    }

But I need a frequency of 100khz or as close as possible, the 8 bits resolution is not necessary of my porpouse, it will work just fine with 6 or 7 bits.

title: how to change increase pwm frequency by changing resolution?

Answers: 1

body:
Here's code for timer 1 on a atmega32u tested in a Teensy 2.0:

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

       // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
       // And 7.32 bits 0-159 PWM on OC1B at 100kHz
       // Output on OC1B
       // Set at TOP, Clear at OCR1B
       // WGM =15 0b1111

       DDRB |= bit(DDB5) | bit(DDB6);  // atmega32u OC1A and OC1B outputs
      // DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

       TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
       OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                              // or 16000000/(PreScaler *Ftimer)
       OCR1B  = 10;           // 10/160 duty cycle
       TCNT1 = 0 ;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      OCR1B = 160/4 -1 ; // 25% duty cycle.
    }

The trick here is using OCRxA to set the TOP value/resolution/frequency of the timer, and then using OCRxB as the PWM-controlled output.  The popular examples aim for a specific frequency with toggling, but often don't go into showing the PWM with the non-TOP OCRxx registers.

If you check the registers for your chip, this should also adapt to the other timers.  Here, I used timer1 to avoid confusing delay() and millis().


body:
I tried to assemble Adafruit's Arduino LCD 16 x 2 using the instructions [RGB LCD Shield: Control a 16x2 Character LCD using 2 pins - Assembly][1]  without any success.

After assembly, I uploaded the [HelloWorld example sketch][2] on to the Arduino. The shield doesn't seem to be working. The LCD didn't turn on.

If I push back/press the LCD it turn on. Any idea on how to troubleshoot this?

  [1]: https://learn.adafruit.com/rgb-lcd-shield/assembly
  [2]: https://github.com/adafruit/Adafruit-RGB-LCD-Shield-Library

title: Troubleshoot Arduino LCD 16 x 2 shield

Answers: 1

body:
By visually assessing the pictures, the issue seems to be due to poor soldering job.

You should try re-heating the soldering joints and make sure they are clean. There could be dry joints that may not be conducting signals.

Also you should upload pictures to your question post, not as an answer.


body:
I have been running a simple weather station composed of a Sparkfun Pro Micro (8kHz/3.3V), a DHT22 and a NRF24L01+ transceiver during the last couple of months, and I can tell you up here in Canada weather stations save lives...

The board checks the temperature and the humidity once every second and transmits the new measurements back to my home server over RF if the changes are above some threshold. As such, the board sleeps most of the time, and the transmissions happen rarely (about once to thrice per minute).

The system has been running off an iPhone charger up to now, but I am now thinking of weaning it off the mains. The maximum power consumption of the whole circuit when DHT22 is on and RF chip is transmitting remains below 200mA and many articles suggest that [with some optimization one can reduce the power draw by levels of magnitude][1]. Actually, from what I read [I gather that the average consumption of the circuit can be pushed below 1mA][2].

So, I was thinking of adding a solar panel, a charging circuit and a Li-ion battery to my setup, when I discovered these low-cost solar-powered USB power banks on several vendor websites. They make outrageous claims about their charge capacity, that in my experience one has to divide at least by two (20,000 ~= 10,000), but they are pretty rugged and seem appropriate for outdoor installation. The units seem to use a 6V/0.6W (100mA) solar cell that should theoretically be sufficient for charging the battery even if some days are less sunny or shorter.

I wonder if anyone has used one of these as a continuous power supply for an arduino kit, or can inform me about the possible limitations. The idea is not to deal with the power apparatus myself each time I want to assemble a kit.

[![enter image description here][3]][3]
[![enter image description here][4]][4]

  [1]: http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/
  [2]: http://www.instructables.com/id/SOLAR-POWERED-ARDUINO-WEATHER-STATION/?ALLSTEPS
  [3]: https://i.stack.imgur.com/QzJfE.jpg
  [4]: https://i.stack.imgur.com/UShbd.jpg

title: Sustainable power source for outdoor arduino weather station

Answers: 0


body:
Can anyone help me on how to correct my program ? I want to transmit value in string form.

I put this to TX code

    struct payload_t
    {

     String sensor1;
    };

..................

At the loop part I put this code

    String sensor1 = (String(x) + "," + String(y) + "," + String(z)) ;

In the RX part I put this code

     struct payload_t
    {

     String sensor1;
    };

At the loop part

    RF24NetworkHeader header;
    payload_t payload;
    network.read(header,&payload,sizeof(payload));

    Serial.println("Sensor1 ");

    Serial.println(payload.sensor1);

Below is the Attach picture result of RX code.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/RDwN1.jpg

Thanks in advance :)

title: How to set string in the structure part of NRF24?

Answers: 1

body:
Did you actually 'instantiate' the struct in the TX and construct `sensor1` as `payload.sensor1 = ...`? Anyways, there's still a problem.

You are using `String` in your payload. The third argument to `read` is the maximum message length that can be stored in `payload`. In your `read` call, you passed the size of payload as `MAX_LEN`. You will receive incomplete payloads since the String object in the RX `payload` struct has no content in it yet and thus `payload`'s size, which you passed as `MAX_LEN`, will be less than that of the actual payload that was transmitted. Just ditch the Strings and try:

TX:

    int vals = {x, y, z};   // guessing they are ints

    network.write(header, &vals, sizeof(vals));

RX:

    int vals[3];
    network.read(header, &vals, sizeof(vals));

    Serial.print(vals[0]); Serial.print(',');
    Serial.print(vals[1]); Serial.print(',');
    Serial.println(vals[2]);


body:
I have an Arduino Mega communicating with a Bluetooth adapter through one of the auxiliary hardware serial ports. It works, but there appears to be a corruption rate of approximately 1 in 200 small packets. In other words, about 0.5% of the packets are being corrupted, it seems. I have the option of configuring the serial mode on both ends. While I cannot decrease the baud rate for bandwidth reasons, I do have enough room to enable *parity* or a larger *stop bit* if that would help.

Granted the corruption is on the serial line and not on the Bluetooth, if I enable parity, will this actually decrease the corruption rate? Or will the corrupt bytes simply be dropped without being re-sent? In other words, what happens when the hardware detects a bad byte?

title: Will enabling parity bit actually decrease corruption?

Answers: 4

body:
Parity by itself does not reduce the error rate, it is used to detect errors. It is up to higher level protocols to determine what to do when the error is detected.

To answer your question about stop bits, going to two *might* help. The extra stop bit adds a 1-bit-time gap between characters and gives the receiver a little more time to sync up with the transmitter. If the baud rates are a little off between the sender and receiver, it would make it more likely that errors would be limited to one character rather than a whole string of them. That said, the 2 stop bit option is mostly a relic from the days of mechanical Teletype machines. These days it is usually better to make sure both clocks are at the correct frequency.

Have you determined where the errors are occurring - in the serial connection between the Mega and the BT adapter, in the BT link itself, or at the other end? With short wires, correct baud rates (check for the correct clock frequency), a good ground, and correct logic voltages, the raw error rate in the serial connection should be extremely low. I would focus on finding the source of the errors before trying to correct them.

body:
Parity doesn't, and was never intended to, decrease corruption.

All parity does is allow you to DETECT errors. If you detect errors, you still have to handle them.

Parity in memory is usually fatal - your code or data is corrupt, the solution is to halt the box, to stop this corruption (in memory) getting on to disk.

When used in communication (as it is here), parity errors usually mean you have to request a re-transmit (or, if acknowledgements are sent back, fail to send an acknowledgement and wait for an automatic re-transmit).

Also, be aware that the relevant error rate is per bit, not per packet. If a small packet (very small!) is 20 bytes, and there is corruption 0.5% of those packets, this indicates a 0.5% / 20 bytes per packet / 8 bits per byte (assuming 7 data bits, 1 parity bit, for example). This comes out to 0.003% errors.

Note that parity checks only work for 1-bit errors - in fact, a 2-bit error (in the same byte), the parity change will cancel out, and it will look ok.

An alternative to requesting re-transmits, is to use forward error correction - send redundant data (reducing your bandwidth). A very easy scheme is to send each packet twice (halving your bandwidth). You still need error checking (or some checksum) - if two packets are different, you still need to know which one was right. Checksums, on a more complex device, could let you try each combination, but for an Arduino, this would probably be too expensive (the code would take up sizable space, which an Arduino may, or may not, have spare).

All of this is usually written into higher level protocols (TCP, used for most internet file transmission, ZModem file transfer used for modems prior to the Internet). Other protocols, such as internet radio, will use either forward error correction, or will accept the occasional glitch.

body:
I am guessing that the problem is that your clock is not 100% divisable to produce exactly 115200. If so it makes sense that communication sometimes fail.

See [this question][1] for more details, in particular
the link to [WormFood's AVR Baud Rate Calculator][2].

  [1]: https://electronics.stackexchange.com/q/7334/568
  [2]: http://wormfood.net/avrbaudcalc.php

body: Parity checking will only let your code detect a corrupted byte, and not very well at that. Assuming your primary goal is to get packets transferred reliably, you'd be better off to add a checksum to each packet sent, testing the checksum when the packet is received, and asking the transmitter to re-send a failed packet. Since you only expect 1 packet in 200 to be retransmitted, your bandwidth shouldn't take a big hit.


body:
Sir/ Ma'am,
.
How to read the dimension labels of this IC?[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/36PTZ.jpg

title: (HELP)How to read Physical Dimensions in datasheets

Answers: 2

body: Values above the horizontal lines are in inches. Values below it are in mm.

body:
I have annotated your drawing a little to help you understand it better:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/hMxQV.png


body:
My company is developing a programmable remote control car which is driven by an Arduino Nano. We would like a way for the user to install software updates to the Arduino, but we don't want to give the user access to the code.

Is there a way to compile Arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Then after this how would I go about manually uploading it (to the Arduino)?

title: Is there a way to upload precompiled code to an arduino?

Answers: 2

body:
> Is there a way to compile arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Yes, you can save the .hex file produced by the compiler. If you turn on verbose output from the compiler you can find the temporary directory where it is stored. Simply copy from there to a folder for download on the website.

> And then after this how would I go about manually uploading it (To the arduino)?

You can do that with the command line tool avrdude but as that is somewhat complex with a lot of parameters it might be easier to use a graphical front-end. One such tool is [xloader][1]. There are several. This depends on your end-users and the host machine that they will be using.

You can find some more info [here][2].

Cheers!

  [1]: http://russemotto.com/xloader/
  [2]: https://github.com/euphy/polargraph/wiki/Uploading-precompiled-binary-hex-files

body:
I think if you do not publish the source code, the project will be a little bit unconstructive, both for developers and users, especially when it is based in open hardware.

You can put hex files available to users, but also the source code, allowing the community to participate in the development of your product.

Anyway, if you use third-party code in your project, such as libraries, remember to respect their licenses.

Best regards. Good luck with the project.


body:
I'm not expert in electrical circuits, maybe I am making a very simple mistake or missing some basic points with my circuit.

What I'm trying to achieve is simple, to run 2 DC motors with an ultrasonic sensor to detect obstacles and change direction. When I unplug the ultrasonic sensor everything is working fine as expected without obstacle detection but when I connect the ultrasonic sensor, sensor always responds with 0 cm distance. Then I removed 9 V battery from the circuit and plug Arduino to computer via USB, sensor works fine but motors are not working properly, it looks like the power from USB is not enough to drive motors at the same time. I've added my circuit scheme below:

[![Circuit Scheme][1]][1]

  [1]: https://i.stack.imgur.com/aBHPi.png

title: Problem with running 2 DC motors with ultrasonic sensor

Answers: 1

body:
How (acoustically) loud are the motors?  If they're the typical RC car motors, they can screech harmonics right up into the 40 KHz range typical of ultrasound ranging sensors, interfering with the sensor's ability to work at all.

How (electrically) loud are the motors?  If RC as above, they throw all sorts of transients onto the power lines (and everything else within electrical pickup range).  You might want to put some ceramic capacitors across the motor leads to absorb some of those transients.

Kudos for the suggestions to provide separate power supplies for the motors and the Arduino / sensor combination.  I'd go even further, and provide separate power for all three, and use opto-isolators for the connection between the ultrasound and the Arduino.

Some years ago I used two [Novak Super-Rooster][1] motor drivers for a battle-bot competition.  They were driven by PWM outputs of an Arduino, where 50% duty cycle was off, 0% was full speed reverse, and 100% was full speed ahead.  These were powered by a sealed lead acid battery, and driven full-out, the motors got +/- 12VDC at about 40 amps.  There was a common ground with the Arduino, going to the Super Roosters, but not the motors, and the drivers took care of the electrical shielding, with a little help from the ceramic bypass capacitors I mentioned.  Worked great!

  [1]: http://teamnovak.com/products/esc/super_rooster/index.html


body:
I am familiar with the keyword `Volatile` being used to declare variables that are shared among multiple threads on a software application (basically on a multithreaded application).

But why do I need to declare a variable as `Volatile` when running the code on an an Arduino interrupt? Is the code running in the interrupt executing on different thread? Is there something else going on?

title: Why the need to use the volatile keyword on global variables when handling interrupts in Arduino?

Answers: 2

body:
`volatile` has nothing to do with multithreading per se, and it seems to be among the most miused keywords in that area. It is never a substitute for proper synchronization.

As per standard C, `volatile` invokes mostly implementation defined behaviour of telling the compiler to not optimize away accesses to the memory a variable resides in, even if the compiler thinks there can't be any other.

This *can* be useful in the following situations where the compiler is not aware that outside means can change a variable:

 * memory mapped hardware registers
 * variables accessed from other threads but checked in a tight loop
 * variables accessed from interrupt or signal handlers but checked in a tight loop

body:
First, it's `volatile` not `Volatile`. I cover these concepts in my page about [Interrupts](http://www.gammon.com.au/interrupts) however to avoid giving a link-only answer I'll repeat the relevant bits.

---

## What are "volatile" variables?

Variables **shared** between ISR functions and normal functions should be declared `volatile`. This tells the compiler that such variables might change at any time, and thus the compiler must reload the variable whenever you reference it, rather than relying upon a copy it might have in a processor register.

For example:

    volatile boolean flag;

    // Interrupt Service Routine (ISR)
    void isr ()
    {
     flag = true;
    }  // end of isr

    void setup ()
    {
      attachInterrupt (0, isr, CHANGE);  // attach interrupt handler
    }  // end of setup

    void loop ()
    {
      if (flag)
        {
        // interrupt has occurred
        }
    }  // end of loop

---

## Critical sections ... accessing volatile variables

There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).

Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

---

### First ... when do you use "volatile" variables?

A variable should only be marked volatile if it is used both inside an ISR, and outside one.

* Variables **only** used **outside** an ISR should **not** be volatile.
* Variables **only** used **inside** an ISR should **not** be volatile.
* Variables used both **inside and outside** an ISR **should be** volatile.

eg.

    volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

---

### Atomic access

Consider this code:

    volatile byte count;

    ISR (TIMER1_OVF_vect)
      {
      count = 10;
      }

    void setup ()
      {
      }

    void loop ()
      {
      count++;
      }

The code generated for `count++` (add 1 to count) is this:

     14c: 80 91 00 02  lds r24, 0x0200
     150: 8f 5f        subi r24, 0xFF     <<---- problem if interrupt occurs before this is executed
     152: 80 93 00 02  sts 0x0200, r24   <<---- problem if interrupt occurs before this is executed

*(Note that it adds 1 by subtracting -1)*

There are two danger points here, as marked. If the interrupt fires after the lds (load register 24 with the variable `count`), but before the sts (store back into the variable `count`) then the variable might be changed by the ISR (TIMER1_OVF_vect), however **this change is now lost**, because the variable in the register was used instead.

We need to protect the shared variable by turning off interrupts briefly, like this:

    volatile byte count;

    ISR (TIMER1_OVF_vect)
      {
      count = 10;
      }  // end of TIMER1_OVF_vect

    void setup ()
      {
      }  // end of setup

    void loop ()
      {
      noInterrupts ();
      count++;
      interrupts ();
      } // end of loop

Now the update of `count` is done "atomically" ... that is, it cannot be interrupted.

---

### Multi-byte variables

Let's make `count` a 2-byte variable, and see the other problem:

    volatile unsigned int count;

    ISR (TIMER1_OVF_vect)
      {
      count++;
      } // end of TIMER1_OVF_vect

    void setup ()
      {
      pinMode (13, OUTPUT);
      }  // end of setup

    void loop ()
      {
      if (count > 20)
         digitalWrite (13, HIGH);
      } // end of loop

OK, we are not changing `count` any more, so is there still a problem? Sadly, yes. Let's look at the generated code for the "if" statement:

     172: 80 91 10 02  lds r24, 0x0210
     176: 90 91 11 02  lds r25, 0x0211  <<---- problem if interrupt occurs before this is executed
     17a: 45 97        sbiw r24, 0x15
     17c: 50 f0        brcs .+20

Imagine that `count` was 0xFFFF and was about to "wrap around" back to zero. We load 0xFF into one register, but before we load the second 0xFF the variable changes to 0x00. Now we think `count` is 0x00FF which is neither the value it had before (0xFFFF) or now (0x0000).

So again we have to "protect" the access to the shared variable, like this:

    void loop ()
      {
      noInterrupts ();
      if (count > 20)
         digitalWrite (13, HIGH);
      interrupts ();
      }  // end of loop

---

### What if you are not sure interrupts are on or off?

There is a final "gotcha" here. What if interrupts might be off already? Then turning them back on afterwards is a Bad Idea.

In that case you need to save the processor status register like this:

    unsigned int getCount ()
      {
      unsigned int c;
      byte oldSREG = SREG;   // remember if interrupts are on or off

      noInterrupts ();   // turn interrupts off
      c = count;         // access the shared variable
      SREG = oldSREG;    // turn interrupts back on, if they were on before

      return c;          // return copy of shared variable
      }  // end of getCount

This "safe" code saves the current status of interrupts, turns them off (they may already be off), gets the shared variable into a temporary variable, turns interrupts back on - if they were on when we entered the function - and then returns the copy of the shared variable.

---

## Summary

Code may "appear to work" even if you don't take the above precautions. That is because the chances of the interrupt occurring at the exact wrong moment is fairly low (maybe 1 in 100, depending on the code size). But sooner or later it will happen at the wrong moment, and your code will either crash, or occasionally return the wrong results.

So for reliable code, pay attention to protecting access to shared variables.


body:
I'm working on a project where I need to have Bluetooth capability on my Arduino Nano to send data from a sensor over to the computer. Unfortunately, I'm having a difficult time figuring out how to establish a connection from the HC-06 to the computer.

I've hooked up the HC-06 to my Arduino in a fashion similar to the picture shown below.

![HC-06 to Arduino Nano](https://i.stack.imgur.com/2xars.png)

I've also been testing it with various code that I've found online that deal with tutorials on the HC-06.  The current code I'm working with is below.

<!-- language: c -->

    #include <SoftwareSerial.h>
    SoftwareSerial BT(1, 0);

    void setup()
    {
      // set digital pin to control as an output
      pinMode(13, OUTPUT);
      // set the data rate for the SoftwareSerial port
      BT.begin(9600);
      // Send test message to other device
      BT.println("Hello from Arduino");
    }
    char a; // stores incoming character from other device
    void loop()
    {
      if (BT.available())
      // if text arrived in from BT serial...
      {
        a=(BT.read());
        if (a=='1')
        {
          digitalWrite(13, HIGH);
          BT.println("LED on");
        }
        if (a=='2')
        {
          digitalWrite(13, LOW);
          BT.println("LED off");
        }
        if (a=='?')
        {
          BT.println("Send '1' to turn LED on");
          BT.println("Send '2' to turn LED on");
        }
        // you can add more "if" statements with other characters to add more commands
      }
    }

When I search for a connection on my computer, it finds the HC-06 and I can then attempt to establish a connection.  I enter the pairing code of 1234.  It then says that a connection has been established so I go into the Bluetooth Services tab where it tells me what COM port to use (either COM7 or COM4 depending on which computer I try it on.  I've tried this on two separate computers.)

So, I open a PuTTY session and attempt to connect to the indicated COM port.  About 50% of the time, it says that a connection could not be established to the indicated COM port.  The other 50% of the time, I am able to open a PuTTY session but then nothing happens.  The green LED on the HC-06 continues to blink away no matter what I try to do.

Any help would be VERY appreciated as I feel like I've tried everything I can think of.

Thank you!

title: HC-06 Bluetooth Module on Arduino Nano

Answers: 2

body:
I agree with TisteAndii's comment. Your voltage divider is in the wrong place. You are dividing down the 3.3V signal from the HC-06 to be a maximum of 2.269 volts. However the Nano requires at least 3.5V to be considered HIGH.

Plus, you are putting 5V from the Nano into the HC-06 which may damage it.

body:
Try changing the order of the pins on the Software Serial declaration, the correct order is (Rx,Tx), so SoftwareSerial BT(0, 1);
Or, just forget Software Serial altogether and remove the first two lines and change "BT" to "Serial" to use the hardware UART on those same pins which works better.


body: I am starting to get into i2C, SPI, and other forms of communication. I have read about them and have a fuzzy idea of how they work electrically, but can someone explain how I would turn the electronic portion into the coding/controlling portion? I really want to get a great understanding of it.

title: Can someone explain how to program i2C communications without using the library?

Answers: 3

body:
The AVR microcontrollers that Arduino uses have built-in hardware support for the said protocols.

That means that you don't have to write program to control the transmission/reception process but you only need to configure the appropriate registers and the hardware will initiate transfer and inform you when it's done.  I suggest you carefully read the datasheet of the microcontroller you are using with your Arduino and you should find all the information there.  It even has code examples, so you can actually copy-paste functions and use them in your program, here is one of the examples:

    void SPI_MasterInit(void)
    {
        /* Set MOSI and SCK output, all others input */
        DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
        /* Enable SPI, Master, set clock rate fck/16 */
        SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
    }

    void SPI_MasterTransmit(char cData)
    {
        /* Start transmission */
        SPDR = cData;
        /* Wait for transmission complete */
        while(!(SPSR & (1<<SPIF)));
    }

The keywords with the capital letters are usually register and bit names: you can look them up in the datasheet.

body:
> Can someone explain how to program i2C communications without using the library?

The AVR has hardware support for this but you can implement it with the pin functions. I2C is a lot about timing the signals and detecting the reply signal from the slave.

The hardware support for I2C requires understanding of a complex state-machine. If you have implemented the I2C protocol it becomes easy to understand the hardware support and how this help remove a lot of work from the processor core. The state machine, control and status registers and interrupts, are described in the AVR product specification. There are also lots of excellent descriptions on the web. Do not miss the AVR application notes for the I2C. Most of the code in the Arduino core originated from them.

Cheers!

body:
A good way to learn how to code for these interfaces is to look at the source code for the libraries themselves. In the PC world, these will be in the directory

Program files (x86)\Arduino\hardware\arduino\avr\libraries


body:
**Desired Behaviour**

I want to send RGB values from my Arduino Uno PWM pins to an RGB LED strip.

**What I've Tried**

I've purchased this [RGB LED strip][1] and [12V power supply][2] (specs below).

I'm trying to follow [this adafruit tutorial][3] but am finding the diagram references unclear.

I've mocked up a diagram but am not sure it would work:

[![enter image description here][4]][4]

( I haven't used the `Vin` pin before, so, just to be clear, that is the pin that is connected to the positive line on the breadboard - is that how to transfer the 12V power to the breadboard? )

**Questions**

**01)**  Is the above diagram safe and sound?

**02)**  How do I connect the power supply to the RGB LED strip?

**03)**  Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

**04)**  I've seen references to `grounding` the power source, how do I do that?

**05)**  Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Printed Text on MOSFET:  IRF520 Y32K BE

MOSFET Datasheet:  [Link][5] (IRF520NPbF)

**Specifications**

*RGB LED Strip*

* LED type:  5050 SMD

* Color:  RGB

* LED quantity:  300LED

* Package:  5 Meter/REEL

* Voltage:: 12V DC

* Working Power: 14.4W

* Working temperature: -20° to 50°

* Size: ⌀180mm

* Length : 5m

* Life Span: 50000+hours

* Weight: 0.3kg

*Power Supply*

* Input Voltage: AC 100 - 240V

* Output Voltage : DC 12V, 6A

* Power : 72 Watts

* Connector Size:

* External Diameter: 5.5mm

* Internal Diameter: 2.5mm

  [1]: http://www.ebay.com.au/itm/331584281701
  [2]: http://www.ebay.com.au/itm/261991816695
  [3]: https://learn.adafruit.com/rgb-led-strips/usage
  [4]: https://i.stack.imgur.com/z8H11.png
  [5]: https://www.arduino.cc/documents/datasheets/MosfetTransistor.pdf

title: How to connect a 12V power supply to an RGB LED strip receiving RGB values via Arduino Uno PWM pins?

Answers: 1

body:
> 01) Is the above diagram safe and sound?

It looks to be OK, except one thing:

The current you can draw from the Arduino's VIN pin is limited to about 1A. That is a sixth of what your power supply can provide, and the LED strip when everything is on needs more than that (1.2A), so you could run into problems.  The limit is threefold:

* The barrel jack itself is rated at up to 1A
* There is a protection diode with a limit of 1A
* The header pins are rated at up to 1A

And of course the Arduino itself needs to use some of that available 1A.  So you might be better off splicing your LED circuit into the power supply's wire before it enters the Arduino.

> 02) How do I connect the power supply to the RGB LED strip?

Power goes in (+) to the common pin of the LED strip and then out of any of the three colour pins that happen to be connected to the ground of the power supply. That is, the ground of the Arduino in your schematic since they are (as they should be) all shared.

> 03) Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

Yes. There is circuitry on the Arduino that allows both the USB and barrel jack to be plugged in together.

> 04) I've seen references to grounding the power source, how do I do that?

That refers to connecting the external power supply's ground and the Arduino's ground together. By using the barrel jack that is all taken care of for you.

> 05) Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Not really.  They are designed to be switched with a higher voltage than the Arduino's IO pins provide.  While they will work, they may cause the LEDs to be dimmer than they should be, or the MOSFETs might get hot.  Basically a MOSFET has a "threshold" voltage range which is the voltage range at which the MOSFET transitions from off to on. That is 2V - 4V for that MOSFET, which while within the range of an IO pin isn't really that great. At 4V the MOSFET still isn't completely on. You may notice from the datasheet that the "R_DS(ON)" value - that is the resistance of the MOSFET when it is on, is measured with the gate voltage at 10V. That is a voltage where the MOSFET is guaranteed to be fully on. Anything less than that and the resistance will be higher causing more losses across the MOSFET.  I could see that instantly from the model number - it starts with "IRF".  There is a specific range from International Rectifier which is designed to be directly driven by an IO pin - these are the "IRL" (for *International Rectifier Logic-level*) series.  These have their R_DS(ON) values measured typically at a gate voltage of 4.5V and a threshold voltage in the region of 500mV to 1.5V. When directly driving from an Arduino these IRL (or equivalent from other manufacturers) are preferred.


body:
Nick Gammon's cheatsheet for the Ardunino UNO's ATmega328P (below) shows some hints on the Clear Timer on Compare (CTC) modes of AVR chips.  Most of the examples for CTC mode I find use the COMxxx registers of 01 = toggle to control the OCxx pin, which would give a 50% duty cycle at 1/2 the frequency of the timer clearing.

My question is about using the non-toggling COMxxx modes of Clear and Set, which don't seem to provide an automatic way to reset into the opposite state, as in the PWM modes.

For example:
<!-- language-all: lang-cpp -->

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

       // Timer 1 CTC mode Clearing OC1B at 0.25Hz using OCR1A to set frequency
       // Output on OC1B
       // Clear at OCR1B
       // WGM =15 0b0100

       DDRB |= bit(DDB5)| bit(DDB6);  // Teensy2.0 atmega32u OC1A and OC1B outputs
      // DDRB |= bit(DDB1)| bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)
       TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM12)  | bit(CS12);  // Set /1 prescaler
       TCCR1C = 0;  // Note that it is good to initialize the timer
                    // into a known mode before trying to set interesting TOPs
       OCR1A  = 62500U ;    // Set TOP count to 16000000/(PreScaler *Ftimer)
       OCR1B  = OCR1A/2;    //  ~50% duty cycle
       TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM12)  | bit(CS12) | bit(CS10);  // Set /1024 prescaler
       TCNT1 = 0 ;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      //OCR1B = 62500U/4-1; // 25% duty cycle.
    }

If I try the above code, I get a 0.125Hz ( 8s period signal) on PB5 and a constant low on PB6.

What is the way to set OC1B high to be cleared by the timer match?  And similarly, vice versa: clearing OC1B to be set by the timer match?

Is there a direct way or do you fiddle with COM1Bx, trigger FOC1B, and then fiddle COM1B back?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/7l2L1.png
  [2]: http://www.gammon.com.au/timers

This code uses the TCCR1C:FOC1B register to set the bit by messing with the TCCR1A:COM1Bx bits, but it seems awkward:

    void setup() {
       // Timer 1 CTC mode Clearing OC1B at 0.25Hz using OCR1A to set frequency
       // Output on OC1B
       // Clear at OCR1B
       // WGM =15 0b0100

       DDRB |= bit(DDB5)| bit(DDB6);  // Teensy2.0 atmega32u OC1A and OC1B outputs
      // DDRB |= bit(DDB1)| bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)
       TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM12)  | bit(CS12);  // Set /1 prescaler
       TCCR1C = 0;  // Note that it is good to initialize the timer
                    // into a known mode before trying to set interesting TOPs
       OCR1A  = 62500U ;    // Set TOP count to 16000000/(PreScaler *Ftimer)
       OCR1B  = OCR1A/2;    //  ~50% duty cycle
       TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM12)  | bit(CS12) | bit(CS10);  // Set /1024 prescaler
       TCNT1 = 0 ;
    }

    void loop() {
      int saveCOM;
      Serial.println(TCCR1A,BIN);
      delay(7000); // 7 seconds
      saveCOM = TCCR1A;
      TCCR1A |= bit(COM1B1) | bit(COM1B0) ; // config for set OC1B
      TCCR1C = bit(FOC1B); // force a compare to set bit
      TCCR1A = saveCOM ; // restore mode
    }

This code has the 0.125Hz on OC1A, and a semi-random series of 1-4 second long pulses on OC1B.

I was interested in playing with the CTC modes for doing long cycle/low frequency PWM.  With the normal PWMs you could range from a 1-bit 50% PWM at 8MHz to a 16 bit PWM at a frequency of 0.119Hz (8.388s)  With the CTC modes, if you could manage the sets and clears in an TIMERx_OVF_vect with a couple 16 bit registers, you could extend it to 32 bits of PWM resolution with a period up to 152 hours.

title: Timer CTC Set and Clear modes -- How to un-Clear and un-Set?

Answers: 0