message:
ICT Bill Accepter

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.

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.


sender: user

sender: assistant

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/


message:
Get servo to travel full length

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/

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


message:
How do I count time in seconds?

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?

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.


message:
Dereferencing char into a struct

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

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/


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

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.

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.


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

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?

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.


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

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.

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().


message:
Troubleshoot Arduino LCD 16 x 2 shield

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

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.


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

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 :)

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]);


message:
Will enabling parity bit actually decrease corruption?

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?

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.


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

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

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


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

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)?

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.


message:
Problem with running 2 DC motors with ultrasonic sensor

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

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


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

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?

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.


message:
HC-06 Bluetooth Module on Arduino Nano

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!

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.


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

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.

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


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

**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

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.


message:
Sending colours to vga monitor

I'm looking for a simple way to send a signal from my arduino to a vga monitor.

What would be the easiest method, and what components would be needed?

I don't need to display an image, just a solid colour.

body:
A quick Google search for "Arduino VGA" will give you a lot of information. There are a few variations on both circuits and programming, which also vary in resolution and color depth.

I was searching for this a few days ago, and these are my favorite (so far):

- http://labdegaragem.com/profiles/blogs/gerando-sinal-vga-colorido-com-arduino-completo (it is in portuguese, but you can get a pretty good idea of what to do)

- https://forum.arduino.cc/index.php?topic=320238.0 (read the whole discussion, pretty nice results)

If using a TV is also a plausible option, check the Arduino TV out library. It can be installed directly from the Arduino IDE and has a good demo.


body:
Not needing to display an actual image simplifies things substantially, as an Arduino lacks the memory and (except in a crude sense) the bandwidth to do so.

However, you cannot simply apply a steady analog voltage to the R, G, and B lines.  Not only do you have to drive horizontal and vertical sync signals, you have to blank the RGB signals when not on the active portion of the screen, otherwise the monitor will assume their steady voltage means "black" and your colors will last only as a brief flash when your device is first connected or enabled.

Generating a large rectangular field of color from an Arduino is likely to be rather challenging, but probably not impossible.  You may be able to use hardware PWM channels for the horizontal and a "color enable", and tightly coded software counters for the vertical aspect.  You can then use the "color enable" to gate a network of potentially variable resistors to establish the single color of particular interest.


body:
My page about [Arduino Uno output to VGA monitor](http://www.gammon.com.au/forum/?id=11608) has a lot of theory on it, including a sketch that produces colour bars like this:

[![Colour bars][1]][1]

---

## Code

To produce a single colour is slightly simpler, this sketch did it for me:

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

    /*
     VGA colour video generation

     Author:   Nick Gammon
     Date:     22nd April 2012
     Version:  1.0

     Connections:

     D3 : Horizontal Sync (68 ohms in series) --> Pin 13 on DB15 socket
     D4 : Red pixel output (470 ohms in series) --> Pin 1 on DB15 socket
     D5 : Green pixel output (470 ohms in series) --> Pin 2 on DB15 socket
     D6 : Blue pixel output (470 ohms in series) --> Pin 3 on DB15 socket
     D10 : Vertical Sync (68 ohms in series) --> Pin 14 on DB15 socket

     Gnd : --> Pins 5, 6, 7, 8, 10 on DB15 socket

    */

    #include <TimerHelpers.h>
    #include <avr/pgmspace.h>
    #include <avr/sleep.h>

    const byte hSyncPin = 3;     // <------- HSYNC

    const byte redPin = 4;       // <------- Red pixel data
    const byte greenPin = 5;     // <------- Green pixel data
    const byte bluePin = 6;      // <------- Blue pixel data

    const byte vSyncPin = 10;    // <------- VSYNC

    const int horizontalBytes = 60;  // 480 pixels wide
    const int verticalPixels = 480;  // 480 pixels high

    // Timer 1 - Vertical sync

    // output    OC1B   pin 16  (D10) <------- VSYNC

    //   Period: 16.64 ms (60 Hz)
    //      1/60 * 1e6 = 16666.66 µs
    //   Pulse for 64 µs  (2 x HSync width of 32 µs)
    //    Sync pulse: 2 lines
    //    Back porch: 33 lines
    //    Active video: 480 lines
    //    Front porch: 10 lines
    //       Total: 525 lines

    // Timer 2 - Horizontal sync

    // output    OC2B   pin 5  (D3)   <------- HSYNC

    //   Period: 32 µs (31.25 kHz)
    //      (1/60) / 525 * 1e6 = 31.74 µs
    //   Pulse for 4 µs (96 times 39.68 ns)
    //    Sync pulse: 96 pixels
    //    Back porch: 48 pixels
    //    Active video: 640 pixels
    //    Front porch: 16 pixels
    //       Total: 800 pixels

    // Pixel time =  ((1/60) / 525 * 1e9) / 800 = 39.68  ns
    //  frequency =  1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

    // However in practice, it we can only pump out pixels at 375 ns each because it
    //  takes 6 clock cycles to read one in from RAM and send it out the port.

    const byte verticalBackPorchLines = 35;  // includes sync pulse?
    const int verticalFrontPorchLines = 525 - verticalBackPorchLines;

    volatile int vLine;
    volatile byte backPorchLinesToGo;

    #define nop asm volatile ("nop\n\t")

    // ISR: Vsync pulse
    ISR (TIMER1_OVF_vect)
      {
      vLine = 0;
      backPorchLinesToGo = verticalBackPorchLines;
      } // end of TIMER1_OVF_vect

    // ISR: Hsync pulse ... this interrupt merely wakes us up
    EMPTY_INTERRUPT  (TIMER2_OVF_vect)

    void setup()
      {

      // disable Timer 0
      TIMSK0 = 0;  // no interrupts on Timer 0
      OCR0A = 0;   // and turn it off
      OCR0B = 0;

      // Timer 1 - vertical sync pulses
      pinMode (vSyncPin, OUTPUT);
      Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
      OCR1A = 259;  // 16666 / 64 µs = 260 (less one)
      OCR1B = 0;    // 64 / 64 µs = 1 (less one)
      TIFR1 = bit (TOV1);   // clear overflow flag
      TIMSK1 = bit (TOIE1);  // interrupt on overflow on timer 1

      // Timer 2 - horizontal sync pulses
      pinMode (hSyncPin, OUTPUT);
      Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
      OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
      OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)
      TIFR2 = bit (TOV2);   // clear overflow flag
      TIMSK2 = bit (TOIE2);  // interrupt on overflow on timer 2

      // prepare to sleep between horizontal sync pulses
      set_sleep_mode (SLEEP_MODE_IDLE);

      // pins for outputting the colour information
      pinMode (redPin, OUTPUT);
      pinMode (greenPin, OUTPUT);
      pinMode (bluePin, OUTPUT);

    }  // end of setup

    // draw a single scan line
    void doOneScanLine ()
      {

      // after vsync we do the back porch
      if (backPorchLinesToGo)
        {
        backPorchLinesToGo--;
        return;
        }  // end still doing back porch

      // if all lines done, do the front porch
      if (vLine >= verticalPixels)
        return;

      PORTD = bit (5) | bit (6);  // cyan (green + blue)
      delayMicroseconds (27);     // one scan line

      PORTD = 0;  // back to black
      // finished this line
      vLine++;

      }  // end of doOneScanLine

    void loop()
      {
      // sleep to ensure we start up in a predictable way
      sleep_mode ();
      doOneScanLine ();
     }  // end of loop

