message:
How to transmit serial data from laptop USB out to Teensy?

I want to send serial data from my laptop to a Teensy LC chip through the laptop's USB port. I am not sure how to do this. From reading I have found two possibilities, which both seem to have problems:

1. Get a USB to serial adapter cable, connect the USB to the laptop, the serial to a MAX232 chip, the MAX232 chip to the UART serial on the Teensy. The ambiguity in this option lies in the fact that the MAX232 chip requires a minimum 4.5V input, and the specs on the Teensy LC say it has 3.3V and *one* 5V digital output (would this one output be compatible with a MAX232?). Also, it has only 3.3V input, so it sounds like 5V coming from the MAX232 chip would be too much (I guess I could incorporate a chip like https://www.adafruit.com/product/735 ?). Now if I were to go this route with a Teensy 3.1, which says its input pins are 5V tolerant, its voltage output is also only 3.3V (and there is no mention of any 5V output). I guess the answer here would be to incorporate a chip like https://www.adafruit.com/products/1787 ?

2. The second possibility I looked into would be a USB-to-TTL adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way and I wasn't sure if the serial communication coming through the USB-to-TTL cable would be compatible with the Teensy. I was looking at one of these cables at Sparkfun, and I think I would connect the TxD from the cable to the RX on the Teensy, the RxD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

Could someone point me in the right direction regarding sending serial data through a laptop's USB out to the Teensy?

body:
Your second option is the easiest.

> a usb to ttl adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way

Without seeing what you read, perhaps they were just talking about the fact that the Arduino is not "true" RS-232, it's only at TTL (or 3.3V) levels.

> and wasn't sure if the serial communication coming through the usb to ttl cable would be compatible with the Teensy.

It should be compatible, especially since you note that the Teeny is 5V-tolerant.

> I was looking at one of these cables at sparkfun, and I think I would connect the TXD from the cable to the RX on the Teensy, the RXD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

That's it in a nutshell!


sender: user

message:
Arduino ADS1115 PGA settings

I am trying to use an external ADC with my UNO for very precise measurement of my signal.
The ADC which I am using is ADS1115.

http://henrysbench.capnfatz.com/henrys-bench/arduino-voltage-measurements/arduino-ads1115-module-getting-started-tutorial/

This is the site which I am referring to.It says the default reference voltage of the PGA gives a resolution of 188microvolt per bit.It also indicates towards changing the reference voltage to 2.048, to still increase the resolution per bit.

Can you please guide me in how to achieve this 2.048V.

Update:
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiFpq3P89vNAhXJro8KHa6IC04QFggpMAI&url=https://cdn-learn.adafruit.com/downloads/pdf/adafruit-4-channel-adc-breakouts.pdf&usg=AFQjCNGhdMw47MRlXolMiMoHdsTwKMwMow

It seems that by adjusting the gain (page number 16-17 of 18) we can achive it.

WHat I need to know now, is where should I put that piece of code

>>> ads1115.setgain(...)

in void loop() or in void setup()

Thanks

Anupam

sender: assistant

body:
Reference voltage inputs are usually high impedance requiring little current.  So you can get by with simple circuits like a resistor and zener diode.  Here is just one I happened across:

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

Do some research to find out more about this.

For your specific case, you should read the [ADS1115 specification sheet][2].  As this ADC chip has it's own built in voltage reference.

In the Arduino paradigm, tasks that are to be executed once at the beginning of a program are placed in the setup() method.  Tasks which are to be executed repeatedly are placed in the loop() method.  As setting the gain of the ADC appears to only be done once (consult the ADS1115 PDF linked to above), it appears to fall into the former category.

  [1]: https://i.stack.imgur.com/NZmnZ.gif
  [2]: http://www.ti.com/lit/ds/symlink/ads1115.pdf

Added later...

I changed the circuit diagram after I realized it was a bad example for creating an Analog to Digital Converter voltage reference.


body:
`setup()` runs once at the beginning after the program is run.  However, `loop()` runs continuously after that.

The `setgain()` instruction is needed once at the beginning, so it should be in `setup()` function.

good luck!


message:
square wave with serial plotter

I have this code which produces a square wave:

    int output_state = 0;
    unsigned long start;

    void setup() {
      Serial.begin(1200);
      start = millis();
    }

    void loop() {

      if((millis() - start) >=1000){
        output_state = ! output_state;
        //output_state *= 1023;
        start = millis();
      }

        Serial.println(output_state);
    }

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

but should I multiply the signal by 1023:

    output_state *= 1023;

this signal is produced by the Serial Plotter:

[![enter image description here][2]][2]

Mind that the timing is right, just the x axis speeds up in zero values. Why is that happening, and how can be solved?

Any thoughts would be appreciated.

  [1]: https://i.stack.imgur.com/HRuqh.png
  [2]: https://i.stack.imgur.com/Na4s3.png

body:
It takes twice as long to print "1023" (6 bytes, including the CRLF line
terminator) than to print "0" (3 bytes). Thus, in the same time, you are
printing twice as many "0" than "1023".

If you want the data points to be printed at a consistent rate,
you can impose the printing timing just like you did on the
`output_state`. Keep in mind that you cannot print more than 20 samples
per second at 1200 bps. You could also pad the strings so that they
always have the same length:

<!-- language: lang-c++ -->

    char s[5];  // one byte for the NULL terminator
    sprintf(s, "M", output_state);
    Serial.println(s);

I would prefer the first solution (explicitly control the timing).


message:
Can I close an input?

I wan't to build a diversity controller similar to [this][1] one.

> A diversity controller is basically a circuit which detects the strongest RSSI Signal of multiple receivers and provides the data signal of that (the strongest) receiver.

As a receiver I use boscam [RX5808][2] receivers.

This receiver can be switchen between 8 channals through a 3 bit output interface. The CH1-3 outputs are active high 5V which got to be pulled to ground.

**Is it possible to put these receiver-outputs on an arduino digital inputs, to either put them on ground or not?**

How exactly do I implement this in software?

  [1]: https://github.com/sheaivey/rx5808-pro-diversity
  [2]: https://www.foxtechfpv.com/product/5.8G modules/rx5808/RX5808-Spec-V1.pdf

body:
When you output HIGH you connect the pin to +5V. When you output LOW you connect the pin to ground.  It's called a *push-pull* interface, and looks like this:

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

When it's set HIGH the p-FET is turned on and the n-FET is turned off. That connects the output direct to VDD. When it's set LOW the p-FET is turned off and the n-FET is turned off. That connects the output direct to GND.

They are just like switches, as depicted to the right. Only one is closed at a time - when HIGH the upper switch is closed, when LOW the lower switch is closed.

So you just connect the output pins of the Arduino direct to the input pins of your device and write either HIGH or LOW to them to set the 5V or GND connections you need.

  [1]: https://i.stack.imgur.com/xzL94.gif


message:
Making two points on a tm1637 display blink [ Solved ]

[![The display.][1]][1]

Hello! In my project, using a display controlled by a TM1637, I want to make the two points on the middle of the screen blink (as every clock does).

The following example, provided by the library I'm using, makes the two points blink as I want (`tm1637.point(POINT_ON/POINT_OFF);` is what enables/disbales the point):

    #include <TimerOne.h>
    #include "TM1637.h"
    #define ON 1
    #define OFF 0

    int8_t TimeDisp[] = {0x00,0x00,0x00,0x00};
    unsigned char ClockPoint = 1;
    unsigned char Update;
    unsigned char halfsecond = 0;
    unsigned char second;
    unsigned char minute = 0;
    unsigned char hour = 12;

    #define CLK 2//pins definitions for TM1637 and can be changed to other ports
    #define DIO 3
    TM1637 tm1637(CLK,DIO);

    void setup()
    {
      tm1637.set();
      tm1637.init();
      Timer1.initialize(500000);//timing for 500ms
      Timer1.attachInterrupt(TimingISR);//declare the interrupt serve routine:TimingISR
    }
    void loop()
    {
      if(Update == ON)
      {
        TimeUpdate();
        tm1637.display(TimeDisp);
      }

    }
    void TimingISR()
    {
      halfsecond ++;
      Update = ON;
      if(halfsecond == 2){
        second ++;
        if(second == 60)
        {
          minute ++;
          if(minute == 60)
          {
            hour ++;
            if(hour == 24)hour = 0;
            minute = 0;
          }
          second = 0;
        }
        halfsecond = 0;
      }
     // Serial.println(second);
      ClockPoint = (~ClockPoint) & 0x01;
    }
    void TimeUpdate(void)
    {
      if(ClockPoint)tm1637.point(POINT_ON);
      else tm1637.point(POINT_OFF);
      TimeDisp[0] = hour / 10;
      TimeDisp[1] = hour % 10;
      TimeDisp[2] = minute / 10;
      TimeDisp[3] = minute % 10;
      Update = OFF;
    }

I tried to do it as it was the famous "blink", but nothing works.

Here's what I have done:

    #include "TM1637.h" // Library for the 4-Digit Display
    #include "RTClib.h" // Library for the RTC
    #include <SoftwareSerial.h>

    #define CLK 6
    #define DIO 7

    TM1637 tm1637(CLK,DIO);
    RTC_DS1307 RTC;

    const int fotoRes = 2;

    SoftwareSerial mySerial(10, 11);

    void setup()
    {
      pinMode(fotoRes, INPUT);

      RTC.begin();
      RTC.adjust(DateTime(__DATE__, __TIME__));

      tm1637.init();
    }
    void loop()
    {
      DateTime now = RTC.now();

      tm1637.display(0,now.hour()/10);
      tm1637.display(1,now.hour());
      tm1637.display(2,now.minute()/10);
      tm1637.display(3,now.minute());

      tm1637.point(POINT_ON); //Like blink example.
      delay(500);
      tm1637.point(POINT_OFF);
      delay(500);
    }

**EDIT: `tm1637.set(0-7)` ONLY set the brightnes of the screen. What makes the two pints appear is `tm1637.point(POINT_OFF/POINT_ON)`. I'm asking how can I do to make these two points blink. Thanks.**

*Arduino UNO R3, DigitalTube library by Grove*

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

body:
I haven't used the TM1637 code, but I (think I) understand how it works.

In the original code is the following:

    void setup()
    {
        tm1637.set();
        tm1637.init();

But in your code you only do the following:

    void setup()
    {
        ...
        tm1637.init();

Have you tried adding the `tm1637.set();` line in?


body:
Calling the `point()` method only updates a flag; you see the effect the next time you try to display a number. You can use something like this:

    void show_time(DateTime &t){
      tm1637.display(0,t.hour()/10);
      tm1637.display(1,t.hour());
      tm1637.display(2,t.minute()/10);
      tm1637.display(3,t.minute());
    }

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

      tm1637.point(POINT_ON);
      show_time(now);  // changes take effect here
      delay(500);
      tm1637.point(POINT_OFF);
      show_time(now);
      delay(500);
    }


message:
Find a time server for NTP to get the current time (EtherCard library)

There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example [pool.ntp.org][1], but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the `How do I use pool.ntp.org` page, but it doesn't seem to say anything about finding IP-addresses.

**Questions**

> 1. Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
> 2. All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?

The code I currently find the easiest to understand is from the [Arduino forum][2], and has an IP address hard coded.

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the `EtherCard` libray. I do know of existence of RTC devices but I would prefer NTP.

  [1]: http://www.pool.ntp.org/zone/nl
  [2]: http://forum.arduino.cc/index.php?topic=171941.0

body:
The `EtherCard` library offers a method called `ether.dnsLookup(host)` where you ask it to look up the IP address for you.

    etherCard.dnsLookup("pool.ntp.org");

...only that might fail, so it returns a `false`:

    if (!etherCard.dnsLookup("pool.ntp.org")) {
        // Error! Do something!
        return;
    } // if

But if it works...

    if (!etherCard.dnsLookup("pool.ntp.org")) {
        // Error! Do something!
        return;
    } // if
    // At this stage, dnsLookup() worked...

    // Can now connect to IP adress in etherCard.hispip

Now: please note that `ntp.org` would prefer you to use a more precise locale than `pool.ntp.org`. If you're going to distribute your application worldwide, then that's fine. But I always use `au.pool.ntp.org` because I'm in the Australian region. There are [others][1] that you can/should use instead.

  [1]: http://www.pool.ntp.org/zone/@


message:
How is the integration time set for a camera?

I using the [TSL1401R-LF Linescan Camera Module][1], which reads in a 1 X 128 line of pixels, and I'm having trouble understanding how the integration time is set for this device.

I understand from page 9 that the minimum integration time is a constent that results from a function of the clock speed, but I don't fully understand when this integration period takes place.

According to the timing waveform (Figure 1 on Page 5) the integration period appears to be set after the first 18 clock cycles. Does this mean that the integration period is set while the camera is outputting pixels?

[![TSL1401R-LF Timing Diagram][2]][2]

How is that even possible? Also does this mean that in order to achive the minimum delay time I would have to take that time and divide it across those remaining 110 clock cycles (i.e. 307 ns for a total of 33.75 us)?

UPDATE:

This is how I am currently programming the camera. I'm using `delayMicrosecond()` after the HIGH and LOW clock impulses as well as at the end. I have enough delays to achieve the minimum 33.75 microsecond delay, but I'm still having sensitivity problems.

    int delayTime = 20;

    void readPixels()
    {
      digitalWriteFast(SI, HIGH);
      delayMicroseconds(delayTime/2);
      digitalWriteFast(CLK, HIGH);
      delayMicroseconds(delayTime/2);
      digitalWriteFast(SI, LOW);
      delayMicroseconds(delayTime/2);
      digitalWriteFast(CLK, LOW);
      delayMicroseconds(delayTime);

      for(int i = 0; i < 128; i++)
      {
        digitalWriteFast(CLK, HIGH);
        pixelsArray1[i]=analogRead(Cam1Aout);
        pixelsArray2[i]=analogRead(Cam2Aout);
        pixelsArray3[i]=analogRead(Cam3Aout);
        delayMicroseconds(delayTime);
        digitalWriteFast(CLK, LOW);
        delayMicroseconds(delayTime);
      }

      digitalWriteFast(CLK, HIGH);
      delayMicroseconds(delayTime);
      digitalWriteFast(CLK, LOW);
      delayMicroseconds(delayTime);

      delayMicroseconds(20);

    }

  [1]: http://datasheet.elcodis.com/pdf/58/61/586128/tsl1401r-lf.pdf
  [2]: https://i.stack.imgur.com/jRHqc.png

body:
It is quite a difficult system to get your head around, as you have noticed.  I'll try and break it down more logically for you...

An important thing to note is that there are two capacitors in each pixel - the *integrating* capacitor and the *sampling* capacitor. It's these two capacitors that lead to a certain amount of confusion, and it's vital to understand the role of each one.

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

Under normal sampling operation light falling on the photodiode of a pixel generates charge through the internal amplifier which is stored in the *integrating* capacitor. Simultaneously that stored voltage level is mirrored in the *sampling* capacitor.

When you send the pulse on SI a signal called `HOLD` is generated internally. This signal is sent to all of the pixels and tells them to disconnect their sampling capacitors. They do that through the switch S2.  At the same time the integrating capacitor is emptied by S1 causing a short circuit across it. That is held there for 18 clock cycles to make sure that it's completely empty. All this time the sampled voltage is still there in the sampling capacitor.

Then as you continue clocking the pulse you sent in through the SI pin is walked down a 128 bit shift register. As it pops out of each output in turn it connects the sampling capacitor of that pixel to the output buffer so you can read the voltage. It's then flushed out and re-connected to the integrating circuit again to sample the pixel again.

So there is actually multiple things happening during your 129 clocks. Reading and integrating are both happening at the same time. But you're not reading *this* set of clock's integration, but the *last* set of clocks integration.

So you have:

* SI pulse - HOLD generated, samples frozen
* 18 clocks of clearing the integrators and reading nothing much.
* 110 clocks of reading nothing much (nothing is sampled yet) and integrating.
* 1 clock to terminate
* SI pulse - HOLD generated, samples frozen
* 10 clocks of clearing the integrators and reading the **previously integrated samples 1-18**
* 110 clocks of reading the **previously integrated samples 19-128** and integrating new ones
* 1 clock to terminate
* ... etc ...

So clocks 130 to 258 are reading the light that was sampled during clocks 19 to 128.

The upshot of all this is that your integrating period is the total time taken for the 110 clocks that occur between the end of the 18 clocks that clear the integrators and the next SI pulse that creates a new HOLD signal.

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


message:
Port Not Being Found

Hey everyone I know this is a pretty common question, and I have read/tried almost everything on all the other posts here and on the arduino.cc forums, but I have been unable to fix my problem. Basically I have been using my Arduino Leonardo for a little over a month now for all sorts of things and have never had this issue with the Arduino not showing up under the port tab on the menu. I have no idea why this just started happening to me, I am using the same cable, etc, and was hoping someone could help me out. I am on a MacBook Pro by the way.

Thanks in advance.

body:
Try this...
Go to your Arduino IDE.
Under the Tools tab, go to "Board" and select Arduino Leonardo.
Then in the Tools tab, go to Port and check to see if a port is selected.
Use this link to try and find which Serial Port you should have: https://www.arduino.cc/en/Guide/MacOSX
Try plugging in the cable in different USB ports on your computer and see if the port number changes automatically.

Also, could you please say what peripherals or other things are connected to the arduino? Because for example, I know what using a Bluetooth slave with the Arduino while connected with the cable to your computer, doesn't let you upload your program. There could be similar problems to this.


body:
If you have uploaded a sketch that doesn't use the serial port, then after a couple of seconds, the Leonardo won't show up in the ports list.

To upload a new sketch you need to press and release Reset a moment after the upload to the board starts.


message:
Arduino Mega Hall sensor interrupt for a speedometer

I am having difficulty setting up an interrupt to count how many times the magnet passes so that I can count something like every 100 ms the actual speed.

I have a little code put together from the Internet:

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

    const byte LED_pin =13;
    const unsigned long wheel_circumference = 431800UL * 2UL * 31416UL; // = 94,248,000
    unsigned long Speed = 0;
    unsigned long PrevSpeed = 0;
    volatile byte hall_rising = 0; // interrupt flag
    volatile unsigned long irqMicros;
    unsigned long startMicros;
    unsigned long elapsedMicros;
    unsigned long ledFlashStartMillis;
    const unsigned long ledFlashWaitMillis = 10;
    unsigned long displayStartMillis;
    const unsigned long displayWaitMillis = 100;

    void wheel_IRQ()
    {
      irqMicros = micros();
      hall_rising = 1;
    }

    void setup()
    {
      pinMode( 2, INPUT_PULLUP ); // pin # is tied to the interrupt
      pinMode( LED_pin, OUTPUT );
      Serial.begin( 9600 ); // can this be faster? faster would be better
      delay( 1000 );

      attachInterrupt( 0, wheel_IRQ, RISING ); // pin 2 looks for LOW to HIGH change
    }

    void loop()
    {
      if ( hall_rising == 1 )
      {
        elapsedMicros = irqMicros - startMicros;
        startMicros = irqMicros;
        hall_rising = 2;
      }
      else if  ( hall_rising == 2 )
      {
        if ( millis() - ledFlashStartMillis >= ledFlashWaitMillis )
        {
          hall_rising = 0;
        }
      }

      // print speed 1000/Wait (10) times per second
      if ( millis() - displayStartMillis >= displayWaitMillis )
      {
        Speed = wheel_circumference * 0.0009 / elapsedMicros;

        displayStartMillis += displayWaitMillis;
        if ( Speed != PrevSpeed )
        {
          Serial.print(Speed); // this shows mm/sec with no remainder
          Serial.println(" kmh");
        }
        PrevSpeed = Speed;
      }
    }

But when I use this code in U8glib to display the value on a GLCD . Values are totally wrong. Can someone help me?

body:
You either need to change your code to count the number of revolutions in the interrupt.  Then divide that value in your main loop by the elapsed time to get the [angular velocity][1].  This may or may not work, as the number of revolutions may be small or even zero when you do the calculations.  Thus contributing to errors.

Or, change your code to record the elapsed time between rising edges in the interrupt.  Then find the inverse of this value.  This may be better as you could even miss an event in your main loop and still calculate the speed.  Careful not to take the inverse of zero.

To calculate speed you need to find the [rotational speed][2] of the wheel, and, consequently, how fast you are bicycling.  Use this equation:
[![enter image description here][3]][3]
...where omega is the revolutions per time as calculated by the 1st method above or reported by the interrupt routine in the 2nd method above.  Do not forget that the interrupt routine is probably using milliseconds and not seconds.

Also, do not forget to clear out the last value reported by the interrupt.  No matter which of the above 2 approaches you take.

Also consider special cases.  For instance, when you stop bicycling the interrupt will never fire.  In your main loop you may have a second counter which, when exceeded, indicates that your speed is zero.

  [1]: https://en.wikipedia.org/wiki/Angular_velocity
  [2]: https://en.wikipedia.org/wiki/Rotational_speed
  [3]: https://i.stack.imgur.com/D46Os.png


message:
Is there an easy way to turn integer values to pixels?

I'm working with a black & white camera and it gives me integer values to represent the amount of light hitting the sensor. Very bright is 1023 and totally dark is 0. The values are printed through serial and everything works fine but now I want to recreate the image based on the values.

Does anyone know if there is a simple way of doing this? I'm assuming the process would consist of looking up the value and giving a specific colored pixel in return, but I have no idea how to do this.

body:
Simplest thing may be to write down your image in [plain Portable Gray
Map format](http://netpbm.sourceforge.net/doc/pgm.html). This is a very
simple (and inefficient) ASCII format consisting of a signature (the
string "P2"), followed by the width and height of the image, followed by
the maximum possible gray level (1023 in your case), followed by the
pixel values. It's a free form format, meaning you can mix spaces and
newlines at your convenience.

Here is an example image: two rows of pixels, five columns, and
brightness increasing left to right and top to bottom:

    P2
    5 2
    1023
      0 111 222 333 444
    555 666 777 888 999

Then, any image conversion software should be able to convert that into
the format of your choice (PNG, JPEG, whatever...).


message:
Main Idea of Gyro

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

[![enter image description here][2]][2]

I have a L3G4200D (GY-50 model) gyroscope. I have been  trying to learn how a gyro sensor works. The circuit diagram is attached. I want to ask some questions;

a) According to the datasheet of L3G4200D,
    x_lsb and x_msb  (28h and 29h),
    y_lsb ,y_msb     (2Ah and 2Bh),
    z_lsb , z_msb    (2Ch and 2Dh) as  shown in the picture 3.
But according to code that in the picture first, Arduino requests bytes from 168 address of gyro (in the picture, the mark number is 1).
But, 0x28 (hex) stands for b00101000 .
What's wrong with it ?

b) Output of gyro is outputs degrees/second, is it correct?

c) In the picture 2, I did not move it, as it shown its results change, how can the angle change? It must be zero when it does not move.