As @ChrisStratton suggested, the hardware timers are a big help.

---

## Wiring

I wired it up like this:

[![VGA wiring][2]][2]

[![VGA pins][3]][3]

---

## TimerHelpers library

The **TimerHelpers.h** library is described on my [timers](http://www.gammon.com.au/timers) page, a copy is below:

    /*
     Timer Helpers library.

    Devised and written by Nick Gammon.
    Date: 21 March 2012
    Version: 1.0

    Licence: Released for public use.

    See: http://www.gammon.com.au/forum/?id=11504

     Example:

     // set up Timer 1
     TCNT1 = 0;         // reset counter
     OCR1A =  999;       // compare A register value (1000 * clock speed)

     // Mode 4: CTC, top = OCR1A
     Timer1::setMode (4, Timer1::PRESCALE_1, Timer1::CLEAR_A_ON_COMPARE);

     TIFR1 |= bit (OCF1A);    // clear interrupt flag
     TIMSK1 = bit (OCIE1A);   // interrupt on Compare A Match

    */

    #ifndef _TimerHelpers_h
    #define _TimerHelpers_h

    #include <Arduino.h>

    /* ---------------------------------------------------------------
     Timer 0 setup
     --------------------------------------------------------------- */

    namespace Timer0
    {
      // TCCR0A, TCCR0B
      const byte Modes [8] [2] =
      {

      { 0,                         0 },            // 0: Normal, top = 0xFF
      { bit (WGM00),               0 },            // 1: PWM, Phase-correct, top = 0xFF
      {               bit (WGM01), 0 },            // 2: CTC, top = OCR0A
      { bit (WGM00) | bit (WGM01), 0 },            // 3: Fast PWM, top = 0xFF
      { 0,                         bit (WGM02) },  // 4: Reserved
      { bit (WGM00),               bit (WGM02) },  // 5: PWM, Phase-correct, top = OCR0A
      {               bit (WGM01), bit (WGM02) },  // 6: Reserved
      { bit (WGM00) | bit (WGM01), bit (WGM02) },  // 7: Fast PWM, top = OCR0A

      };  // end of Timer0::Modes

      // Activation
      // Note: T0 is pin 6, Arduino port: D4
      enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T0_FALLING, T0_RISING };

      // what ports to toggle on timer fire
      enum { NO_PORT = 0,

        // pin 12, Arduino port: D6
        TOGGLE_A_ON_COMPARE  = bit (COM0A0),
        CLEAR_A_ON_COMPARE   = bit (COM0A1),
        SET_A_ON_COMPARE     = bit (COM0A0) | bit (COM0A1),

        // pin 11, Arduino port: D5
        TOGGLE_B_ON_COMPARE  = bit (COM0B0),
        CLEAR_B_ON_COMPARE   = bit (COM0B1),
        SET_B_ON_COMPARE     = bit (COM0B0) | bit (COM0B1),
      };

      // choose a timer mode, set which clock speed, and which port to toggle
      void setMode (const byte mode, const byte clock, const byte port)
      {
      if (mode < 0 || mode > 7)  // sanity check
        return;

      // reset existing flags
      TCCR0A = 0;
      TCCR0B = 0;

      TCCR0A |= (Modes [mode] [0]) | port;
      TCCR0B |= (Modes [mode] [1]) | clock;
      }  // end of Timer0::setMode

    }  // end of namespace Timer0

    /* ---------------------------------------------------------------
     Timer 1 setup
     --------------------------------------------------------------- */

    namespace Timer1
    {
      // TCCR1A, TCCR1B
      const byte Modes [16] [2] =
      {

      { 0,                         0 },            // 0: Normal, top = 0xFFFF
      { bit (WGM10),               0 },            // 1: PWM, Phase-correct, 8 bit, top = 0xFF
      {               bit (WGM11), 0 },            // 2: PWM, Phase-correct, 9 bit, top = 0x1FF
      { bit (WGM10) | bit (WGM11), 0 },            // 3: PWM, Phase-correct, 10 bit, top = 0x3FF
      { 0,                         bit (WGM12) },  // 4: CTC, top = OCR1A
      { bit (WGM10),               bit (WGM12) },  // 5: Fast PWM, 8 bit, top = 0xFF
      {               bit (WGM11), bit (WGM12) },  // 6: Fast PWM, 9 bit, top = 0x1FF
      { bit (WGM10) | bit (WGM11), bit (WGM12) },  // 7: Fast PWM, 10 bit, top = 0x3FF
      { 0,                                       bit (WGM13) },  // 8: PWM, phase and frequency correct, top = ICR1
      { bit (WGM10),                             bit (WGM13) },  // 9: PWM, phase and frequency correct, top = OCR1A
      {               bit (WGM11),               bit (WGM13) },  // 10: PWM, phase correct, top = ICR1A
      { bit (WGM10) | bit (WGM11),               bit (WGM13) },  // 11: PWM, phase correct, top = OCR1A
      { 0,                         bit (WGM12) | bit (WGM13) },  // 12: CTC, top = ICR1
      { bit (WGM10),               bit (WGM12) | bit (WGM13) },  // 13: reserved
      {               bit (WGM11), bit (WGM12) | bit (WGM13) },  // 14: Fast PWM, TOP = ICR1
      { bit (WGM10) | bit (WGM11), bit (WGM12) | bit (WGM13) },  // 15: Fast PWM, TOP = OCR1A

      };  // end of Timer1::Modes

      // Activation
      // Note: T1 is pin 11, Arduino port: D5
      enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T1_FALLING, T1_RISING };

      // what ports to toggle on timer fire
      enum { NO_PORT = 0,

        // pin 15, Arduino port: D9
        TOGGLE_A_ON_COMPARE  = bit (COM1A0),
        CLEAR_A_ON_COMPARE   = bit (COM1A1),
        SET_A_ON_COMPARE     = bit (COM1A0) | bit (COM1A1),

        // pin 16, Arduino port: D10
        TOGGLE_B_ON_COMPARE  = bit (COM1B0),
        CLEAR_B_ON_COMPARE   = bit (COM1B1),
        SET_B_ON_COMPARE     = bit (COM1B0) | bit (COM1B1),
      };

      // choose a timer mode, set which clock speed, and which port to toggle
      void setMode (const byte mode, const byte clock, const byte port)
      {
      if (mode < 0 || mode > 15)  // sanity check
        return;

      // reset existing flags
      TCCR1A = 0;
      TCCR1B = 0;

      TCCR1A |= (Modes [mode] [0]) | port;
      TCCR1B |= (Modes [mode] [1]) | clock;
      }  // end of Timer1::setMode

    }  // end of namespace Timer1

    /* ---------------------------------------------------------------
     Timer 2 setup
     --------------------------------------------------------------- */

    namespace Timer2
    {
      // TCCR2A, TCCR2B
      const byte Modes [8] [2] =
      {

      { 0,                         0 },            // 0: Normal, top = 0xFF
      { bit (WGM20),               0 },            // 1: PWM, Phase-correct, top = 0xFF
      {               bit (WGM21), 0 },            // 2: CTC, top = OCR2A
      { bit (WGM20) | bit (WGM21), 0 },            // 3: Fast PWM, top = 0xFF
      { 0,                         bit (WGM22) },  // 4: Reserved
      { bit (WGM20),               bit (WGM22) },  // 5: PWM, Phase-correct, top = OCR2A
      {               bit (WGM21), bit (WGM22) },  // 6: Reserved
      { bit (WGM20) | bit (WGM21), bit (WGM22) },  // 7: Fast PWM, top = OCR2A

      };  // end of Timer2::Modes

      // Activation
      enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_32, PRESCALE_64, PRESCALE_128, PRESCALE_256, PRESCALE_1024 };

      // what ports to toggle on timer fire
      enum { NO_PORT = 0,

        // pin 17, Arduino port: D11
        TOGGLE_A_ON_COMPARE  = bit (COM2A0),
        CLEAR_A_ON_COMPARE   = bit (COM2A1),
        SET_A_ON_COMPARE     = bit (COM2A0) | bit (COM2A1),

        // pin 5, Arduino port: D3
        TOGGLE_B_ON_COMPARE  = bit (COM2B0),
        CLEAR_B_ON_COMPARE   = bit (COM2B1),
        SET_B_ON_COMPARE     = bit (COM2B0) | bit (COM2B1),
      };

      // choose a timer mode, set which clock speed, and which port to toggle
      void setMode (const byte mode, const byte clock, const byte port)
      {
      if (mode < 0 || mode > 7)  // sanity check
        return;

      // reset existing flags
      TCCR2A = 0;
      TCCR2B = 0;
      TimerHelpers.h
      TCCR2A |= (Modes [mode] [0]) | port;
      TCCR2B |= (Modes [mode] [1]) | clock;
      }  // end of Timer2::setMode

    }  // end of namespace Timer2

    #endif