d) In the picture 1, what I should calculate: highbyte*256+lowbyte ?

e) What does Fs=250,500,2000 dps mean? I know that Dps stands for Degree Per Second. But what would change by FS range, I mean if I pick either 500 or 2000 ?

  [1]: https://i.stack.imgur.com/Tvs16.png
  [2]: https://i.stack.imgur.com/1ocVG.png

body:
> According to the datasheet of L3G4200D, x_lsb and x_msb (28h and 29h), y_lsb ,y_msb (2Ah and 2Bh), z_lsb , z_msb (2Ch and 2Dh) as shown in the picture 3. But according to code that in the picture first, arduino requests biytes from 168 adress of gyro(in the pciture ,mark number is 1). But , 0x28 (hex) stands for b00101000 . what's wrong with it ?

168 is, in hex, 0xA8.  That's 0x28 with the MSB set. Why? Well, the datasheet says:

> In order to read multiple bytes, it is necessary to assert the most significant bit of the subaddress
field. In other words, SUB(7) must be equal to 1, while SUB(6-0) represents the
address of the first register to be read.

So address 0xA8 is the same as address 0x28 plus the instruction "I want to read multiple bytes".

> Output of gyro is outputs degrees/second ,is it correct ?

Kind of. The number is actually a representation of the fraction of FS. See below.

> in the picture 1,what I should calculate hightbyte*256+lowbyte ?

That is turning two 8-bit values into a single 16-bit value. It's easier to represent it using bit shifts:

    (bighbyte << 8) | lowbyte

That is, the high byte is shifted left 8 bits and the low byte is then ORed over the lower (zero) 8 bits.

> What does Fs=250,500,2000 dps mean ? I know that Dps stands for Degree Per Second .But what would change by FS range ,I mean if I pick either 500 or 2000 ?

That is the "Full Scale" value. It defines what the raw numbers from the gyro actually mean.  The gyro returns -32768 to +32767. -32768 is -FS, +32767 is +FS. So if the FS is set to 500 degrees per second then:

* -32768 is -500 degrees per second
* +32767 is +500 degrees per second

The simple formula is (using floating point maths):

   DPS = Reading / 32768.0 * FS

The format is more commonly known as *Q15* where a 16-bit value is split into 3 parts - a sign bit (bit 15), an integer part (there isn't one in this case), and 15 bits (14-0) of fraction. So the number actually represents, in Q15 format, between -1 and +1 in 65536 steps of 1/65536. That number is then multiplied by the full scale value, just like you would a percentage, to get the real DPS value.


body:
According to the [datasheet](http://www.st.com/content/ccc/resource/technical/document/datasheet/04/46/d6/00/be/d9/46/ae/CD00265057.pdf/files/CD00265057.pdf/jcr:content/translations/en.CD00265057.pdf ), FS seems to be Measurement Range. Also, I think you will find useful information in the following discussions: [Understanding the sensitivity of an L3G4200D gyroscope](https://electronics.stackexchange.com/questions/56234/understanding-the-sensitivity-of-an-l3g4200d-gyroscope) and in [How do I get gyro sensor data (L3G4200D) into degrees/sec?](https://electronics.stackexchange.com/questions/39024/how-do-i-get-gyro-sensor-data-l3g4200d-into-degrees-sec) Due to the fact that the gyro is 16 bit, the range of values would be 2^16, what makes 65536. So, the values on your screen are between -65536/2 and +65536/2, that's why max. values that you see are around 32000.

 There is always very tiny motion that the sensor can detect due to vibrations and etc. So, you should not expect the output of gyro to be a set of constants. Ideally, you should combine the data, lets say for 1 second, and find RMS value(average it) to get the result, don't look just for few instances/samples.

Also I should note that if there is ultrasound in the gyro environment, it might also cause wrong results. When outer frequencies coincide with the natural frequency of the gyro system, it leads to resonance and distorted data. This [paper](http://link.springer.com/article/10.1134/S2075108713030048#/page-1) has explanation of this phenomenon among with other impacts to the gyroscope.


message:
Why SD.exists() only looks for inside media/realroot on Intel's Galileo?

I'm following a tutorial which says SD.exists() only look for files inside media/realroot on Intel's Galileo board. I just confirmed this using SSH to create e remove files during a loop which was looking for some specific named file. Where's information about this? I searched for cpp files inside SD library and found nothing.

body:
The Intel Galileo runs Linux.  Most Linux distributions (auto) mounts media under specific directories like "/media".  So this is likely not so much a feature of the Arduino paradigm but of the Linux paradigm.  If you really want to change this you will probably have to research how Linux (specifically how the Intel Galileo version of Linux) auto mounts media.

[This][1] is a stack exchange question about auto-mounting using a Linux distribution called Ubuntu.  I am not sure how close the Intel Galileo Linux is to Ubuntu.  But it's a starting point.

  [1]: https://askubuntu.com/questions/214646/how-to-configure-the-default-automount-location


message:
Can't assign elements to index in array

I'm trying to create an array of strings. I'm building each individual string by parsing a json file and getting the strings between '{'s and '}'s. However, for some reason, my array is only assigning one index with the string i want. This is my code:

      String day = "";
      String Combo[] = {"0","0","0","0","0","0","0","0"};
      int x = 2;
      int number = 0;

      /* Read data until either the connection is closed, or the idle timeout is reached. */
      unsigned long lastRead = millis();
      while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        /* Reads one character at a time*/
        while (www.available()) {
          char sym = www.read();

          if (sym == '{') {
            x = 1;
          }
          if (x==1){
            if (!day.concat(sym)) {
              //Serial.println("concat() error!");
            }
          }
          if (x==1 && sym == '}'){
            x=0;
            Serial.println(number);
          }

          if ((number > 0) && (number < 9) && (x==0)) {
            Combo[number-1] = day;
            Serial.print(day);
            Combo[number-1] = day;

            Serial.println(F("-------------------------------------"));
            Serial.println(Combo[number-1]);

            Serial.println(F("-------------------------------------"));
            Serial.println(F("-------------------------------------"));
            day = "";
            number +=1;
            x = 2;
          } else if (number ==0 && x ==0){
            day = "";
            number +=1;
            x = 2;
          }
          lastRead = millis();

        }

      }

Which returns this:

    {
  "firstString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "secondString"
  }-------------------------------------
    {
  "secondString"
  }
    -------------------------------------
    -------------------------------------
    {
  "thirdString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "fourthString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "fifthString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "sixthString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "seventhString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "eighthString"
  }-------------------------------------

    -------------------------------------
    -------------------------------------
    {
  "secondString"
  }-------------------------------------

Based on this output I know that day is being constructed correctly but for some reason isn't assigned to an index in Combo (except "secondString")
Does anyone know what's going on?

Ideally Combo would equal: {"secondString", "thirdString", ... "eighthString"}

body:
I'm trying to understand your code.

1. It looks like `x` is a state variable, with the following values:

        2 = "Looking for start brace (`{`)"
        1 = "Found! Now accumulating `day` until stop brace (`}`)"
        0 = "Finished!"

   If so, you may instead want to use the following:

        enum States { Looking, Adding, Done };

        // int x = 2;
        States state = Looking;

        // x = 1
        state = Adding;

        // if (x==1){
        if (state==Adding) {

2. If you follow the flow of code, when `number` is still `0` and `x` finally becomes `0`, you:

 * Print out `number` - the first line of your output;
 * You then miss the main `if` (`number` is _not_ greater than `0`);
 * And enter the `else` (which is satisfied);
 * And then you immediately clear your hard-earned `day`.

3. The second time through, after `x` becomes `0` again, this time you:

  * Print out `number` - the second line of your ouptut;
  * You _do_ enter the main `if`:
     * You assign `day` to `Combo[1]`
     * You print out only the first seven entries in the the array (you want `<=7`, not `<7`)
         * This should print out `0{?}000000` (I don't know what `day` should be).
         * The fact that it doesn't seems to imply that your `concat()` failed. Can you please change it to

                    // day.concat(sym);
                    if (!day.concat(sym)) {
                        Serial.println("concat() error!");
                    } // if

      * You then print out the row of dashes - and start a new line.
   * The third time through, it seems to work - you get your `{$ "first string" $}` (where `$` represents `\n` and/or `\r` - can you strip those out?)

                  // if (x==1){
                  //    day.concat(sym);
                  if (x==1 && sym>=' '){ // Don't concat new line characters!
                      day.concat(sym);

   * And the final few times `concat()` seems to have failed again.

The reason I say "`concat()` has failed" is that it looks like `day` is still `""` when it is assigned to `Combo`

### Edit

You've changed the code so that the main if now does the following:

1. Assigns `day` to `Combo[number-1]`;
2. Prints out `day` - this seems to work;
3. Assigns `day` to `Combo[number-1]` _**again**_;
4. Prints out a line of hyphens - this works;
5. Prints out `Combo[number-1]` - this does **NOT** seem to work;
6. Prints out two lines of hyphens - this works.

Since 5 is printing out nothing, it implies that 3 failed. This really does look like you're in a low-memory condition, and the system is failing to allocate memory from the heap.

You don't say what Arduino you're working on - note that most don't have much memory, and if you're already parsing a JSON file you've probably used a lot of it. You also don't say which version of the Arduino IDE you're using. There was a `String` bug in the earlier versions.

Rather than trying to use the String class (a renowned heap hogger), you should try to use normal `char` arrays and work the buffer management yourself.


message:
Grouping multiple pins to one variable

I'm new to all of this, but it's there a way to group a cluster of pins to one variable? I don't necessarily want the grouped pounds to be sequential.

body:
Only if you drop to low-level access, and only if the pins are on the same port.

    #define pinset 0x55

     ...

    PORTC |= pinset;
    delay(1000);
    PORTC &= ~pinset;


body: In the example of the constellations, consider using an array for each constellation where each element in the array corresponds to an LED output pin. You could simply put a 1 or a 0 in each array element to indicate if you want the corresponding LED output pin on or off. It would be easy then to create a function that you would pass a constellation array and would turn the LED output pins on or off based on the contents of the array.


message:
Moving ATMEGA to 3.3V

I currently have a barebone arduino built from just an Atmega 328P and a 16Mhz external crystal.

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

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

I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?

What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

body:
> ...I have read that on low voltage I have to use 8Mhz crytstal...

Technically you can run anywhere below 13Mhz or so, so you have lots of choice.

You may also be able to use the prescaler to divide the clock by 2, either by hoping the ATmega can run the short time at 16MHz, or by programming the CKDIV8 fuse to start it at 2MHz.

> ...do I have to take the chip out to reflash with the programmer again...

If you move to a frequency within spec with either a clock change or prescaler use, yes. The bootloader and Arduino libraries expect a 16MHz clock, so you will have to rebuild the bootloader with the new clock rate, and sketches that use `delay()` et alia as well as the intrinsic delay functions will also need to be rebuilt.

> What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

It may work, it may not.


body:
> I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?

Any time-sensitive code -- such as delays and UART I/O -- will run at half speed with the 8 MHz crystal. If any of this matters, you'll need to reprogram the chip. (This will include the bootloader, which will now run at half the baud rate it used to!) If this is OK, though, you can leave it alone.

> What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

The ATmega328P isn't specified to run reliably at 16 MHz at 3.3V. Many chips will actually work at this speed, but some will fail, possibly in subtle ways or at inconvenient times. Don't rely on it working.


message:
Why doesn't this work on a Mega2560 although it works on an Arduino Uno

So, This is your code slightly altered. I am using it to read the readings of the roll and pitch of a quadcopter. I have tried using this code for a mega 2560 but it does not work in ports A0 and A1. I think it might in A5 and A6 but I am unsure how to alter this code.
THank you,
Rohan Paleja

<!-- language: lang-c++ -->

    /*  rcTiming.ino -- JW, 30 November 2015 --
     * Uses pin-change interrupts on A0-A4 to time RC pulses
     *
     * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
     *
     */

    #include <Streaming.h>
    static   byte rcOld;        // Prev. states of inputs
    volatile unsigned long rcRises[2]; // times of prev. rising edges
    volatile unsigned long rcTimes[2]; // recent pulse lengths
    volatile unsigned int  rcChange=0; // Change-counter
    int Roll, Pitch;
    // Be sure to call setup_rcTiming() from setup()
    void setup_rcTiming() {
      rcOld = 0;
      pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
      pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

      PCMSK1 |= 0x0F;       // Four-bit mask for four channels
      PCIFR  |= 0x02;       // clear pin-change interrupts if any
      PCICR  |= 0x02;       // enable pin-change interrupts
    }
    // Define the service routine for PCI vector 1
    ISR(PCINT1_vect) {
      byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
      byte changes = rcNew^rcOld;   // Notice changed bits
      byte channel = 0;
      unsigned long now = micros(); // micros() is ok in int routine
      while (changes) {
        if ((changes & 1)) {  // Did current channel change?
          if ((rcNew & (1<<channel))) { // Check rising edge
            rcRises[channel] = now;     // Is rising edge
          } else {              // Is falling edge
            rcTimes[channel] = now-rcRises[channel];
          }
        }
        changes >>= 1;      // shift out the done bit
        ++channel;
        ++rcChange;
      }
      rcOld = rcNew;        // Save new state
    }

    void setup() {
      Serial.begin(9600);
      Serial.println("Starting RC Timing Test");
      setup_rcTiming();
    }

    void loop() {
      unsigned long rcT[2]; // copy of recent pulse lengths
      unsigned int rcN;
      if (rcChange) {

        // Data is subject to races if interrupted, so off interrupts
        cli();          // Disable interrupts
        rcN = rcChange;
        rcChange = 0;       // Zero the change counter
        Roll = rcTimes[0];
        Pitch = rcTimes[1];

        sei();          // reenable interrupts

        Serial <<  " " << Roll << " " << Pitch
           << " "  << rcN << endl;

      }
      sei();            // reenable interrupts
      delay(1000);
    }

body:
You are trying to do an Pin Change Interrupt on Port F (A0-A7). On the arduino Uno, this port does support PCINT but not on the Arduino Mega.

An option is to use the Port K for the PCINT. Instead of A0 and A1 you then use A8 and A9. A few little changes in the code should do the job:

    void setup_rcTiming() {
    rcOld = 0;
    pinMode(A8, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
    pinMode(A9, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

    PCMSK2 |= 0x0F;       // Four-bit mask for four channels
    PCIFR  |= 0x04;       // clear pin-change interrupts if any
    PCICR  |= 0x04;       // enable pin-change interrupts
    }

and

    ISR(PCINT2_vect) {
    byte rcNew = PINK & 15;
    ...
    }


message:
How to make a Smart Light Bulb?

I was wondering what I would need and what I should do, to make a **Smart Light Bulb**, like the [Hue one][1] from Philips.

1. I know these light bulbs can be **controlled** by their **Apps** from the smartphone, is there a way I can achieve this too?

2. What **components** would I need to purchase?

3. Is there a reference or a tutorial on how I should **program** this light bulb?

  [1]: http://www2.meethue.com/it-it/

body:
You could use an ESP8266 NODEMCU. There is an example for making it emulate a Hue bridge ( https://github.com/probonopd/ESP8266HueEmulator ).
To have the official bridge control your lights would take Zigbee and finding out the protocol that Philips uses. Their API is open source, however the zigbee protocol they use is not afaik.
ESP8266 is a very cheap solution that works with arduino ide and does not need an arduino. There are powerplugs which have an ESP8266 in them (https://www.itead.cc/smart-home/sonoff-sv.html)


message:
Running sensor input for given time, stopping, then running seperate scheduled relay output

I've set up an Arduino Uno to run a pretty basic garden watering schedule, with the delay function.

I've now built a solar thermal water heater with a pump and tried running it separately through a 555 timer using a thermistor (33k Ohm approx). I couldn't get this running as the change in resistance with a water temperature rise to 30 deg or so wasn't enough to trip and untrip the 555 timer (thermistor at about 20 k at 20 deg, maybe 50k at 30 deg). (Any pointers to circuits that achieve this would be appreciated by the way.)

I've decided to try to run the solar thermal motor with my arduino set up as I have 2 relays free in a relay shield. My question is how I can run the sensor to start the solar thermal pump, then stop operating the solar thermal system and return to the garden watering code, then restart the sensor input, and so on. The issue is that my power supply is only 1 Amp, and running both systems at once might overheat it.

Hope this makes sense,
Brian

body:
If you are just running the relays off the 1 Amp supply, and there aren't more than 6 relays they shouldn't draw more than an amp.(I will edit this statement if need be)

What you can do in the way of coding you can is to do a classic spinoff of using the `millis()` function.

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

    //monitors temperature and schedules its operations
    //RSM
    #define TimeBetweenHydration 10000  //10 seconds
    #define TimeBetweenThermal 1000  //1 second
    #define Temperature_Thresh  25   //25°C

    float temperature = 0.00;

    unsigned long lastTempReadTime = 0;  //keep track of the time temperature was checked
    //boolean MotorOn = false;  //state monitoring

    unsigned long lastWaterTime = 0; //last time the system did something with the watering thing
    //boolean Watering = false; //state monitoring

    // other variables related to specifics
    //…
    //

    void setup(){

    //setup of analog inputs
    //setup of digital pins

    }

    void loop(){

     unsigned long presentTime = millis();

    if((presentTime - lastTempReadTime) > TimeBetweenThermal){
    lastTempReadTime = presentTime;
     int inADC = analogRead(0);

      //do whatever conversion is needed to get a value of the temperature
    temperature = inADC*3.14;

    if(temperature > Temperature_Thresh){

    //   if(!MotorOn){
         digtalWrite(RLY, HIGH); //turn on pump
    //     MotorOn = true;
    //  }
     }
      else{
      digitalWrite(RLY, LOW); //turn off pump
      }
    }

       if((presentTime - lastWaterTime) > TimeBetweenHydration){
       lastWaterTime = presentTime;

    //put your watering code stuff here

      }
    }

If you want to make the pump run without a microcontroller you could use a comparator with the thermistor and use its output to switch a transistor. I do not have the 555 timer art skills.

[![thermistor controls with comparator][1]][1]

T1 is you thermistor. You should use the values listed for R1 - R3. The transistor, coil and flyback diode are there to show how you should connect it up, the coil could be a motor or a relay to control the motor. The comparator changes around the 30-40Kohm mark.

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


body:
I really appreciate your answer, thanks. I knew I'd have to let go of the delay function at some stage, and this is the moment I think ;)

As for the PS, I'm actually also powering two solenoid valves and the arduino through the same PS, so just being on the safe side.

I wasn't too happy with a transistor circuit I made previously, but I'll give yours a go for sure. I actually came up with a workaround, which is probably pretty lame. I rigged up a second 555 timer with a large resistor to switch on and off the supply to the first 555 with thermistor every minute or so (a la flashing LED). So the thermistor now goes to temp, switches on the load, but then won't switch it off; the second 555 then resets the first 555, load switches off and either immediately switches on again if at temp, or stays off. Pretty ugly, right!


message:
Arduino fast start not working properly

I have an Arduino 328p (custom) and I can program it using a FTDI header.

However, when I power it from the FTDI using only the RAW (5V) and GND, it only executes simple programs (example blink). If in my sketch I attempt to use SPI for example, it will just get stuck.

If I power the arduino from the FTDI with the DTR pin connected, it will work just as expected for any sketch. I can even remove the DTR pin at this point and there will be no issue.

What could be the cause of this behavior?
Can it be an issue with optiboot fast start?

**PS:** FTDI is configured for 5V but VCC for the Arduino is 3.3V (I'm using the [MCP1703](http://www.microchip.com/wwwproducts/en/en530838) regulator). This means that the Arduino is powered by 3.3V but the RST pin will have 5V.
**PPS:** The Arduino is running at 16MHz

body:
The reason for this issue is to do with SPI.

Basically in my custom arduino I have a 4Mbit flash and it communicates over SPI.
It seems that when the RST pin is connected it also automatically initializes the SPI protocol.

When the arduino is powered from RAW + GND directly from an external power source you need to initialize SPI manually.

In your sketch you need to:

        #include <SPI.h>

        void setup() {
            SPI.begin(); // this needs to be invoked before any SPI device gets initialized

            // initialize and use SPI devices
        }


message:
Cannot enter programming mode on Arduino Uno

I have an Arduino Uno that I've been programming with an [AVR Dragon][1] through Atmel Studio 7.

I did two things in close proximity, and I'm not entire sure which action is the culprit. I tried using the [DebugWIRE][2] interface (for the first time) instead of ISP in the tool select screen. I also hit the Arduino's reset button as Atmel Studio was compiling/uploading to the Arduino (stupid, I know.)

Now I cannot program with [ISP][3] the normal way, or do anything really.  If I try to upload to the Arduino I get:

[![Enter image description here][4]][4]

I've tried to use the device programming feature using the Dragon and change the fuses as I've read about in other posts and get:

[![Enter image description here][5]][5]

I've tried burning a new bootloader with the Arduino IDE and the IDE tries ten times, but it tells me that the programmer is not responding.

When I plug my AVR ISP mk2 into a different Arduino Uno I get a nice constant green light. If I plug it into the board I've been discussing it blinks red.

I'm not sure where to go from here...

  [1]: https://en.wikipedia.org/wiki/Atmel_AVR#AVR_Dragon
  [2]: https://en.wikipedia.org/wiki/DebugWIRE
  [3]: https://en.wikipedia.org/wiki/In-system_programming
  [4]: https://i.stack.imgur.com/2Ow4e.png
  [5]: https://i.stack.imgur.com/kmxmA.png

body: I think either the chip or the board is fried. Try swap the chip (only the chip) to the other board and retry loading the program.


message:
arduino + GSM/GPRS SIM 900A cannot able to read a message

Here I am using Arduino uno and GSM sim900A, I want to read sms from sim900A. But i am trying to read message, it is showing the empty values. I tried different methods, but no use. Here I have added my script. Please help me.

    #include <avr wdt.h="">
    String phoneSMS = "+91xxxxxxxxxx";
    String messageTxt;
    void setup()
    {
    Serial.begin(9600);
    delay(60000);
    srl_msg();
    }
    String srl_msg()
    {
    Serial.println("AT+CMGF=1\r");
    delay(1000);
    Serial.println("AT+CNMI=2,2,0,0,0");
    delay(1000);
    Serial.println("AT+CMGL=\"ALL\"\r"); // to read ALL the SMS in text mode
    delay(1000);
    char txtmsg2[100]; // AT command output
    String date = readSerial(txtmsg2);
    String value = date.substring(1, 50);
    messageTxt = "Internal - Heart Beat;";
    messageTxt.concat(value);
    Serial.println(value);
    SendSMS(messageTxt);
    }
    void loop()
    {
    }
    void SendSMS(String message)
    {
    Serial.print("at+cmgf=1\r");
    delay(1000);
    Serial.print("at+cmgs=\"");
    Serial.print(phoneSMS);
    Serial.println("\"");
    delay(1000);
    Serial.println(message);
    delay(1000);
    Serial.print((char)26);
    delay(15000); // AAN
    }
    String readSerial(char result[])
    {
    int i = 0;
    while (Serial.available() > 0)
    {
    char inChar = Serial.read();
    if (inChar != '\r')
    {
    result[i] = inChar;
    i++;
    }
    }
    return result;
    }

output is look like this:
AT+CMGF=1

OK

AT+CNMI=2,2,0,0,0

OK
AT+CMGL="ALL"

OK

body:
wdt.h is just time handling data library, and have no methods for *send* or *receive* sms...

Your method: `SendSMS(String message)`

 is just printing serial labels and counting a char that you are putting in the serial monitor.

Try this [GSM][1] example...

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


body:
Check you sim card inbox. I also had the same problem, and it turns out the sim card sms inbox capacity is full.
You can also try to use another library, here is one of [them][1]

  [1]: https://github.com/Seeed-Studio/GPRS_SIM900


message:
Why/when to use IoT publish/subscribe protocols rather then RESTful HTTP?

I am sending data (GPS coordinates) from Arduino once a minute with HTTP POST request to REST API (in OpenShift PaaS). Data is then stored to MySQL db.

Would so called "IoT" publish/subscribe protocols (XMPP, MQTT) be better? Why?

When exactly do you use those two protocols rather than Restful HTTP? Would I really save a significant baterry energy using them?

AFAIK in those protocols machine would "publish" a data to broker and my app would subscribe to it. If I would like to gather data every minute in my app I guess that I would got to have some CRON job that would subscribe to data every minute? Or how would data gathering be achieved?

body:
Basically, MQTT reduces latency where there's relatively high latency like Wi-Fi by keeping the TCP connection alive so that data can be published and received very quickly. It uses port 1883 and not 80.
As I understand it, the publishers and subscribers connect once to the broker and then ping the broker regularly to keep the connection alive; how often the broker is pinged depends on the pre-agreed keep-alive period. MQTT packets are also significantly smaller than HTTP requests. If the connection is somehow broken, the client repeatedly tries to re-establish the connection and when successful, the subscribers re-subscribe.

Subscribers define callbacks that are called after a topic has has been updated by some publisher. MQTT is best for time-critical jobs where HTTP requests would just take too long and where quick notification of changed topics is desired. I'm not sure but it will probably consume more battery power, since there's that matter of a constant TCP link to the broker.

Since you're only expecting data updates every minute, I think it makes more sense to connect and GET the feed data from the server every 60 seconds. You can use the feed's `Last-updated` time-stamp (if it doesn't exist, create one) to check if the feed has been updated by the Arduino yet. An MQTT technique would just spend most of the time connected to a broker for no reason since you already know that the update events occur every minute; that is a significant amount of time and power spent waiting for predictable data.

However, you could wait for about 55 seconds, subscribe to the topic and when you get the new data, you disconnect and then wait for 55 seconds again, though I dont know if this will be much of an improvement over REST. If you use this method, you can also set the keep-alive period to be just about 10 seconds, so that the Arduino has enough time to update the feed before your app is notified and there's no need for regular pings.

If you decide to go with MQTT, check out [this Arduino library][1].

  [1]: https://github.com/knolleary/pubsubclient


body: In my applications, the biggest power drain is turning on the radio to transmit data. I often keep the radio off, collect data points, and then turn on the radio to send multiple pieces of data together as one request using a RESTful HTTP call. For my case, RESTful HTTP is way more efficient since I do not need an always on connection.


body:
(shameless self-promotion)  I did a talk on iot stuff this year at our local code camp.  Notes are here: https://github.com/adbacker/bcc2016/blob/master/2016bcc-iotonthecheap.pdf

Super simplified per my limited experience:
(experts correct at will :-)  )

MQTT protocol:
<list>

requires a broker

maintains a connection to the broker (which allows for push notifications back to the device)

was specifically designed for "small footprint" applications (read: limited RAM and processing power)

</list>

MQTT is optimized for sending simple data.  GPS coordinates would be a good fit. I'm sure MQTT *could* be used to send complex data (ie: large json objects) but that doesn't seem to be what it's designed for.

You're not looking for push notifications back to the device, nor are you maintaining a connection to the REST server so (from a practical standpoint) I'm guessing your battery life improvement would be minuscule at the very best converting the solution to mqtt.

Adafruit has a pretty good mqtt tutorial and libraries, as well as a beta service that provides broker services: https://learn.adafruit.com/adafruit-io/mqtt-api

Also, for super-duper-easy IOT setups (that admittedly use a custom protocol), let me recommend blynk.  ( www.blynk.cc )  It's free and so easy I rewrote my entire presentation around it.  Additionally, there are (free) blynk ios and android apps that allow creation of custom dashboards that communicate (via the also-free blynk broker) with your device of choice.  If you host the broker server (also free) yourself, it has it's own REST api that allows data access to/from your device.


body:
In my experience ReST is good for real-time data transfer and processing but has a lot of overhead for simple message passing. Plus, there's no queuing in it so store-forward configurations are troublesome.

MQTT is a message queue transport system where the message can be placed on the channel by the publisher and will stay there until the subscriber picks it up. So you can have some rudimentary store-forward capabilities with this. Also MQTT is more transparent and multicast so communicating to many nodes is no different than communicating to one.

With that, each have their place and use and ReST is great for sending large items (JSON blobs), sending data for calculation and getting it back, and for requesting a specific dataset. MQTT is more for "here's my sensor data every second, enjoy".


message:
Arduino PWM fading led in assembly

I'm writing Arduino UNO (=ATMega328P-PU) programs in assembly to save memory, so I use avra.exe (same as atmel studio's avrasm32) to compile and avrdude to upload, and simple programs like blinking run fine. But now i tried to half-bright a LED with pwm. I checked up my code for errors but I didn't find any, and the LED just full brighs. I checked wiring too. I'm getting struck :c. Here's my pwm.asm code:

    .nolist
    .include "m328pdef.inc"
    .list

    .cseg
    .org 0x00
         rjmp start
    .org 0x34
     start: sbi ddrb, 5 ;pin 13
            sbi portb, 5 ;pin 13 on, just to compare with the PWMed led
            sbi ddrd, 5 ;pin 5 pwm
            ldi r16, 0b00100011 ;fast pwm mode, non inverted pwm at oc0b = pin 5 (right?)
            out tccr0a, r16 ;I'm using Timer0
            ldi r16, 0b00000001 ;no prescaler
            out tccr0b, r16
            ldi r16, 128 ; duty cycle = 50%
            out ocr0b, r16

      loop: rjmp loop

body: I tried your program, after converting it to GNU-as syntax. It works as expected, as seen on the scope. Your problem may be simply that the difference between 50% ON and 100% ON is not very obvious to the eye because of its [logarithmic perception](https://en.wikipedia.org/wiki/Weber–Fechner_law).


body:
you have to set the PRR timers on

start:  lds     r16,PRR
        andi    r16,0b10010111 ; PRTIM2 | PRTIM0 | PRTIM1
        sts     PRR,r16


message:
Best practices for really long distance sensor deployments

I'm noob to Arduino and electronics, but here is a problem from life which I need to solve for myself:

We grow strawberries and early spring freezes can take most of the flowers from the plants. One way to protect this is to have some kind of heating in solar houses, but if you grow outside, your best option is to watering the flowers on the crops when the freezing comes.

I want to deploy at least 3-4 temperature sensors, which are placed at every parts of the land, which will send the data for an Arduino which will turn on the pump with a relay (for this part I also want to use a pre-built relay solution with socket plugs already built, I don't want to mess around with high electricity myself).

For a cable solution (like catKIT system) I need at least 100m cable for the farest part of the land, which can be managable, but later on, scaling the land lots of cables everywhere can be a problem.

So the best solution would be if every temperature sensor is a standalone station, data transmitted by wireless to the main Arduino which is triggering the pump. This way there will be lass cables on the land, less change to cable break by tractor, etc.

Also, with a wireless system, I don't have to deal with signal loss over the cable, just only wireless signal loss. Is it possible to correct this by middle wireless signal transmitter stations? Or even better, all of them connected to each other!?

Like if the farest sensor reading Celsius 0.8, middle sensor reading Celsius 1.2. Middle sensor have a variable to also consider any reading from the farest sensor, which is reading 0.8. If that reading under Celsius 1, than don't bother his own output, send 0.8 to the main Arduino which is triggering the pump.

These station's power input still need to be solved, but maybe solar panels can be an option? However I have a clue that night they will not work, most of them freezing comes at night.

I saw wireless shields for arduino which offering even a km range in ideal conditions. But how degrading when the conditions are not ideal, like a house wall, rain, fog, snow?

Is it possible to feed multiple wireless inputs too one arduino? 3-4-10-20 standalone stations which transmitting temperature reads for the main arduino. If one of them sends lower temperature than +1 Celsius, than the pump will be turned on. Is it possible to solve this?

Thank You for your answers!

body:
There's as many ways of solving your problem as there are of skinning a cat (those poor poor cats - always getting skinned... ;) )

As you have already noted there are two basic solutions: wired or wireless.

Wired does have one major advantage that you haven't really touched on (only mentioned in passing) and that is power. With a wired solution you can provide power over those same wires so you don't need to worry about solar panels, batteries, whatever. But wires can break, yes. So they're not ideal. But then what is?

With wireless you then introduce the major problem of power. Solar panels are one possible way of getting power, though they are expensive, and you need to "over spec" them to charge batteries so you continue to have enough power for the times when is little or no sun.  Complementing them with wind power is also an option to boost the battery charge when its windy. It all adds up to very expensive sensors though.

A compromise might be to consider both options together.  Turn the sensors into small clusters of sensors that are near by with a base station for those sensors that both gathers and stores the power needed for them, and performs the wireless communication. The sensors would then be wired to the base station.  Your wires are then shorter, and your power is more centralised.

But what to then use for the wireless itself? Well, there it's really all down to frequency.  There's two basic gropings here:

* High frequency - 2.4GHz - is great at unobstructed communication. That's the frequency your WiFi works on, and as you probably know it's great if there's no walls in the way. Add walls and the signal drops off considerably.
* Low frequency - 433MHz - Far far better at penetrating walls and things but much less bandwidth.

I have had distances of hundreds of meters using a 2.4GHz nRF24L01+ module with power amplifier and antenna. That's in open air with (pretty much) line of sight. Indoors the range is much much shorter. Put buildings in the way and your hundreds of meters drop down to tens of meters.

So if there are obstructions you're pretty much going to want to use the 433MHz range (there is another frequency, which is different depending on where in the world you are - 868MHz or 915MHz, so we'll ignore that for now).

There's plenty of modules around that run at 433MHz, some better than others. There is, however, a new standard emerging now that is designed specifically for this kind of thing - long range, low bandwidth, just for sensors (as part of the IoT bandwagon) called LoRa (short for **Lo**ng **Ra**nge) which aims at distances of 15km using very small amounts of power (tens of mA) which is ideal for solar powered operation. It also can use the 868/915MHz region as well.

The final option that you touched on without knowing it is that of a *mesh*. This is where all the nodes form a network and each node is capable of relaying data from other nodes to get to their destination. Kind of like how the internet works. There are some mesh libraries available for some radio modules on the Arduino, but I have no idea how good or reliable they are. The best ones would be completely self-healing with auto-discovery - add a node and the whole mesh works out how to route messages to the destination node; remove a node and the mesh works out new routes to pass the data around the hole it's created.

Creating a good mesh stack is not child's play, so you would want to research it properly and find the best modules with the best library support if you wanted to take this route. That's why LoRa is taking off - it's so much simpler to get wide coverage without the need of complex mesh systems.


body:
Personally I wouldn't use an Arduino as a wireless sensor controller, I would use an ESP8226, which comes with WIFI interface built in.  You can program this through the Arduino IDE in the same language, and its compatible with most Arduino sensors.

The ESP8266 also has the advantage that it can create a WIFI network of its own, because it can act as a WIFI client, a WIFI access point or both at the same time.  So if you do have an issue with the range of the signals then you can program your own WIFI repeater, which could also measure the temperature at the same time.   They come in many different shapes and sizes, I think you might be better having an external aerial capability, have a look around and see what you can find.  They cost around $2 so they should break the bank.

As for powering it you could use solar or wind power to charge a battery.  Probably the best sort of battery for this is a Lead Acid battery because they don't object to being trickle charged.  Assuming you sensor station runs at 5V, you want at least a 6V battery.  You charge a 6V battery at 7.2V, so your solar panel(s) should generate at least 7.2V in _average_ sunshine.  You also need to work out how much power you sensor station is going to need, factor in an extra for working in cold weather, etc and then multiply it by the number of hours per day want it to work (24?).  This is the total power you need per day, so the output of you panels must be = (Required Power / Hours of Sun).  At this point you are best looking for a COTs device to charge the batteries and achieve your needs.


message:
Burn bootloader on custom ATmega 2560 board

I have developed and produced a custom board with a ATmega 2560 on it and a FT232RL for USB communication. I want to burn an Arduino bootloader onto the board without using an external Arduino as ISP. I can't seem to figure out how.
When I just click "burn bootloader" from the arduino software it says:

avrdude: stk500_recv(): programmer not responding

What am I doing wrong and how can I correctly burn the bootloader?

body:
To burn a bootloader you *have* to use some external device. That can either be another Arduino or a hardware programmer, like an USBASP or something similar.

You can't just magic the bootloader on there through the USB and a dose of wishful thinking. To use the USB you first have to have the bootloader on there.


message:
RFID RF522 kit for access control

I am trying the RFID RC522 reader kit with an Arduino UNO to built a controlled access system for a door.

Using the code below, I am able to read the UID of my card and light up an LED when the reader detects the card or the badge, however it will light up whatever card is presented to it even if the UID of this card is not entered as a String in my program.

My question is how can I enter hundreds of cards (depending on memory) that will unlock the door and have all the others set as unknown if not in my program.

Thank you very much for your help

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10         //(or SDA) Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    // ===========================================================================
    String read_rfid;
    String ok_rfid_1 = "C5 12 E3 52"; // for the badge
    String ok_rfid_2 = "9A 48 3A D5"; // for the card
    // ==========================================================================
    int led = 3;
    // ===========================================================================
    void setup() {
     Serial.begin(9600); // Initialize serial communications with the PC
     //while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
     SPI.begin(); // Init SPI bus
     mfrc522.PCD_Init(); // Init MFRC522
     mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     Serial.println(F("Scan PICC to see UID, SAK, type, and data bleds..."));
      pinMode(led, OUTPUT);
    }
    // ===========================================================================
     void dump_byte_array(byte *buffer, byte bufferSize) {
      read_rfid="";
      for (byte i = 0; i < bufferSize; i++) {
        read_rfid = read_rfid + String(buffer[i], HEX);
      }
     }
    // ==========================================================================
    void unlock() {
      digitalWrite(led, HIGH);
      delay(2000);
      digitalWrite(led, LOW);
    }
    // ======================================================================
    void loop() {
     // Look for new cards
     if (! mfrc522.PICC_IsNewCardPresent())
     return;
     // Select one of the cards
     if (! mfrc522.PICC_ReadCardSerial())
     return;

      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println(read_rfid);

      if (read_rfid == ok_rfid_1 || ok_rfid_2) {
        Serial.println("Open");
        unlock(); // turns LED on
      }

      else {
        Serial.println("Stay Closed");
      }
    }

body:
Your IF statement is the problem. `if (read_rfid == ok_rfid_1 || ok_rfid_2)` always evaluates to `True`. Your condition should be:

    if (read_rfid == ok_rfid_1 || read_rfid == ok_rfid_2)

You also need to remove the spaces in the string literals if you want this condition to have the desired effect.

This approach isn't very good though, since you have to add more comparisons to the IF condition if you want to match more cards. You should use the byte arrays as they are, without converting to Strings; it can actually be a lot simpler to compare as well as memory-safe. Store all your allowed card UIDs in a 2-D array:

    #define ALLOWED 2   // no of allowed cards
    byte read_card[4];   // same purpose as before
    bool found = false;  // to know when a valid card match occurs
    byte cards[ALLOWED][4] = {{0xC5, 0x12, 0xE3, 0x52},
                             {0x9A, 0x48, 0x3A, 0xD5}};

Then you should get rid of `dump_byte_array()` and compare cards like this:

    memcpy(read_card, mfrc522.uid.uidByte, 4); // copy UID into array with shorter name ;)

    for (int i = 0; i < ALLOWED; i++){
      if (memcmp(read_card, cards[i], 4) == 0){

          found = true;
          break;
      }
    }

    if (found){
      Serial.println("Open");
      unlock(); // turns LED on
      found = false;
    }
    else {
      Serial.println("Stay Closed");
    }


message:
How can I get analog-in reading from Digital-PWM-out on the same board?

I have a wire going from `PWM4` to `A0` but I don't dare turn on my `Arduino Mega` in case this is incorrect.

`PWM4` will eventually go to an *analog* device but I want to make sure the read value is what I expect it to be. Am I okay to proceed with my current setup or do I need to throw in a `resistor` / conversion?

body:
You are fine by doing that, but you won't get what you expect.

A PWM signal isn't an analog value. It's a series of pulses, the duration of those pulses is set by the (not accurately called) analogWrite. So sometimes the value is 5V and sometimes it's 0V. You need to get the average value by adding e.g. an RC-filter.

Another option is to add a proper DAC (digital to analog converter) chip to your circuit.


message:
Converting char array to int

I'm trying to use nRF24L01 module to send a messages between 2 arduinos

Transmiter code:

      const char text[] = "Hello World";
      radio.write(&text, sizeof(text));

      delay(1000);

Reciver code:

    char text[32] = {0};
    radio.read(&text, sizeof(text));

    Serial.println(text);

How I can put into char array an int value?
I tried doing it in this way

For example:
      int a = 60;
      const char text[] = String(a);
      radio.write(&text, sizeof(text));

      delay(1000);

body:
Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.

I recommend using [sprintf][1]

    sprintf(char * str, char * format, args)

Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:

    char[x] result;    //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
    int number = 24;
    sprintf(result, "My number is %d", number);
    sendSomewhere(result);   //sends "My number is 24"

  [1]: http://www.cplusplus.com/reference/cstdio/sprintf/


body:
You can not have 'const' prefixed the 'text' variable as it then become 'read-only'.

        char text[32];
        int a = 60;
        sprintf(text, "Number %d", a);
        radio.write(&text, sizeof(text));


body:
The simplest method is to send the integer in binary format (skipping the conversion to text).

    int a = 60;
    radio.write((char*) &a, sizeof(a));

Cheers!


message:
How can you speed up the ADC on an ATtiny85?

I'm reading input from a camera and trying to reach a fast frame rate. Problem is my ATtiny85 has a pretty slow conversion time (65 - 260 µs Conversion Time). Is there any way to make this faster? I heard that you can set-up a prescaler for the `analogRead()` method by doing the following:

    #define FASTADC 1

    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    void setup()
    {
      #if FASTADC
       // set prescale to 16
       sbi(ADCSRA,ADPS2) ;
       cbi(ADCSRA,ADPS1) ;
       cbi(ADCSRA,ADPS0) ;
      #endif

      /*Rest of the code goes here.*/
    }

I can't really make sense of the code and I found it on a less then reliable website so I was wondering if any of the gurus on here could let me know if what I'm attempting is possible and if this is the proper way of achieving my goal.

Also, would this also work for the Arduino Mega? I'm currently using it to test and debug my project since the ATtiny84 doesn't have serial output.

Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

body:
The ADCs in the ATtiny85 and ATmega2560 (the chip powering the Arduino
Mega 2560) are pretty similar, except for the Mega having more inputs.
In particular, the way you set the clock prescaler is the same, namely
the bits ADPS2:0 in the register ADCSRA. You could use the same code to
set the prescaler on both chips, but you probably don't want to unless
your ATtiny is clocked at 16 MHz, like your Mega. I would normally
just _set_ the control register to the value I want, rather than
touching only a few bits, but that is a matter of personal preference.
So, to set the ADC clock of the Mega to 1 MHz, I would

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

    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADPS2);  // clock at F_CPU / 16 = 1 MHz

The same code would do the same thing on an ATtiny clocked at
16 MHz. If the ATtiny runs at 8 MHz, I would instead

    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADPS1)   // clock at
           | _BV(ADPS0);  //     F_CPU / 8 = 1 MHz

If you want to be generic:

    #if F_CPU >= 12000000
    # define ADPS_SETTING _BV(ADPS2)                 // F_CPU / 16
    #else
    # define ADPS_SETTING (_BV(ADPS1) | _BV(ADPS0))  // F_CPU / 8
    #endif

    ADCSRA = _BV(ADEN)      // enable the ADC
           | ADPS_SETTING;  // clock somewhere near 1 MHz

As bigjosh explained in comments, the prescaler setting is a trade-off
between speed and accuracy. I recommend you read the [article on the
Arduino ADC by Nick Gammon][Gammon]. He did some tests at various speeds
which showed that you can get decent results with clock speeds up to
1 MHz, then it becomes pretty bad at 2 MHz and mostly
useless beyond. You may want to run the same tests with your particular
setup.

Except for the very first conversion, which takes longer, an ADC
conversion takes 13 cycles of the ADC clock. If you run that clock
at 1 MHz, that is 13 µs per reading. If you get the readings
with `analogRead()`, you won't get one reading every 13 µs, because
the CPU needs extra time to execute the code you have between successive
calls of `analogRead()`. You can save time by having the CPU and the ADC
work in parallel, maybe along these lines:

    ADCSRA |= ADSC;     // start the first conversion
    for (int i = 0; i < NB_READINGS; i++) {
        loop_until_bit_is_clear(ADCSRA, ADSC);  // wait for the ADC
        uint16_t reading = ADC;     // get the reading
        ADCSRA |= ADSC;             // start the next conversion
        process(reading);           // process the reading we have
    }

This way you process one reading while the ADC is taking the next one.
Or you can set the ADC to “free running mode” (where it takes one
reading after another without ever stopping) and get the readings in an
interrupt service routine. Whichever method works best depends on your
particular application: the amount of works your CPU has to do while
reading the ADC and whether you can afford to do the whole series of
readings with interrupts disabled.

[Gammon]: http://www.gammon.com.au/adc


message:
Good book/reference for AVR coding in pure C/C++?

Can someone recommend a good book/reference for going vanilla (i.e. not using arduino simplified language) on e.g. ATtiny85? I will need to use the equivalents of analogRead() and digitalRead() quite a bit. And is softwareserial the best method for debug output? I have less than 8KB of flash, so any advice on that (and reduction of binary for upload) would also be greatly appreciated.

body:
If you abandon the Arduino paradigm you will be pushed into dealing with setting up all the hardware that makes today's embedded processor so flexible.  This usually takes an experienced embedded programmer days if not weeks to get through on a new processor.  You will also need a dedicated Atmel programmer as you will no longer be using the Arduino boot loader.

Once you get past these obstacles, you can start studying C and C++. The "grand dad" C reference book would be by the "first guys" that did C, Kernighan & Ritchie.  The equivalent C++ book (if you are up to it) would be by Bjarne Stroustrup.

However...

What have you gained by abandoning the Arduino paradigm?

Some would say, not much.

Most of why programming in the Arduino paradigm is easy has to do with Arduino libraries.  They "abstract" the hardware down to a couple simple function calls.  For example, with one function call you can set up the pulse train that can position a servo motor using a familiar term: degrees.

It should also be pointed out that the compiler Arduino uses is a C / C++ compiler.  And that most Arduino libraries are purposely written in C++.

Perhaps writing a C++ Arduino library is a good way to learn C++.  Start by finding the code to libraries that you already use.  Then reviewing how the C++ code is put together.  Finally write you own C++ Arduino library.


body:
Sorry, I don't have any book recommendation apart from the AVR Datasheet.

You could try to use AVR-LIBC as a abstraction layer instead of playing directly with individual registers: [http://www.nongnu.org/avr-libc/][1].

That might help you saving some Ks on your code which the Arduino layer might be adding. Just make sure you have a proper IDE to assist you with code-completion and navigation.

Also Atmel has a good link how to optimize your C code: [http://www.atmel.com/images/doc8453.pdf][2], which I had a look when doing some bootloader coding.

Finally, you could explore the Arduino libraries, and see the overhead added to each function, like "analogRead()" from your example. Most of the Arduino funcions will be a layer on top of the AVR-GCC, so it'll be a good learning exercise - again, get a proper IDE that helps with auto-completion and navigation.

Cheers

  [1]: http://www.nongnu.org/avr-libc/
  [2]: http://www.atmel.com/images/doc8453.pdf


body:
The Arduino implements a subset of c++. I am not sure what you expect to achieve by not using it.

If you are really after optimum code, there is no obligation to use any inbuilt function and you can code your own.

Most conventional compilers use a standard runtime library. The reason Arduino does not is because of the limited memory. It is necessary to omit many standard functions to save space.

By not using a library only functionality you need is actually linked in.


body:
First, let's make this clear: The Arduino environment does not provide a
“simplified language”: it provides a simple hardware abstraction layer
through its core library. The language is plain C++.

Like Talk2, I don't have good book recommendations. The basics of
low-level programming are covered in the Arduino tutorial on [port
manipulation][]. Past this you will have to dig into the datasheet of
your MCU. Look also at the doc of the [avr-libc][] and the tutorials in
[Nick Gammon's microprocessors pages][Gammon].

I would suggest you try to develop your program like this:

1. Do the initial prototype of your idea on an Arduino Uno (or similar)
   using the Arduino libraries. It just makes things easier, and you are
   more likely to get a working prototype pretty fast.
2. Once the initial idea works, optimize it for the limited resources of
   the ATtiny85. This may involve replacing some call to the Arduino
   libs with avr-libc and/or direct port access.
3. You may then want to remove all references to Arduino core, but you
   don't have to: there are some ATtiny cores available that you can use
   if you want.
4. If it now fits in less than 8 K, port to the ATtiny.

The thing I love about the Arduino environment is that you can very
easily mix and match abstraction levels: you can have, in the same
program, calls to Arduino core, to avr-libc, direct port access, and
even inline assembly if want to. You don't even need to stick to the
`setup()` and `loop()` method: you can write your own `main()` if you
prefer, just remember to call `init()` to initialize the Arduino core if
you are going to use it. Oh, and you don't have to use the Arduino IDE
either if you don't like it (I don't).

As for the optimization tips, I would recommend :

* Use direct port access instead of `digitalRead()`, because that
  function is pretty big and slow.
* `analogRead()` may not be that bad, size wise, but it has a serious
  shortcoming: it's a blocking function which spends 104 µs in a
  spin loop, just waiting for the ADC result. If your CPU has better
  things to do, you may want to implement a non-blocking read instead.
* For debugging output, the most efficient option is likely to be the
  USI port. You will have to search for a driver or implement your own
  based on the Atmel application note [AVR307: Half Duplex UART Using
  the USI Module][uart-usi]. Alternatively, you could use something like
  [AltSoftSerial][]. Do not use SoftwareSerial: it blocks interrupts for
  insanely long amounts of time.
* Use the command `avr-nm --size-sort -Crtd my_program.elf` to get a
  listing of the functions of your program sorted by flash usage. This
  will help you choose good targets for size optimization.

[port manipulation]: https://www.arduino.cc/en/Reference/PortManipulation
[avr-libc]: http://www.nongnu.org/avr-libc/user-manual/index.html
[Gammon]: http://www.gammon.com.au/forum/?bbtopic_id=123
[uart-usi]: http://www.atmel.com/Images/doc4300.pdf
[AltSoftSerial]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


body:
I can recommend the book "**Make: AVR Programming**", which uses **avr-gcc** directly. The Arduino IDE *is* mentioned at one point, but just in order to "place" it, and to explain how to use its libraries in your own code. You can study all the code used in the book [right here (github link)][1].

(late answer, I know, I was searching for other books that don't use the Arduino IDE and stumbled upon this question)

  [1]: https://github.com/hexagon5un/AVR-Programming


message:
How to control a DC Motor with Hall Encoder using Arduino and Motor Driver?

I'm using a DC motor with Hall Encoder. I bought it from [DX][1].

I have made all the connections to motor driver and arduino and I suppose all are correct. I've connected m1 and m2 pins of motor to that of motor driver, encoder A phase and B phase to arduino pins 3 and 11, and GND of motor to GND of Arduino and 3.3V pin of motor to 3.3V pin of Arduino. Also motor driver is also connected to arduino.

The problem is that I'm unable to run the motor but I can count the rotations made by the motor. Please help me with the working code. Thanks.

  [1]: http://www.dx.com/p/12v-350rpm-dc-gear-motor-with-hall-encoder-silver-431965#.V334kbh96Uk

body:
What are the "m1" and "m2" pins you mention?

On the diagram I see on that link, the pins "1-M1 motor -" and "6-M1 motor +" should be connected to the motor driver. The other four pins should go to the Arduino only.

You can probably test the motor by disconnecting it and connecting pins 1 and 6 to a 9-12V battery or similar, to see if it turns.

By the way I guess the two Encoder Phase connections would be set up on the Arduino using [PinMode][1] setting "INPUT_PULLUP". But as you can already read the positions, that part may not matter.

  [1]: https://www.arduino.cc/en/Reference/PinMode


message:
What speaker can you drive with output pin?

I'm wondering how to drive a speaker using an arduino output pin.  I am using a pwm playback method with a sound data file.  If you wire a speaker across an output pin and ground then how do you calculate what speaker power and impedence you can use without damaging the arduino?  Is there a reference making these calculations?

Thanks

body: Only very small ones with 20-30mA.  Earbud-size and slightly larger. You can buy a 2x3W amplifier which runs on 5V, and gives you two audio channels - but it works fine for mono. It can drive my 4 ohm desktop speaker, and is probably too powerful for that. Read about signal voltage and resistance for speakers. IIRC small audio outputs (like from an mp3 player) switch from -2.5V to 2.5V, giving an RMS of 5V. Or perhaps that was just my player. The only way to know this is to measure it - I played a sine wave and got a circa value. Offhand I can't say how to drive negative voltages from an arduino without extra circuitry. Hope it helps (and show us your code :)


body:
The Arduino can supply 5V at max 20mA so 5/0.02 ⇒ 250Ω (if you can find such a beast).

NOTE you should use a capacitor to prevent DC flow if using a conventional speaker.

In general the larger the speaker the better. Tiny speakers are inefficient transducers. Hi-Fi speakers are not a good choice, as they are often inefficient, trading efficiency for linearity.

An alternative, if you are a scrounger, is to scavenge a transformer from an old transistor radio - this should give the best match.


message:
not getting proper bitstream output in serial monitor using digitalRead

I am producing a  data stream and feeding to a gpio pin. THe data is sampled at 2kbps. i want to dump this data into a file after a certain length of reading . how should i proceed with this ?

body:
Without seeing your code it's impossible to tell just what is happening, but I would guess you are reading and printing the *level* of the wave, not the *transitions from one level to another*.

For instance:

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

As you can see, just reading regularly and printing it (which itself is quite slow) results in 11001101 rather than the 10101 that you want. That's because the speed of your reading/printing and the frequency of your wave are completely separate things and out of step with each other. There's nothing to tie one to the other.

Instead you need to look for the transitions from LOW to HIGH and from HIGH to LOW. Only when the input *changes* should you look to see what the new level is and print that.

[![enter image description here][2]][2]

As you can see the 1 and 0 are *just after* the change in level, since it's impossible to do anything *during* a change, only *once the change has happened*.

You might code that as something like:

    void setup() {
        Serial.begin(115200);
        pinMode(3, INPUT);
    }

    void loop() {
        static byte oldValue = LOW;     // Place to store the previous level
        byte newValue = digitalRead(3); // Read the current level
        if (newValue != oldValue) {     // The input has changed
            oldValue = newValue;        // Save the current level
            Serial.print(newValue);     // Print it.
        }
    }

  [1]: https://i.stack.imgur.com/WCm6a.png
  [2]: https://i.stack.imgur.com/rQeYx.png


message:
Informations lost in a string

At first, I sorry if I make some English faults but I'm French.

So, I'm making a connection between a client and an Arduino Uno. I receive all data that I need but when I send a response to my client some characteres are lost.
I receive this format : GET /?b=7&p=100$ (for exemple)
And my Arduino sends this to my client : GET /?b=7&p=1d

This is the function where I get all data from my client :

    void read_data(int *state, int *progress_program){
      // Check if there is a client
      EthernetClient client = server.available();
      if (client) {
        url = "";
        index = 0;
        Serial.println("\nnew client");
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.println(c);
           if(c != '$') { // if end of char
              url[index] = c;
              index++;
            } else {
              url[index] = '\0';
              int i;
             Serial.print("\n");
              for(i=0;i<index;i++)
                Serial.print(url[i]);
              if(interpret(state, progress_program)){
                action();
                delay(100);
              }
              answer(client);
              break;
            }
          }
        }
        url[0] = '\0';
        // give the web browser time to receive the data
        client.stop();
        delay(100);
        Serial.println("\nclient disconnected");
      }
    }

And the response sent to the client :

    void answer(EthernetClient client){
      Serial.print("\nResponse"); // debug
      delay(100);
      client.print(url);
      Serial.print("Response Sent");
      delay(100);
    }

With client.write(url) there is the same problem.

Have you got a solution?
thanks

body:
So, the solution was very simple,
My pointer "url" received a constant null string with url=""; at the beginning. To initialize a string as null we need to make this :

     url[0] = '\0';

thanks


message:
PCINT with my arduino UNO says redefinition of 'void __vector_4()'

So i'm working on a quadcopter controlled by the arduino UNO, and focusing in pin interrupts for the reciever. This is the code for the reciever.

    unsigned long timer[4];
    byte last_channel[4];
    volatile int input[4];

    void rx_initialize() {
      PCICR |= (1 << PCIE0);
      PCMSK0 |= (1 << PCINT0);
      PCMSK0 |= (1 << PCINT1);
      PCMSK0 |= (1 << PCINT2);
      PCMSK0 |= (1 << PCINT3);
      Serial.begin(9600);
    }

    ISR(PCINT1_vect) {

      timer[0] = micros();//Lire la valeur PWM en microsecondes

      //////////////////////////CHANNEL1/////////////////////////////
      if(last_channel[0] == 0 && PINB & B00000001){//vaut digitalRead(HIGH); mais en plus rapide
        last_channel[0] = 1;//le state est HIGH
        timer[1] = timer[0];//Lire combien de temps HIGH
      }
      else if(last_channel[0] == 1 && !(PINB & B00000001)){
        last_channel[0] = 0;//le state est HIGH
        input[0] = timer[0] - timer[1];
      }

      //////////////////////////CHANNEL2/////////////////////////////
      if(last_channel[1] == 0 && PINB & B00000010){//Rising
        last_channel[1] = 1;//le state est HIGH
        timer[2] = timer[0];//Lire combien de temps HIGH
      }
      else if(last_channel[1] == 1 && !(PINB & B00000010)){//Falling
        last_channel[1] = 0;//le state est HIGH
        input[1] = timer[0] - timer[2];
      }

      //////////////////////////CHANNEL3/////////////////////////////
      if(last_channel[2] == 0 && PINB & B00000100){//Rising
        last_channel[2] = 1;//le state est HIGH
        timer[3] = timer[0];
      }
      else if(last_channel[2] == 1 && !(PINB & B00000100)){//Falling
        last_channel[2] = 0;//le state est HIGH
        input[2] = timer[0] - timer[3];
      }

      //////////////////////////CHANNEL4/////////////////////////////
      if(last_channel[3] == 0 && PINB & B00001000){//Rising
        last_channel[3] = 1;//le state est HIGH
        timer[4] = timer[0];
      }
      else if(last_channel[3] == 1 && !(PINB & B00001000)){//Falling
        last_channel[3] = 0;//le state est HIGH
        input[3] = timer[0] - timer[4];
      }
    }

I'm using various files for every other part of the quadcopter such as PID controlling and IMU Reading.

But avrdude tells me that I did a redefinition of 'void __vector_4()'.
Itried to look into PinChangeInt.h in the Arduino library folder but still no solution to the problem.

Thank you for your help!

body:
You should use the ISR(PCINT0_vect) instead of the ISR(PCINT1_vect).

Or if you want to use PCINT1:

    PCICR |= (1 << PCIE1);
    PCMSK1 |= (1 << PCINT8);
    PCMSK1 |= (1 << PCINT9);
    PCMSK1 |= (1 << PCINT10);
    PCMSK1 |= (1 << PCINT11);

  But them you have to change every PINB to PINC too as it uses a different PORT


body:
`__vector_4()` is just another name for `PCINT1_vect()`. The error
message simply means that you have defined that function twice. One
definition is explicit in the code you are showing to us. I cannot see
the other definition: obviously you are not showing **all** of your
code. Most likely that other definition lies inside some library you are
using in your program.

Since you cannot define an ISR twice, you will have to use another PCINT
which is not already in use. Or you could modify the library and try to
merge it's `PCINT1_vect()` with yours.

BTW, the error message does not come from avrdude, it comes from the
linker.


message:
Reading Multiple switch inputs

I am trying to setup 20 input switches that can be pressed with hand. I am trying to get the output based on the pattern in which the input switches are pressed with the hand. Based on the pressure and the area of the hand pressing the input switches, there can be multiple switches that can be pressed to display the output pattern at the same time. How can I use Arduino Uno inputs to support these multiple pin reads at the same time?

body:
You could use a MCP23017 or similar.  Its an IC that provides 16 IO ports via I2C, I think you can have 4 of them so that should be enough for both hands.

Or you could use resistors.  All the buttons are connected to a single analogue port.  The resistors are chosen so that when you press any combination of buttons you will get a unique reading at the port. So if you press button one and get a reading of 100, press 2 and get 150, press 3 and get 200, etc.  So buttons 1+2 give you 250, 2+3 gives you 350 and 1+2+3 gives you 450.  The problem with this is the maths get out of hand very quickly and the IC is < $1.


body:
I'd second the use of the MCP23017, have used this chip in several projects with good results, you can connect 8 of them together which gives 128 I/O pins.
Off the SDA/SCL pins UNO R3
Link [Adafruit MCP23017][1]

  [1]: https://www.adafruit.com/products/732

Also on Ebay from other suppliers.