---

## References

* [Timers](http://www.gammon.com.au/timers)
* [Interrupts](http://www.gammon.com.au/interrupts)
* [Arduino Uno output to VGA monitor](http://www.gammon.com.au/forum/?id=11608)

  [1]: https://i.stack.imgur.com/EBkxW.jpg
  [2]: https://i.stack.imgur.com/KpXrW.png
  [3]: https://i.stack.imgur.com/zvu7k.jpg


message:
Is it possible to infer the length of a neopixel string using 1-wire protocol?

I'have been looking at the [AdaFruit NeoPixels][1] recently and am trying to understand how the addressing scheme works.

All of the examples I've seen explicitly identify the length of the string (number of neopixel units) and are typically set using an array of 24-bit values to control the color of a particular neopixel.

My question is two fold:

 1. How do the neopixels know where they are in a string to allow for addressing?
 2. If the neopixels know where they are in the string, would it not be possible to potentially feed the output of the last neoxpixel back to a microcontroller to determine the number of neopixels in the string?

**OP Note** (this is my interpretation and may be suspect, but it is more or less my take away)

Thank you for all the answers on this - it has been very enlightening from ALL of the answers. General take away, the NeoPixel is not "directly" addressable in the sense that you can pick pixel "X" of "n" pixels. The string of NeoPixels acts essentially as a gigantic shift-register (as stated in one of the answers) so to "address" a particular pixel you have to update a buffer that represents the state of the entire string and then shift it down the wire. This is why micro-controllers, such as an Arduino, would have limitations on how many NeoPixels it could control. This is also why it is more practical to define the number of pixels in the string and allocate memory to represent that state.

  [1]: https://learn.adafruit.com/search?q=neopixels

body:
As far as I can make out (eg. [NeoPixels Revealed: How to (not need to) generate precisely timed signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/)) the NeoPixels are not in fact addressed, but are like a long shift register. Thus if you have 10 pixels, you have to send out 10 lots of RGB colours and then latch them. This is why you need to know how many pixels you have, so that you send out the right number of RGB bytes.

I don't think it would be particularly practical to try to detect how many pixels are in the chain, because the individual ones "reshape" the timing pulses.


body:
Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain.  Although the data wire may look continuous it isn't - the signal is electrically re-driven from each unit to the next.

For the RGB ones, they are logically three monochrome pixels of different colors, so they peel off three words rather than just one.

At any point in the chain you can determine how many logical pixels potentially remain to be updated, by counting the words you are passing on.  You can't of course tell if they are actually there, or if there are further pixels for which no data is being provided.  And you can't tell how many pixels preceded, other than to bound it by the amount of gap time from the previous update you received.


body:
As noted in Chris Stratton's answer, “Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain”.

This behavior is spelled out clearly in WS2812.pdf and WS2812B.pdf datasheets from http://www.world-semi.com :

>    The data transfer protocol use single NZR communication mode. After the pixel power-on reset, the DIN port receive data from controller, the first pixel collect initial 24bit data then sent to the internal data latch, the other data which reshaping by the internal signal reshaping amplification circuit sent to the next cascade pixel through the DO port. After transmission for each pixel, the signal to reduce 24bit. pixel adopt auto resha-ping transmit technology, making the pixel cascade number is not limited the signal transmission, only depend  on the speed of signal transmission.

This means that each WS2812 unit in a chain picks off the first 24-bit data packet, latches that data into an internal register, and passes the rest of the data on out, through reshaping circuitry.  Hence, if you put *m* packets of data into a chain and *k* packets come out, the chain length is *m-k* or more.  (The chain length may be more than *m-k* when *k* is zero.)


body:
It is possible to do this by feeding the end of the strip back into the arduino.  bunnie Huang blogged about doing this a few years ago: http://www.bunniestudios.com/blog/?p=3345

He has [schematics](http://bunniefoo.com/bunnie/phage-armband.PDF) and [firmware](https://github.com/ThePhage/phage-armband) which uses a [modified neopixel library](https://github.com/bunnie/Adafruit_NeoPixel) that can measure the length of the strip.


body:
This is certainly possible as I have now confirmed.

The code below will detect the length of a string of NeoPixels up to 10000 long.

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

    /*
     *
     * Find length of NeoPixel string.
     * Author: Nick Gammon
     * Date:   11 March 2016
     */

    #include <SPI.h>

    const unsigned long LIMIT = 10000;  // maximum pixels to test

    // Note: Connect NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega)
    //       Connect the other end of the NeoPixels to D2 (External Interrupt 0)

    void sendByte (byte b)
      {
        // send one byte to the Neopixels - note that the "off" gap is partly handled by the loop overhead
        //   gaps measured empirically to be 1.7 µs to 2 µs, so we don't need to add any more of our own
        for (byte bit = 0; bit < 8; bit++)
          {
          if (b & 0x80) // is high-order bit set?
            SPI.transfer (0b11111100);  // 1 bit - 750 ns on + 250 ns off (acceptable "on" range 550 ns to 850 ns)
          else
            SPI.transfer (0b11100000);  // 0 bit - 375 ns on + 625 ns off (acceptable "on" range 200 ns to 500 ns)
          b <<= 1; // shift next bit into high-order position
        } // end of for each bit
    } // end of sendByte

    void ledsetup()
    {
      SPI.begin ();
      SPI.setClockDivider (SPI_CLOCK_DIV2);
      SPI.setBitOrder (MSBFIRST);
      SPI.setDataMode (SPI_MODE1);   // MOSI normally low.
    } // end of ledsetup

    void sendPixel (const byte r, const byte g, const byte b)
      {
      sendByte (g);
      sendByte (r);
      sendByte (b);
      } // end of sendPixel

    void show()
      {
      delayMicroseconds (7);
      } // end of show

    volatile bool triggered;

    void myISR ()
      {
      triggered = true;
      } // end of myISR

    void setup()
      {
      ledsetup();
      Serial.begin (115200);
      Serial.println (F("Starting ..."));
      attachInterrupt (0, myISR, RISING);
      } // end of setup

    unsigned int increment = 1000;
    unsigned int counter = increment;

    void loop()
      {
      noInterrupts ();
      triggered = false;
      EIFR = bit (INTF0);  // clear flag for interrupt 0

      for (unsigned int i = 0; i < counter; i++)
        sendPixel (5, 0, 0);
      TIMSK0 = bit (TOIE0);  // throw away timer overflow interrupt
      interrupts ();
      show ();  // latch the colours - handle the interrupt meantime

      if (triggered)
        {
        if (increment <= 1)
          {
          Serial.print (F("There are "));
          Serial.print (counter - 1);
          Serial.println (F(" NeoPixels in the string."));
          Serial.flush ();
          exit (0);
          }
        else
          {  // binary search
          counter -= increment;
          increment /= 2;
          } // end of if
        } // end of if triggered

      counter += increment;

      if (counter > LIMIT)
        {
        Serial.print (F("Could not find any NeoPixels after trying "));
        Serial.print (LIMIT);
        Serial.println (F(" pixels."));
        Serial.flush ();
        exit (0);
        }

      } // end of loop

It works by sending out increasingly long strings of 24 bits, and waiting for one to "shuffle off" the other end of the string.

Connect the Data In of the NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega) as this sketch uses SPI to generate the timed sequences. Connect the far end of the NeoPixels (Data Out) to pin D2 which is External Interrupt 0.

The sketch pumps out batches of pixels, and waits for an external interrupt. When that occurs it indicates that the last pixel in the chain was reached, and passed the pixel data out Data Out to the non-existent pixel past the end of the chain.

The number of pixels needed to do this is then noted.

The sketch does a "binary search" to speed things up for long strings of pixels. The worst-case scenario (where you have either 10000 pixels, or none at all) takes 6 seconds to execute. With less pixels it will be faster. I had under a second execution time for 3 pixels in my test string.

The sketch outputs a dull red (intensity 5) so you should see the pixels light up in red if all is well. If you wanted to do it unobtrusively, you could output black (as that still results in bits being sent down the string).

Example output:

<!-- language-all: lang-none -->

    Starting ...
    There are 3 NeoPixels in the string.


message:
Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?

The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

body:
> Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

> In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

> Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the [TLC5940][1] but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or [74HC125][2] and a pull-low resistor.

Cheers!

  [1]: http://www.ti.com/lit/ds/symlink/tlc5940.pdf
  [2]: http://www.nxp.com/documents/data_sheet/74HC_HCT125.pdf


message:
A simple login page on Arduino Uno

I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

body:
<s>Arduino cannot run a web server so it is not possible to do what you want with just using an Arduino board?.</s>
It seems we can run a web server, look at the answer by @Nick Gammon below.

By using a wifi shield and connecting to a local or public web server where your page is hosted you should be able to to do it.

Don't expect to load a full fledged page on an Arduino you have to try posting a few post and get requests to get this working. It will look like a terminal based login.

What is the control page you are trying to do?

If you are ok with spending more money try using a Raspberry pi + Arduino combination.


body:
Have you tried to change Arduino Uno board to Arduino Yun board?
Yun has a Linux distribution onboard and you can easy configure a web page to control physical objects.

**Here some examples:**
http://scuola.arduino.cc/lesson/b4EoRkV/Arduino_Yn_Intro_to_web_server
https://github.com/mat-lo/yun-examples


body:
I have a page about [a tiny web server](http://www.gammon.com.au/forum/?id=12942) for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are *some* limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.

You could put the data to be display into PROGMEM (more information [here](http://www.gammon.com.au/progmem)) or onto an SD card as someone suggested.

The login and password could be stored in EEPROM.


message:
Can I use IO10 as digital IO while using SPI interface?

If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

I am actually using an Intel Galileo, with the same pinout as an Arduino Uno Rev3.

body:
> Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

> If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.

So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

[![Intel Galileo Logic Schematics][1]][1]

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the [product info][2] SPI is master only. More details schematics details [here][3].

Cheers!

  [1]: https://i.stack.imgur.com/57yHU.jpg
  [2]: https://www.arduino.cc/en/ArduinoCertified/IntelGalileo
  [3]: http://www.intel.com/content/dam/support/us/en/documents/galileo/sb/galileo_schematic.pdf


message:
ATTiny watchdog and interrupt

I'm trying to control an Arduino Barebone from an arduino with relays.
Basically when the attiny starts it should switch on the arduino for 4 seconds.
The Arduino sends a signal back to a digital pin of the attiny and as long as it is set to high the attiny should leave it working.
If it is low the attiny should switch the relay of.

the problem is some changes to the code make the interrupt reset the attiny (which would switch of the arduino) othertimes- in this case.
the interrupt doesn't work at all.

<!-- language-all: c -->

    #include <avr/sleep.h>
    #include <avr/wdt.h>
    #include <avr/io.h>
    #include <avr/interrupt.h>

    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    int pinBoard = 0;
    bool boardOn = false;
    bool startBoard_flag = false;
    int pinBoardReturn = 3;

    volatile boolean f_wdt = 1;

    void setup() {
      cli();//disable interrupts during setup
      pinMode(pinBoard, OUTPUT);
      pinMode(pinBoardReturn, INPUT);
      setup_watchdog(9);
      cbi(ADCSRA, ADEN);                   // switch Analog to Digitalconverter OFF
      // cli();//disable interrupts during setup
      for (int i = 0; i < 10; i++) {
        digitalWrite(pinBoard, HIGH);
        delay(100);
        digitalWrite(pinBoard, LOW);
        delay(100);
      }

      PCMSK |= (1 << PCINT1); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
      GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

      startBoard();

      DDRB &= ~(1 << DDB1); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
      PORTB |= (1 << PB1); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
    }

    void startBoard() {
      digitalWrite(pinBoard, HIGH);
      boardOn = true;
      startBoard_flag = false;
      cli();                                  // Disable interrupts
      delay(4000);
    }

    void shutdownBoard() {
      digitalWrite(pinBoard, LOW);
      boardOn = false;
    }

    void loop() {
      if (f_wdt == 1) { // wait for timed out watchdog / flag is set when a watchdog timeout occurs
        f_wdt = 0;     // reset flag
        if (startBoard_flag) {
          startBoard();
        }
        bool boardReturn = digitalRead(pinBoardReturn);
        if (boardOn && !boardReturn) {
          shutdownBoard();
        }
        system_sleep();
      }
    }

    //****************************************************************
    // set system into the sleep state
    // system wakes up when wtchdog is timed out
    void system_sleep() {

      // GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
      // PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin

      set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
      sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
      sleep_cpu();                            // sleep

      // PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
      sleep_disable();                        // Clear SE bit

      // sei();                                  // Enable interrupts
    }

    //****************************************************************
    // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
    // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
    void setup_watchdog(int ii) {

      byte bb;
      int ww;
      if (ii > 9 ) ii = 9;
      bb = ii & 7;
      if (ii > 7) bb |= (1 << 5);
      bb |= (1 << WDCE);
      ww = bb;

      MCUSR &= ~(1 << WDRF);
      // start timed sequence
      WDTCR  |= (1 << WDCE) | (1 << WDE);
      // set new watchdog timeout value
      WDTCR  = bb;
      WDTCR  |= _BV(WDIE);
    }
    //****************************************************************
    // Watchdog Interrupt Service / is executed when  watchdog timed out
    ISR(WDT_vect) {
      f_wdt = 1; // set global flag
    }

    ISR(PCINT_VECTOR) {
      for (int i = 0; i < 4; i++) {
        digitalWrite(pinBoard, HIGH);
        delay(1000);
        digitalWrite(pinBoard, LOW);
        delay(1000);
      }
      startBoard_flag = true;
      f_wdt = 1; // set global flag
    }

body:
Disassembling the `delay` code indicates it uses `micros` which needs interrupts on to work.

    void delay(unsigned long ms)
    {
     27a: cf 92        push r12
     27c: df 92        push r13
     27e: ef 92        push r14
     280: ff 92        push r15
     282: cf 93        push r28
     284: df 93        push r29
     286: 6b 01        movw r12, r22
     288: 7c 01        movw r14, r24
     uint16_t start = (uint16_t)micros();
     28a: d3 df        rcall .-90      ; 0x232 <micros>
     28c: eb 01        movw r28, r22

     while (ms > 0) {
     28e: c1 14        cp r12, r1
     290: d1 04        cpc r13, r1
     292: e1 04        cpc r14, r1
     294: f1 04        cpc r15, r1
     296: 79 f0        breq .+30      ; 0x2b6 <delay+0x3c>
      yield();
     298: ea d0        rcall .+468     ; 0x46e <yield>
      if (((uint16_t)micros() - start) >= 1000) {
     29a: cb df        rcall .-106     ; 0x232 <micros>
     29c: 6c 1b        sub r22, r28
     29e: 7d 0b        sbc r23, r29
     2a0: 68 3e        cpi r22, 0xE8 ; 232
     2a2: 73 40        sbci r23, 0x03 ; 3
     2a4: a0 f3        brcs .-24      ; 0x28e <delay+0x14>
       ms--;
     2a6: 81 e0        ldi r24, 0x01 ; 1
     2a8: c8 1a        sub r12, r24
     2aa: d1 08        sbc r13, r1
     2ac: e1 08        sbc r14, r1
     2ae: f1 08        sbc r15, r1
       start += 1000;
     2b0: c8 51        subi r28, 0x18 ; 24
     2b2: dc 4f        sbci r29, 0xFC ; 252
     2b4: ec cf        rjmp .-40      ; 0x28e <delay+0x14>
      }
     }
    }
     2b6: df 91        pop r29
     2b8: cf 91        pop r28
     2ba: ff 90        pop r15
     2bc: ef 90        pop r14
     2be: df 90        pop r13
     2c0: cf 90        pop r12
     2c2: 08 95        ret

---

That appears to confirm that the code in `wiring.c` is indeed what is being used on the ATtiny85 core:

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

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

Turning interrupts off and then doing a `delay` is a Bad IdeaTM.

---

> So i would rather have a counter for the watchdog in order to wait for the specified time?

Using the watchdog timer is certainly one way of waiting for 4 seconds.


message:
Arduino GSM Shields stacking

I'm researching options for a project in which I need to send/receive SMS messages to/from multiple users of different service providers.
Hoping to reduce costs, I'm thinking of forwarding the messages to a different SIM card, depending of the user's service provider (since all of them have plans with free SMS for numbers of the same provider).
Arduino GSM Shield seemed like a good option, except the shield has only one SIM card slot.
I wonder: would it be possible to stack 3 shields (there are 3 mayor service providers in my country) on the same Arduino Board and use some reasonably straightforward programming to handle the task?
Thanks in advance.

body:
Stacking might be hard, since they communicate on pins 2&3.  But if you work around that somehow, you could use Software Serial to access multiple GSM devices.

I think the GSM library has hardcoded the pins, and it might not share well with multiple, but you might be able to use SoftwareSerial or AltSoftSerial to do multiple connections, but that would be less straightforward.


body: Yes, that is easy. You need multiplexer (MUX) to forward communication pins (2 & 3) to the right GSM shield. Google for it to find the one that suits your budget.


body:
Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The [product page](https://www.arduino.cc/en/Main/ArduinoGSMShield) says each shield may require up to 1000mA.

Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.


message:
Two arduinos one power source

I was surprised that this question had no answer on Stack Exchange and I can't find much about it elsewhere so, in the hopes that it will be useful to people other than myself, I'd like to ask:

How can one power two arduinos using the same power source? Such that the first is connected by barrel jack to a 12v transformer.

I saw [this youtube video][1] which _very_ briefly mentions doing this by make the connections:

> Ardu1 --> Ardu2
>
> 5V --> 5V
>
> GND --> GND

This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the `VIN` pin somewhere along the line.

Am I correct in thinking that the second arduino would take power on it's `VIN` pin from `5V` on arduino one?

If so, where should the second arduino ground to?

  [1]: https://www.youtube.com/watch?v=Jndb2vpAWwU

body: You could put the 12v from the barrel jack on both Arduninos Vin pins by jumpering the Vin pins together instead of the Vin->+5 or +5->+5.  Then they'd have independent protection and regulation of 1A, 5V through their NCP1117ST50T3G chips.


body:
I have powered numerous arduino's via the 5V pin. I would however call this an advanced usage because there are some limitation/dangers.

First of all: Power your arduino via 5V and plugin a powered USB cable or a powered plug and it may (probably will) damage your USB or arduino or both.

Secondly; it is best to assume that all arduino's are different on behalf of the behaviour of the +5V pin. I know for a fact there is a difference with uno,yun,due.

thirdly: The way it is used on the video -you linked to- (power jack 5V arduino 1 to 5V arduino 2 and ground arduino 1 to ground arduino 2) makes that all power goes through the voltage converter on the Arduino 1.
These voltage converters can not handle much current. This is only sufficient in very low power drawing applications.

It s not a good idea to connect the 5V pin of arduino 1 to Vin of the arduino 2. This because the voltage converter on arduino 2 will not be able to provide 5V to The 5V cirquitry.

It is mutch smarter to connect the Vin from arduino 1 to Vin of Arduino2.

When I power arduino's from "standard batteries" I use a switching power supply that powers the arduino over a cut in halve USB cable. This way it is lots safer as I can add power over the jack and I can not plugin a second USB cable.


body:
Connecting the +5V pins together is acceptable providing you don't exceed the total load that the source of the +5V can provide. This would be either:

* The maximum the *USB interface* can provide:

        Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
        Device Descriptor:
        ...
          bDeviceClass            2 Communications
        ...
          idVendor           0x2341 Arduino SA
          idProduct          0x0043 Uno R3 (CDC ACM)
        ...
          Configuration Descriptor:
        ...
            MaxPower              100mA
That would seem to be 100 mA from doing `lsusb -v` on my Ubuntu system.

* The maximum that the *voltage regulator* can provide (if you are using the power jack, **or** Vin). This would depend on the model of Arduino, plus what your input voltage is (the higher the input voltage, the hotter the voltage regulator will get).

---

When I am testing things like sending I2C from one Arduino to another, I will often connect the USB to one of them, and just connect together the +5V pins (**and ground** of course) so that the second Arduino gets powered.

---

**Caveat** : my [page about power](http://www.gammon.com.au/power) indicates that without using sleep modes and other techniques, a Uno may consume 50 mA on its own. Thus connecting two Unos is likely to be reaching the limit that the USB interface can provide. Connecting three or more is likely to be problematic.

---

Regarding the USB power issue, see [How to get more than 100mA from a USB port](https://electronics.stackexchange.com/questions/5498/how-to-get-more-than-100ma-from-a-usb-port). On that page it says:

> **USB-100mA**

> USB by default will deliver 100mA of current (it is 500mW power because we know it is 5v, right?) to a device. This is the most you can pull from a USB hub that does not have its own power supply, as they never offer more than 4 ports and keep a greedy 100mA for themselves.

> ...

> Near the end of enumeration you setup device parameters. Very specifically the configuration descriptors. If you look on this website they will show you all of the different pieces that can be set. It shows that you can get right up to 500mA of power requested.

As the negotiation in this case appears to be requesting 100 mA (and not 500 mA) the port on the PC may well limit you to that.


body:
> This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the VIN pin somewhere along the line.

Power is just power. It doesn't have a "direction" like an IO pin. It just flows from a point of higher potential to a point of lower potential. If you put a load onto the 5V pin then the power will flow out of the 5V pin, through the load, to the lower GROUND potential. And that is all the other Arduino is - a load. The power flows out of the 5V, into the other Arduino, through it, and down to the lower GROUND potential.

It's just like a rechargeable battery. Put a light on the battery and the electricity flows out of the battery to light the lamp. Apply a higher voltage to the battery from another supply and the power flows out of the supply into the battery, recharging it (or making it explode if the voltage is too high).


message:
Hall effect sensor direction detection using arduino

I'm using a hall effect sensor A1356 (linear application) to measure the amount of fluid in a container. The fluid is in constant use. My doubt is I'm placing the sensor and the magnet assembly in place, such that when it is exactly half filled, the magnet's center will align with the center of the sensor. In this condition I get 100% duty cycle output from the sensor.

Condition 1: If the fluid is filled then the magnet moves above the sensor and the duty cycle reduces say to 90%.

Condition 2: If the fluid is consumed then the magnet will move below the sensor and the duty cycle reduces to say 90%.

How do I differentiate between the rise and fall of the fluid? Or is there a better way of orienting the magnet and the sensor such that this problem could be avoided?

I'm interfacing it with an Arduino UNO

body:
According to the data sheet (see below) the no-field PWM output is mid-range; north poles reduce it & south increase.

So if you had an arrangement whereby the float had north down & south up, ie a vertical bar-magnet, this would presumably give a rise-before-0 or fall-before-0 at the float vanishes, or a fall-to-minimum an rise-to-maximum as the float centres? The bit in the middle could be interesting!

From the datasheet:
"The presence of a south polarity magnetic field,
perpendicular to the branded surface of the package face,
increases the output duty cycle from its quiescent value toward
the maximum duty cycle limit. The amount of the output duty
cycle increase is proportional to the magnitude of the magnetic
field applied. Conversely, the application of a north polarity
field decreases the output duty cycle from its quiescent value."


message:
Motor Shield not giving full power, LED DIMS

I have an Adafruit Motor Shield, the V1. I have been using this thing with my OPSEPP Uno and a stepper motor with no issues. (Powered by 12v DC wall wart [CASIO]).

My question, or issue, not sure yet, is this:

Why when I connect my motor directly to the 12v power supply it operates efficiently (for my purposes) and when I run it through my Arduino with the Adafruit Motor.h library does it not power the same.

Basically on direct connection it works fine, but I want to be able to regulate the connection and reverse it, change the speed, etc.

It is possible I am utilizing the library or the board wrong.

Can someone indicate why the power or, torque seems to drop when through the board. I have tried all KHZ all speeds etc, no way to get the same 12v power directly and modulate it?

body:
According to the [Adafruit page](https://www.adafruit.com/products/81) the V1 version of the shield is not as powerful as their V2 version.

Where is the 12V coming from to get to the shield? There isn't really 12V broken out on the Uno anywhere. If it comes from Vin then there is a 0.7V drop through the reverse polarity protection diode. Plus, the tracks on the Arduino board may not be thick enough to provide enough current.

It looks like the shield may take an external power source (it is hard to tell because they discontinued it). You could try using that.