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

  [1]: https://i.stack.imgur.com/xNSRT.png
I have a circuit with preferably long wires that get data from thermistors. The Arduino sends this data (formatted in JSON) to a web server where it can be collected by another program.
Some of these values appear correct, while others do not.

    [
    {
        "dht11": {
            "temperature": 73.4,
            "humidity": 41,
            "heat-index": 77.15
        },
        "thermistors": {
            "therm1": {
                "temp": 71.21,
                "resistance": 12727.27
            },
            "therm2": {
                "temp": 76.22,
                "resistance": 12045.51
            },
            "therm3": {
                "temp": nan,
                "resistance": -19393.41
            }
        }
    }
    ]
code:

    #define THERMISTORPIN A0
    #define THERMISTORNOMINAL 10000
    #define TEMPERATURENOMINAL 25
    #define NUMSAMPLES 25
    #define BCOEFFICIENT 4050
    #define SERIESRESISTOR 10000
    #define THERMISTORPIN2 A5
    #define THERMISTORPIN3 A3
    #define DHTPIN 2
    #define PHOTORESISTOR 3
    #define DHTTYPE DHT11
    int samples[NUMSAMPLES];
    int samples_two[NUMSAMPLES];
    int samples_three[NUMSAMPLES];
    int stuckintime;
    #include <SPI.h>
    #include <Ethernet.h>
    #include "DHT.h"
    byte mac[] = {
      0x00, 0x00, 0x00, 0x00, 0x00, 0xEE
    };
    IPAddress ip(192, 168, 1, 3);
    EthernetServer server(80);
    DHT dht(DHTPIN, DHTTYPE);
    void setup() {
      Serial.begin(9600);
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
      dht.begin();
      analogReference(EXTERNAL);
    }

    void loop() {
      uint8_t i;
              float average;
              float average_two;
              float average_three;
              float stuckintime;
              for (i = 0; i < NUMSAMPLES; i++) {
                samples[i] = analogRead(THERMISTORPIN);
                samples_two[i] = analogRead(THERMISTORPIN2);
                samples_three[i] = analogRead(THERMISTORPIN3);
                delay(10);
              }
              for (i = 0; i < NUMSAMPLES; i++) {
                average += samples[i];
                average_two += samples_two[i];
                average_three += samples_three[i];
              }
              average /= NUMSAMPLES;
              average = 1023 / average - 1;
              average = SERIESRESISTOR / average;
              float tempreading;
              tempreading = average / 10975;
              tempreading = log(tempreading);
              tempreading /= BCOEFFICIENT;
              tempreading += 1.0 / (TEMPERATURENOMINAL + 273.15);
              tempreading = 1.0 / tempreading;
              tempreading -= 273.15;
              tempreading = tempreading * 9 / 5 + 32;
              average_two /= NUMSAMPLES;
              average_two = 1023 / average_two - 1;
              average_two = SERIESRESISTOR / average_two;
              average_two = average_two;
              float tempreadtwo;
              tempreadtwo = average_two / 11811;
              tempreadtwo = log(tempreadtwo);
              tempreadtwo /= BCOEFFICIENT;
              tempreadtwo += 1.0 / (TEMPERATURENOMINAL + 273.15);
              tempreadtwo = 1.0 / tempreadtwo;
              tempreadtwo -= 273.15;
              tempreadtwo = tempreadtwo * 9 / 5 + 32;
              average_three /= NUMSAMPLES;
              average_three = 1023 / average_three - 1;
              average_three = SERIESRESISTOR / average_three;
              float tempreadthree;
              tempreadthree = average_three / THERMISTORNOMINAL;
              tempreadthree = log(tempreadthree);
              tempreadthree /= BCOEFFICIENT;
              tempreadthree += 1.0 / (TEMPERATURENOMINAL + 273.15);
              tempreadthree = 1.0 / tempreadthree;
              tempreadthree -= 273.15;
              tempreadthree = tempreadthree * 9 / 5 + 32;
              float h = dht.readHumidity();
              float t = dht.readTemperature();
              float f = dht.readTemperature(true);
              float hif = dht.computeHeatIndex(f, h);
      EthernetClient client = server.available();
      if (client) {
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            if (c == '\n' && currentLineIsBlank) {
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: application/json");
              client.println("Connection: close");
              client.println("Refresh: 0");
              client.println("");
        client.println("[");
        client.println("   {");
        client.println("    \"dht11\": {");
        client.print("          \"temperature\": ");  client.print(f);   client.println(",");
              client.print("          \"humidity\": ");   client.print(h);   client.println(",");
        client.print("          \"heat-index\": ");  client.print(hif);  client.println("");
        client.println("     },");
        client.println("    \"thermistors\": {");
        client.println("        \"under-bed\": {");
           client.print("             \"temp\": ");    client.print(tempreading);   client.println(",");
        client.print("             \"resistance\": ");  client.print(average);  client.println("");
        client.println("       },");
        client.println("        \"side-bed\": {");
        client.print("             \"temp\": ");    client.print(tempreadtwo);   client.println(",");
           client.print("             \"resistance\": ");  client.print(average_two);  client.println("");
        client.println("       },");
        client.println("        \"top-bed\": {");
        client.print("             \"temp\": ");    client.print(tempreadthree);   client.println(",");
           client.print("             \"resistance\": ");  client.print(average_three);  client.println("");
        client.println("       }");
        client.println("     }");
        client.println("   }");
        client.println("]");
              break;
            }
            if (c == '\n') {
              currentLineIsBlank = true;
            }
            else if (c != '\r') {
              currentLineIsBlank = false;
            }
          }
        }
        delay(1);
        client.stop();
      }
    }

I have no idea what is causing this to happen - pushing RESET doesn't fix it at all, reconnecting wires does not fix it, any help?
(Please tell me what else to include if you need it.)

title: Getting values from multiple thermistors - one value glitches all over the place

Answers: 1

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

Here's a major problem:

    void loop() {

      uint8_t i;
              float average;
              float average_two;
              float average_three;
              float stuckintime;
              for (i = 0; i < NUMSAMPLES; i++) {
                samples[i] = analogRead(THERMISTORPIN);
                samples_two[i] = analogRead(THERMISTORPIN2);
                samples_three[i] = analogRead(THERMISTORPIN3);
                delay(10);
              }
              for (i = 0; i < NUMSAMPLES; i++) {
                average += samples[i];
                average_two += samples_two[i];
                average_three += samples_three[i];
              }

The variables *average*, *average_two*, and *average_three* have **undefined** values. Thus it isn't surprising that when you add something to them, they are still undefined.

Local variables must be initialized (eg. to zero in your case).

Also, you have two variables named *stuckintime* - I would do something about that.


body:
I have a number of temperature sensors connected up to an Arduino - I've split it into 3 sections, with each section having a 2-4 sensors on it (due to distances).   This works, but the code I'm using would seem to me to be very inefficient - particularly with respect of how long it takes to read all the sensors.

I've got 3 code blocks one after each other (which are modified from some code online) which look as below - save, of-course, for the name of the 1wire class.

    // Dallas 1 Wire (Main Area):

     //  ds.reset_search();
     //  delay(250);
      while (ds.search(addr))
      {
        for( i = 0; i < 8; i++) {
          Serial.print(addr[i], HEX);
        }

        if (OneWire::crc8(addr, 7) != addr[7]) {
            Serial.println("CRC is not valid!");
            return;
        }

        ds.reset();
        ds.select(addr);
        ds.write(0x44, 0);        // start conversion, with parasite power on at the end

        delay(1000);     // maybe 750ms is enough, maybe not
        // we might do a ds.depower() here, but the reset will take care of it.

        present = ds.reset();
        ds.select(addr);
        ds.write(0xBE);         // Read Scratchpad

        for ( i = 0; i < 9; i++) {           // we need 9 bytes
          data[i] = ds.read();
        }
        raw = (data[1] << 8) | data[0];
        if (type_s) {
          raw = raw << 3; // 9 bit resolution default
          if (data[7] == 0x10) {
            // "count remain" gives full 12 bit resolution
            raw = (raw & 0xFFF0) + 12 - data[6];
          }
        } else {
          byte cfg = (data[4] & 0x60);
          // at lower res, the low bits are undefined, so let's zero them
          if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
          else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
          else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
          //// default is 12 bit resolution, 750 ms conversion time
        }
        celsius = (float)raw / 16.0;
        Serial.print(":");
        Serial.print(celsius);
        Serial.print(",");
      }

I note that there is a 1000ms delay after each sensor is read, and I'm wondering if I can reduce this to a single 750ms delay for all the sensors.  My initial attempts to do this did not meet with success - but I confess that I can't quite get my head around the ds.reset, ds.select etc - and my initial attempts to do this have all failed.

Is it possible to remove this delay after reading each sensor ?

title: Reducing read time for reading DS18B20 temp sensors

Answers: 3

body:
Doing a search every time is quite inefficient. The search function is for if you don't know the device address - and it takes a while to do. In your case, presumably the addresses will never change. Find the addresses and hard-code them into your code. Or if that isn't practical, store them in EEPROM. And if even that isn't practical find the addresses once in setup.

---

Next, you need a delay while you take the temperature readings. Why not parallel those up? In a loop, tell all the devices to take a reading. Then wait one second. Then read them all (in another loop). That way the one-second delay is shared between all your sensors.

However from [the page Gerben linked](http://milesburton.com/Main_Page?title=Dallas_Temperature_Control_Library):

> And it is NOT possible to run DS1820 sensors on a simple pull-up resistor. During the "Conversion" phase, it needs more power. And there are Application Note discussing this in length.

That suggest that if you are using parasitic power, my suggestion won't work too well (having multiple devices taking readings would make it worse).

---

I found this code on my disk from a couple of years ago. There don't seem to be any delays between reading sensors. There is a delay at the end of the main loop, mainly to stop spamming the serial monitor.

Notice the comment:

> Call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

See if that works for you.

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <Streaming.h>

    // Data wire is plugged into port 10 on the Arduino
    const byte ONE_WIRE_BUS = 10;
    const byte TEMPERATURE_PRECISION = 10;
    // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    // arrays to hold device addresses
    DeviceAddress myThermometer [10];
    int deviceCount;

    void setup(void)
    {

      // start serial port
      Serial.begin (115200);
      Serial << "Dallas Temperature IC Control Library Demo" << endl;

      // Start up the library
      sensors.begin();

      // locate devices on the bus
      Serial << "Locating devices..." << endl;
      deviceCount = sensors.getDeviceCount();

      Serial << "Found " << deviceCount << " devices." << endl;

      // report parasite power requirements
      Serial << "Parasite power is: " << (sensors.isParasitePowerMode() ? "ON" : "OFF") << endl;

      // method 1: by index

      for (int i = 0; i < deviceCount; i++)
      {
        if (sensors.getAddress(myThermometer [i], i))
        {
          Serial << "Device " << i << " Address: ";
          printAddress(myThermometer [i]);
          Serial << endl;
          sensors.setResolution(myThermometer [i], TEMPERATURE_PRECISION);
        }
        else
          Serial << "Unable to find address for Device " << i << endl;
      }  // end of for loop

    }

    // function to print a device address
    void printAddress(DeviceAddress deviceAddress)
    {
      for (uint8_t i = 0; i < 8; i++)
      {
        // zero pad the address if necessary
        if (deviceAddress[i] < 16) Serial.print("0");
        Serial.print(deviceAddress[i], HEX);
      }
    }

    void loop(void)
    {

      // call sensors.requestTemperatures() to issue a global temperature
      // request to all devices on the bus
      sensors.requestTemperatures();

      // now get all temperatures
      for (int i = 0; i < deviceCount; i++)
      {
        float tempC = sensors.getTempC(myThermometer [i]);
        if (tempC > -80)
        {
          Serial << "Device " << i << " Temperature: " << tempC << endl;
        }
        else
          Serial << "Unable to find temperature for Device " << i << endl;
      }  // end of for loop

      delay (1000);
    }

body:
After nearly a year and a number of experiments later, I've learned a little bit more about using these devices:

Issuing the sensors a Skip ROM command followed by Convert T command starts all devices converting temperature at once (pg.11 of the datasheet). Then you need only wait one delay period of {750,375,188,94}ms for a {12,11,10,9}-bit conversion, respectively, before you can start reading back the temperatures.

If the devices are being powered parasitically, the bus will need a strong pullup during the conversion; the 4.7KOhm pullup is not sufficient (pg.5 of the datasheet).

An arduino pin can source 40mA and I've found that a second pin directly bypassing the 4.7K pullup without the suggested transistor, will source enough current for at least 3 sensors (as many as I've tried so far) and I assume the technique could be extended to more pins. The strong pullup must be switched on within 10uSec after the Convert T command and kept on for the duration of the conversion. The 10uSec spec pretty much means you have to do this in the library.

I keep an abbreviated DS18B20 library around in which I assume the sensors on the bus are related, so it sets all of their resolutions at once and starts their conversions at once, and assumes that the bus is parasite-powered, which mine are, so it switches a specified pin as a strong pullup. I give up some flexibility that the full DSTemperature library would allow but it satisfies my temperature measuring requirements (so far) and simplifies my application code by black-boxing the above techniques.

body:
In case the "Temperature Conversion Time (tCONV)" of each resolution is not fast enough ([MAX] 9-bit: 93.75ms; 10-bit: 187.5ms; 11-bit resolution: 375ms; 12-bit: 750ms), you can use more sensors.

For example, to get a half time (for 9-bit): 47ms:
- You can use two sensors at the same measurement point, (they can operate in parallel , as long as the software can operate with each one of them) when reading one, the software starts converting the other.

Each one has its normal conversion time, but when doing the readings in an interleaved way, a shorter reading time can be obtained.

For 8 sensors, a time below 11.75ms can be achieved (for 9-bit).


body:
I am working in my project and I want to see the output of my sensors as (0 or 5).
The maximum read was 770 and the minimum read was 0. So, how can I see the  value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins.
I did the following code, but it didn't work:

<!-- language: c -->

    void setup(){
    Serial.begin(9600);
    }
    void loop()
    {
    if (analogRead(0)<385)
          Serial.print("0");
     else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(1)<385)
          Serial.print("0");
       else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(2)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(3)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(4)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(5)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    delay(1500);
    }

Note: I have 5 light sensors in my circuit.

title: Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins

Answers: 3

body: You can use DigitaRead command instead of analogread. It will give result in only 1 or 0. Hopefully this will help you.

body:
Try this code - it should help you see what is going on more clearly:

    const int threshold = 385;

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

    void loop()
    {
      int reading = analogRead(0);
      Serial.print("Analog 0 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(1);
      Serial.print("Analog 1 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(2);
      Serial.print("Analog 2 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(3);
      Serial.print("Analog 3 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(4);
      Serial.print("Analog 4 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(5);
      Serial.print("Analog 5 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      Serial.println();

      delay(1500);
    }

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

Your code has multiple issues.

    if (analogRead(1)<385)
          Serial.print("0");
       else
          Serial.print("5");
          Serial.print('  ');

Note that `Serial.print('  ');` is not at all the same as `Serial.print("  ");`

---

Also, by the indentation it looks like you should be using braces. Amended code:

    if (analogRead(1)<385)
          Serial.print("0");
       else
          {
          Serial.print("5");
          Serial.print("  ");
          }

Without the braces only the first statement after the *else* is conditionally executed.

If I am wrong about that, you should indent differently, eg.

    if (analogRead(1)<385)
          Serial.print("0");
       else
          Serial.print("5");
    Serial.print("  ");


body:
Can anyone explain why the standard Arduino IDE 1.6 distribution does not include support for the popular CH341G USB/serial drivers?

I am using these USB/serial chips in several teaching projects for CoderDojo and it is somewhat difficult to have each student download the drivers and reboot their PCs for each class. It seems like both Mac and PC users would benefit from having these drivers loaded directly into the standard Arduino IDE.

Is there possibly some security concern? I know that the latest Mac requires that the drivers are digitally signed. In fact for many modern Macs to use the drivers we have to disable the digital signature checks.

Here is the link to [the official drivers][1].

Here is [a good article][2] on how to download the drivers.

BTW, the command to disable the digital signature check on the mac we need to do the following:

In the Mac "Terminal" application enter:

    sudo nvram boot-args="kext-dev-mode=1"

Then we must reboot the mac. Then when we want to re-enable the checks change the 1 to 0:

    sudo nvram boot-args="kext-dev-mode=0"

If we don't do this command, the Arduino App will not show the serial ports. Do to this go to Tools -> Port Menu within the Arduino application.

    /dev/tty.SerialPort
    /dev/cu.SerialPort

I should mention that the CH340G are also used in many "Arduino Nano" clones from China. Perhaps that is why the drivers are not included?

Tags: Driver CH340 Setup Installation

  [1]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
  [2]: http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

title: Why does the standard Arduino IDE not include the CH341G USB Drivers?

Answers: 2

body:
This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.

What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.

Or you could shift to another board that uses the ATMEGA32u4 as this **might** not require anything special. Have a look [here](http://www.aliexpress.com/item/Mini-Leonardo-Pro-Micro-ATmega32U4-5V-16MHz-Module-For-Arduino-Best-Quality/32284746884.html). I don't have tested this board so you will need to check the quality and whether it works with your projects.

body:
> I should mention that the CH340G are also used in many "Arduino Nano" clones from China.

I believe that the Arduino company already has concerns about the number of unofficial clones (many pretending to be genuine) and have lost a considerable amount of revenue to those knock-off products.

I imagine they are not going to make things worse for themselves by including drivers for unofficial boards, so that the job of the clone-makers is even easier.


body:
I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.
So far, so good.
But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, **no** .a)!

My sample code

    #include <Arduino.h>
    #include <SPI.h>

    int main(void) {
        init();
        pinMode(13, OUTPUT);
        for (;;) {
         digitalWrite(13,1);
         SPI.setBitOrder(0);
        }
    }

The pinMode and digitalWrite parts work, but with the SPI method I get an error:

    05:33:26 **** Build of configuration Debug for project ArduinoTestProject ****
    make all
    Building file: ../main.cpp
    Invoking: AVR C++ Compiler
    avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp"
    Finished building: ../main.cpp

    Building target: ArduinoTestProject.elf
    Invoking: AVR C++ Linker
    avr-gcc -s -Os -o"ArduinoTestProject.elf"  ./main.o   -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" >ArduinoTestProject.symbol
    ./main.o: In function `main':
    ../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)'
    collect2: error: ld returned 1 exit status
    avr-nm: 'ArduinoTestProject.elf': No such file
    make: *** [ArduinoTestProject.elf] Error 1

    05:33:26 Build Finished (took 72ms)

Does anyone see the problem?

title: Arduino in Eclipse IDE: How to add SPI library (core library already added)?

Answers: 1

body:
As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)

The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.

In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.

As such there is no SPI.a file created during the compilation process.
In CDT you can have both options (with or  without .a file) but the Arduino IDE way is the easiest, by far.

So lets first assume you want to compile the "Arduino way" aka without SPI.a.
What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path.
That is all there is to it.

If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build

Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.

I would strongly advise to start your arduino eclipse development with [my arduino eclipse plugin][1] because it is simply easier. Later you can evolve to the full freedom of CDT.

If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.

  [1]: http://eclipse.baeyens.it


body:
This questions has been formulated several times with not clear answer, and I wonder if there is one.

it is well stablished from several sources that measuring the voltage of a battery alone is not good indicator of the State of Charge (SOC) of the battery because voltage does not decline proportional to the soc.

Another solution (http://fritzing.org/projects/battery-charge-level/) suggest measuring the voltage (with analogread) between two resistors connected to the gnd and vcc of the circuit (I presume this constantly draw power) and then choose what is the critical voltage of the circuit.

However, my question is how to measure the SOC of a battery using units of 0 to 100% in arduino?

title: How to measure the state of charge of a battery in arduino

Answers: 1

body:
To do it correctly, you need a coulomb counter. Something like [this][1].

Even that is not fully sufficient, as the charge that can be obtained from a battery depends on various factors, such as temperature and ageing.

More recent batteries have somewhat flat discharge curve, when it comes to voltage, till they run flat, then the voltage drops significantly.
Which means that you would need a very accurate voltage meter.

However the starting point is that you must be able to count how much charge is going in and out.

  [1]: http://www.maximintegrated.com/en/products/power/battery-management/DS2740.html


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

I am working in my project and i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

I read in some article that using delay instruction is not as good as using timers'Interruptions so, I tried this code put it didn't work properly :

    void setup(){

    cli();

      TCCR2A = 0;
      TCCR2B = 0;
      TCNT2  = 0;
      OCR2A = 99;
      TCCR2A |= (1 << WGM21);
      TCCR2B |= (1 << CS21);
      TIMSK2 |= (1 << OCIE2A);
    sei();

    Serial.begin(9600);
    }
    void loop()
    {
    Serial.print(digitalRead(1));
    Serial.print(' ');
    Serial.print(digitalRead(2));
    Serial.print(' ');
    Serial.print(digitalRead(3));
    Serial.print(' ');
    Serial.print(digitalRead(4));
    Serial.print(' ');
    Serial.print(digitalRead(5));
    Serial.println(' ');

    }

title: Timer 2 interrupt with ATmega328p and make measurement in ISR

Answers: 1

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

Well let's start from the start ...

---

## Analog readings

> to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

    Serial.print(digitalRead(1));

That is not reading **analog** pin A1, it is reading **digital** pin 1. If you want to read A1 you need:

    Serial.print(analogRead(1));

---

## Check the time

By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.

Example:

    void setup()
    {
      Serial.begin(115200);
    }  // end of setup

    unsigned long lastReading;
    const unsigned long INTERVAL = 100;  // ms

    void loop()
    {

      // is time up?
      if (millis () - lastReading >= INTERVAL)
        {
        lastReading = millis ();  // when we took this reading
        Serial.print(analogRead(1));
        Serial.print(" ");
        Serial.print(analogRead(2));
        Serial.print(" ");
        Serial.print(analogRead(3));
        Serial.print(" ");
        Serial.print(analogRead(4));
        Serial.print(" ");
        Serial.print(analogRead(5));
        Serial.println();
        }  // end of if time up

      // do other things here

    }  // end of loop

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

---

## Using timers

If you really want to use timers (and I don't see what they achieve here) I have a [page about timers](http://www.gammon.com.au/timers) that describes using them, and interrupts, in some depth.

The very least you would need is a timer 2 "compare A" interrupt like this:

    ISR (TIMER2_COMPA_vect)
      {
      // Timer 2 has reached its comparison value
      }


body:
I have an Arduino Micro and I want to connect an LCD and Bluetooth module to it. The problem I face is that there are not enough power pins for them both.

I understand that I probably need some external power supply for them, but I have no idea how to do this properly.

title: Connect multiple modules to arduino micro

Answers: 1

body:
You can design/build/deploy a power supply that provides to each board (arduino included) the voltage it needs (but it's advisable to have modules working at the same voltage level) and that should be sufficient.
As long as you have a shared Vcc-to-GND reference, it's enough.

To verify that the power supply you choose is ok, do the following:

  - check that the modules are compatible with its voltage (ex: all at 5V)
  - check that the combined power consumption of each module (you get that from the datasheet) is lower than the total power output of the power supply.

Additional checks:

  - check that the maximum voltage ripple provided by the power supply is lower than what the modules can tolerate
  - check that the peak current the power supply can provide is larger than the combined peak current of all the other devices.


body:
Why would someone buy a [1sheeld](http://1sheeld.com/)?

Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?

title: HC-06 module versus 1sheeld

Answers: 2

body:
Why would you buy a car when you can cobble something together from some old pram wheels, a lawnmower engine, some old scaffolding, gaffer tape and chewing gum?

Because buying a car is considerably easier and more reliable.  Plus your "friends" don't laugh at you when they see you trying to drive it to work.

Yes, you could cobble something together that might work using random components and other bits of software, but the work involved would be considerably more than plugging in a shield and downloading an app that is guaranteed to work perfectly with that shield.

body:
Giving an equally biased answer as @Majenko, from the other side:

Because they're lazy, they don't know anything about electronics, and they don't want to. And they have more money than they know what to do with.

I am horrified at people shelling out for an "Arduino Temperature Sensor", "Arduino Shift Register", or "Arduino LED", each of which is a generic component soldered on to a board, with pins, at a 1000% markup

I also question the claim that "cobbled together" items are more reliable, or are less likely to have people laugh at you - if you want it to look nice, put it in a nice box (this applies both to "pre-made" items, and to cobbled together).

You will also learn a lot more from making it yourself; you will learn how things work, and you have a better idea and have the opportunity to fix when things go wrong. Your projects will also be a lot smaller.

If you want something that "just works", go buy an ipad. Then, when it doesn't work, throw it in the rubbish and buy a new one. And if you want it to do something it doesn't do, tough luck.


body:
I am struggling to choose servo motor for my project. There are two servos on ebay. Th First one is named Only "Towerpro micro 9g servo" and the second one that is cheaper is named as a "Towerpro 9g Digital servo".
The Links are:

Servo1: http://www.ebay.in/itm/TowerPro-SG90-9g-Mini-Servo-9-gram-Servo-RC-Robotics-/201386256243?hash=item2ee38e6773

Servo2: http://www.ebay.in/itm/251928442829?aff_source=Sok-Goog

My Problem is that **I am confused with the name "Digital Servo"**. Its cheaper but I a afraid that will it work as normal.
Please help me.

Are both the **same** product, but with a different name?

title: Help choosing a servo motor

Answers: 1

body:
Servos are digital by definition.  All you have there is two sellers that are selling the same product, but they are describing them slightly differently.  They are both SG90 servos. They are both digital (they require a digital PWM signal to control them, hence they are digital).

However, here's a little hint: Add the postage costs on to the cost of the servo - you'll see there's not that much difference in price - only 3 rupees between them.  That's about ¢5 or 3p.


body: Since it is not right to use millis() in an ISR to calculate duration of the input, Is it correct to use pulseIn()?

title: Is it correct to use pulseIn() in ISRs?

Answers: 2

body:
You shouldn't really use anything much in interrupts.  Using anything that runs for a period of time is usually bad since no other interrupts can happen at the same time.

It is more normal to use the interrupt to set a flag that is then checked within your main loop to determine what should be done.

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

It is quite OK to use `millis()` or `micros()` inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is `unsigned long` and `volatile`. Eg.

    volatile unsigned long whenItHappened;
    volatile bool eventHappened;

    void myISR ()
      {
      whenItHappened = millis ();
      eventHappened = true;
      }

Now in your main loop you can test the `eventHappened` flag, so you will know if this event has happened, and `whenItHappened` is when.

It is **not** a good idea to use `pulseIn()` because that can wait quite a long time for a pulse. The default timeout for `pulseIn` is 1 second, which is far too long to wait inside an ISR.

If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.

---

## Example

Example code which times how long a ball passes a sensor:

    const byte LED = 12;
    const byte photoTransistor = 2;

    unsigned long startTime;
    volatile unsigned long elapsedTime;
    volatile boolean done;

    void ballPasses ()
    {
      // if low, ball is in front of light
      if (digitalRead (photoTransistor) == LOW)
        {
        startTime = micros ();
        }
      else
        {
        elapsedTime = micros () - startTime;
        done = true;
        }

      digitalWrite (LED, !digitalRead (LED));
    }

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ("Timer sketch started.");
      pinMode (LED, OUTPUT);
      attachInterrupt (0, ballPasses, CHANGE);
    }

    void loop ()
      {
      if (!done)
        return;

      Serial.print ("Time taken = ");
      Serial.print (elapsedTime);
      Serial.println (" uS");
      done = false;
      }

That code used `micros()` for a more accurate timing.

---

## Reference

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


body:
I want to see the voltage data using `void volt();`, when I go to the "Item2SubItem3" within `void menuChanged`. Now I can only see the data *at that time*: how can I refresh the value every second?

    void setup()
    {
     // setup()...
    }

    void loop()
    {
     //loop()...
    }

    // DC Voltometer
    float vPow = 4.7;
    float r1 = 100000;
    float r2 = 10000;

    void volt()
    {
     lcd.clear();
     float v = (analogRead(0) * vPow) / 1024.0;
     float v2 = v / (r2 / (r1 + r2));
     lcd.setCursor(0, 0);
     lcd.print("DC VOLTOMETER");
     lcd.setCursor(0, 1);
     lcd.print(v2);
     delay(1000);
    }

    void menuChanged(MenuChangeEvent changed)
    {
     MenuItem newMenuItem = changed.to; // get the destination menu
     lcd.setCursor(0, 1);            // set start position for lcd
             // printing to the second row

     if (newMenuItem.getName() == menu.getRoot())
     {
      lcd.print("Main Menu       ");
     }
     else if (newMenuItem.getName() == "Item1")
     {
      lcd.print("Item1           ");
     }
     else if (newMenuItem.getName() == "Item1SubItem1")
     {
      lcd.print("Item1SubItem1");
     }
     else if (newMenuItem.getName() == "Item1SubItem2")
     {
      lcd.print("Item1SubItem2   ");
     }
     else if (newMenuItem.getName() == "Item2")
     {
      lcd.print("Item2           ");
     }
     else if (newMenuItem.getName() == "Item2SubItem1")
     {
      lcd.print("Item2SubItem1   ");
     }
     else if (newMenuItem.getName() == "Item2SubItem2")
     {
      lcd.print("Item2SubItem2   ");
     }
     else if (newMenuItem.getName() == "Item2SubItem3")
     {
      lcd.print("Item2SubItem3   ");
      delay(2000);
      volt();
     }
     else if (newMenuItem.getName() == "Item3")
     {
      lcd.print("Item3           ");
     }
     else if (newMenuItem.getName() == "Item4")
     {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Item4           ");
     }
    }

title: Help with LCD's menu and seeing values continuously

Answers: 1

body:
As Gerben implied in a comment, `menuChangeEvent` is called only when the menu selection changes.  Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3.  The code shown below illustrates how to modify your `loop()` so that it checks the menu selection once per second.  Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading.  Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.

    void setup() {
    }  // setup()...

    // DC voltmeter reading
    void volt () {
      const float vPow = 4.7, r1 = 100000, r2 = 10000;
      lcd.clear();
      float v = (analogRead(0) * vPow) / 1024.0;
      float v2 = v / (r2 / (r1 + r2));
      lcd.setCursor (0,0);
      lcd.print("DC Voltmeter");
      lcd.setCursor (0,1);
      lcd.print (v2);
      // Don't delay(1000) since loop() takes care of delay.
    }

    long int second = 0;
    uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
    int passnumber = 0;
    void menuChanged(MenuChangeEvent changed) {
      MenuItem menuitem = changed.to; //get the destination menu
      String itemname = menuitem.getName();
      lcd.clear();       // Make printing spaces at line ends unnecessary
      lcd.setCursor(0,1);       //set lcd printing position = second row
      if(newMenuItem.getName() == menu.getRoot()){
        lcd.print("Main Menu");
        itemcode = 0;
      } else {
        lcd.print(itemname);
        itemcode = 10*(itemname[4] & 7);
        if (itemname.length() > 5)
          itemcode += itemname[itemname.length()-1] & 7;
      }
      passnumber = 0; // Actions can test passnumber if they like
      second = 0; // Cause actions to take place now
    }

    void loop() {
      long int now = millis()/1000; // Get elapsed-seconds
      if (now == second) return; // Only do stuff once per second
      // Update to current second and do chosen menu item
      second = now;
      switch (itemcode) {
      case  0: break;
      case 10: break;
      case 11: break; // Fill in with code for different cases
      case 12: break;
      case 20: break;
      case 21: break;
      case 22: break;
      case 23:   // Item 2, subitem 3, read voltmeter
        volt();
        break;
      case 30: break;
      case 40: break;
      }
      // You can test passnumber to control for cases that only go once
      ++passnumber;
    } // end of loop()

*Edit:* I moved the declaration of `second` and added `second = 0` within `menuChanged()` to decrease latency between a menu item being selected and its action taking place.  Without `second` being zeroed in `menuChanged()`, up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.


body:
I am A Newbie to Arduino

I have a Windows 7 PC. Last Time I bought an Arduino Uno Clone but after working for a day, it stopped detecting on the port. So I bought a new Clone Of different brand. Now I Want in which sequence should I install its drivers, Coonect it, Unzip Arduino IDE...Reboot??

I dont want a problem this time. Another question is Should I first connect the clone and then Install its drivers Or first install drivers and then plug the board? When Is the reboot required?

Product Link : https://m.ebay.in/itm?itemId=121708881208

Please Explain...
Thanks In Advance

title: Help Connecting Arduino Uno To Computer

Answers: 3

body:
I would like to start by pointing out that you are using a clone. The arduino IDE by default does support clones. Just install your port drivers that's far enough.

The reason your board got spoilt the last time definitely was not cause you did not install the drivers in the right order. It could be due to many reasons, few listed below:

1. Poor PCB quality
2. Humidity
3. Cheap USB to UART converter.
4. Short circuit in your connection

So what I recommend is the either the use of genuine arduino boards if you can afford.

**Note:** Most likely its only the USB to UART (CH340G) that has been destroyed, you could buy a hot air station and replace the IC, it is a much cheaper solution.

  [1]: http://arduino.stackexchange.com/questions/14264/why-does-the-standard-arduino-ide-not-include-the-ch341g-usb-drivers/

body: I have shorted my bords a few time and they always came back to "life" after a minute. Maybe you should be more concern about the voltage you supply to the board. Even if it can take up to 12 volt I never use more then 9 volt on the board. And if you run motors on them its always good to supply them with an external power source and use something like a H bridge to power your devices. I made mistakes and my board are still in mint conditions.

body:
I just checked the link and the item is not available anymore. That way it is impossible to say which driver you should install.

I agree with the answers and comments so far, get the real board. I've heard of people who fried their USB ports because of Arduino clones and their terrible/absent circuit protection.

If you can't afford the original board, what will you do if it damages your computer?


body:
I have an 2 analog signal, and I want to calculate the difference between 2 signals (A0 and A1), then integrate an analog, but it doesn't work (I just started studying Arduino).

Please could you show me how to deal with this problem?

Thanks a lot

    float analogInPin = A0;
    float analogInPin1 = A1;
    float analogOutPin = DAC1;
    float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

    void setup() {
      Serial.begin(9600); // use the serial port
    }

    void loop() {
      FeqIn1 = analogRead(analogInPin);
      FeqIn2 = analogRead(analogInPin1);
      FeqIn3 = FeqIn1 - FeqIn2
      // integration
      area(1) = 0;
      y(1) = 0;
      for (n = 1; n = t; t++) {
        Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));
        Recarea(n+1) = t(2)*(FeqIn3(n));
        area(n+1) = (Triarea(n+1) + Recarea(n+1)) + area(n);
      }
    }

The error message is:

    Arduino: 1.6.5 (Windows 8.1), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    _02.ino:3: error: 'DAC1' was not declared in this scope
    _02.ino.ino: In function 'void loop()':
    _02.ino:20: error: expected ';' before 'area'
    _02.ino:21: error: 'y' cannot be used as a function
    _02.ino:24: error: 'Triarea' cannot be used as a function
    _02.ino:24: error: 't' cannot be used as a function
    _02.ino:24: error: 'FeqIn3' cannot be used as a function
    _02.ino:24: error: 'FeqIn3' cannot be used as a function
    _02.ino:25: error: 'Recarea' cannot be used as a function
    _02.ino:25: error: 't' cannot be used as a function
    _02.ino:25: error: 'FeqIn3' cannot be used as a function
    _02.ino:26: error: 'area' cannot be used as a function
    _02.ino:26: error: 'Triarea' cannot be used as a function
    _02.ino:26: error: 'Recarea' cannot be used as a function
    _02.ino:26: error: 'area' cannot be used as a function
    'DAC1' was not declared in this scope

title: Integrating an analog signal using Arduino Due

Answers: 3

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

    float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

    ...

          Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

I honestly don't know what you are doing here.

Triarea is a float, right? A single variable of type *float*.

What is this?

          Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

`Triarea(n+1)` looks like you are calling a function called Triarea with the argument n+1.

That doesn't make any sense because it isn't a function.

---

Maybe you mean to treat it as an array?

      Triarea[n+1] = (0.5*t[2])*(FeqIn3[n+1] - FeqIn3[n]);

But you have not declared those variables as arrays.

It is pure guesswork what is going on in your mind.

However your syntax certainly explains the error messages, for example:

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

    _02.ino:24: error: 'Triarea' cannot be used as a function

---

If I may suggest, read a tutorial on basic C++ programming.

body:
I think your main problem here is a fundamental lack of understanding about C++.  There's numerous basic errors in your code.  Let's take a look at them:

    FeqIn3 = FeqIn1 - FeqIn2

All C++ statements must be terminated by a `;` otherwise it doesn't know where one statement finishes and the next one begins.

    area(1) = 0;
    (and many others)

You have declared a bunch of float variables in the global scope.  You are then trying to use those float variables as functions, and on top of that you are then trying to assign a value to the return value of that function.  That makes absolutely no logical sense whatsoever.

I think you meant to be using arrays of float values.  Arrays are denoted by `[` and `]` not `(` and `)`.  Further, they have to be defined as arrays, including the size of the array, not a single value.  Also in C++ arrays are *zero based* (i.e., they start at index 0 not index 1).

For example, `area` could be defined as:

    float area[1024]; // 1024 floating point values in an array
    // ...
    area[0] = 0;

Next:

    Recarea(n+1) = t(2)*(FeqIn3(n));

I don't even know what to make of this bit...  If I assume you should replace `(...)` with `[...]` for indices to arrays, it still makes no sense.  You're calculating a single value (`FreqIn3 = FreqIn1 - FreqIn2`) then using that as an array (`FreqIn3[n]`) which makes absolutely no sense to me at all.  Then you're using another value `t` which you are incrementing (incorrectly, more on that later), which again you are then trying to use as an array (`t[2]`).  Which is it - arrays or single values? And how do you increment an entire array?

Now the incrementing:

    for (n = 1; n = t; t++)

`n` starts at the value 1.  While `n` is assigned the value `t`, increment `t`.  Now, does that sound logical?  And what is `t`? when that loop starts?  It has no defined value, so it could be anything at all.  And when does the loop end?  Well, since you're using float values for your counters (which is idiotic at best) you won't ever get any integer wraparound, so `t` will never equal `0` and consequently the result of assigning `t` to `n` will never be `0`, so the loop will never end.

I think you need to go back to absolute basics and learn a bit more about syntax of C++, arrays, functions, loops, etc, before embarking on something complex like signal integration.

body:
As previous answers have pointed out, your understanding of C syntax has shortcomings, and you should study C further.  Besides those syntax issues, you may need to revise some of your concepts of how to program.

Firstly, the references you looked at regarding integration may have shown forms like Tₓ₊₁ = (δ/2)·(Vₓ₊₁ – Vₓ) for “triangle area” and Rₓ₊₁ = δ·Vₓ for “rectangle area” [where I've written δ in place of your t(2)].  In spite of the use of subscripts in these formulas, the array concepts mentioned in other answers are not relevant here.  Instead of saving voltage data in arrays, just save and work with two voltage values:  the current differential voltage reading and the previous differential voltage reading.  Letting Vᵣ and Vₓ stand for previous and new voltage differences, use Vᵣ where Vₓ is called for, and Vₓ where Vₓ₊₁ is called for.  At the end of each step, set Vᵣ = Vₓ.

Secondly, making separate computations of “triangle area” and “rectangle area” is verbose, unnecessary, and less accurate than a properly combined computation.  Note that Tₓ₊₁ + Rₓ₊₁, as used in computing areaₓ₊₁, is equal to  (δ/2)·(Vₓ₊₁ – Vₓ) + δ·Vₓ = (δ/2)·Vₓ₊₁ – (δ/2)·Vₓ + δ·Vₓ = (δ/2)·Vₓ₊₁ + (δ/2)·Vₓ = δ·(Vₓ₊₁ + Vₓ)/2.  Thus, instead of those three lines of code using two temporary variables and lots of indices, use code like the following for the integral:

    area += deltaT*(Volt_r + Volt_s)/2;
    Volt_r = Volt_s;

(In the above, `Volt_s` corresponds to your `FeqIn3` value.)

Thirdly, your attempted `for` loop needs to be replaced by an actual `for` loop; and in addition, `deltaT`, a time-step delta, needs to be computed.  (Your `t(2)` needs to represent a change in time, not an absolute time, to represent the time-width of the rectangle and triangle you are adding to the total.)  To get a `deltaT`, read `millis()` after the `analogRead` lines.  For example, you could say:

    Volt_s = analogRead(analogInPin) - analogRead(analogInPin1);
    t_s = millis();
    deltaT = t_s - t_r;
    area += deltaT*(Volt_r + Volt_s)/2;
    t_r = t_s;
    Volt_r = Volt_s;

Fourthly, using two `analogRead`s to get a differential voltage has two problems:  first, any common-mode voltage wastes bits of ADC resolution, so contributes to error; second, the two reads occur at different times so their voltages are not comparable.  Instead, you could use an external op-amp to subtract voltages, or could use the Due's differential-front-end ADC mode, per Section 43.6.8, *Differential Inputs*, on page 1326 in the [ARM Cortex M3 Processor manual](http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf), plus possibly a gain of 1, 2, or 4 (per Section 43.6.9).  Also see: [Analog performance ... of Due's 12 bit ADC](http://www.djerickson.com/arduino/) (including how to speed up `analogReads` on the Cortex), [Differential Sensing with Arduino](http://forum.arduino.cc/index.php?topic=147830.0), [Setting ADC compare mode in a differential input](http://forum.arduino.cc/index.php?topic=194770.0), and [Due pinout diagram](http://forum.arduino.cc/index.php?topic=132130.0).


body:
**Where do I find the pins relative to timers of each individual Arduino microcontroller?**

As I like Arduino's I already have various samples of them. The one I mostly use is the Uno and Micro for now... I'm planning to also get a Mega and others. Most simple things work on all devices, but if you start with complex code to fasten up things, every device is a little different.
A problem I could not solve for days now is the relation between pins and timers.

I cannot find any information about the Arduino Micro. I also don't know exactly what the proper keywords are that I need to find the relation between timers and pins.

**Example:**
A PWM driver multiplexing

As I for now just got some stuff from my local dealer I have no access to shift registers, PWM drivers and other proper integrated circuits.

So I used the Arduino as a PWM driver for 8 RGB or 24 (3*8) white LEDs.
The code works on Arduino Uno. But as the **Arduino Micro has no *Timer2***, `TCCR2B`, I cannot use the same code on the Arduino Micro.

Even if I understand the code (I wrote a lot in other languages...), some of the Atmel chip specific parameters are not clear.

This function sets the prescaler of the timer:

    void setPwmFrequency(int pin, int divisor){

      byte mode;
      if(pin==5||pin==6||pin==9||pin==10){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 64:mode=0x03;break;
          case 256:mode=0x04;break;
          case 1024:mode=0x05;break;
          default:return;
        }
        if(pin==5||pin==6){
          TCCR0B=TCCR0B&0b11111000|mode;
        } else{
          TCCR1B=TCCR1B&0b11111000|mode;
        }
      }else if(pin==3||pin==11){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 32:mode=0x03;break;
          case 64:mode=0x04;break;
          case 128:mode=0x05;break;
          case 256:mode=0x06;break;
          case 1024:mode=0x7;break;
          default:return;
        }
        TCCR2B=TCCR2B&0b11111000|mode;
      }
    }

First of all, I probably don't even need this function as soon I know what frequency I want, and so I probably need only two lines to set my three (RGB) pins.

    //Arduino Uno timer setup for pin 9, 10, and 11
    TCCR1B=TCCR1B&0b11111000|0x01; // Pin 9,10
    TCCR2B=TCCR2B&0b11111000|0x01; // Pin 11

1. Correct, I need to set `TCCR1B` only one time?

2. What does the `0b11111000` refer to?

In the setup function there is also this line:

    TIMSK2 = 1<<TOIE2;

3. What does this do?

While the above three questions are not so important until it works, **I need to understand how I can convert those timers to work with Arduino Micro**, but also later with other Arduino boards.

----------

**On Arduino Micro**

There is no timer 2

Do pin 9, 10, and 12 have the same timer?

    ??????=??????&0b11111000|0x01;

Also if I understand correctly the Arduino Micro has:

1. A higher PWM range 1024 vs 255 (UNO)??
2. A much higher frequency available in on Timer4 only for pin 13

**So is there somewhere a table describing the differences between all Arduino timers?**

**Full working (on Arduino Uno) code.**

    unsigned char Prescaler=0;
    unsigned char CurrentLED=0;
    unsigned char LEDValues[8][3];
    unsigned char ports[8]={
      0b00000100,
      0b00001000,
      0b00010000,
      0b00100000,
      0b01000000,
      0b10000000,
      0b00000001,
      0b00010000
    };//PINS 2,3,4,5,6,7,8,12

    #define PrescalerOverflowValue 4

    ISR(TIMER2_OVF_vect){
      if(Prescaler<PrescalerOverflowValue){
        Prescaler++;
      }else {
        Prescaler=0;
        Multiplex();
      }
    }

    void Multiplex(void){
      PORTD&=0b00000011;
      PORTB&=0b11101110;
      analogWrite(9,255-LEDValues[CurrentLED][0]);
      analogWrite(10,255-LEDValues[CurrentLED][1]);
      analogWrite(11,255-LEDValues[CurrentLED][2]);
      CurrentLED<6?(PORTD|=ports[CurrentLED]):(PORTB|=ports[CurrentLED]);
      CurrentLED++;
      if(CurrentLED>7)CurrentLED=0;
    }
    void setPwmFrequency(int pin, int divisor){
      byte mode;
      if(pin==5||pin==6||pin==9||pin==10){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 64:mode=0x03;break;
          case 256:mode=0x04;break;
          case 1024:mode=0x05;break;
          default:return;
        }
        if(pin==5||pin==6){
          TCCR0B=TCCR0B&0b11111000|mode;
        }else{
          TCCR1B=TCCR1B&0b11111000|mode;
        }
      }else if(pin==3||pin==11){
        switch(divisor){
          case 1:mode=0x01;break;
          case 8:mode=0x02;break;
          case 32:mode=0x03;break;
          case 64:mode=0x04;break;
          case 128:mode=0x05;break;
          case 256:mode=0x06;break;
          case 1024:mode=0x7;break;
          default:return;
        }
        TCCR2B=TCCR2B&0b11111000|mode;
      }
    }

    void setup(void){

      pinMode(2,OUTPUT);//1
      pinMode(3,OUTPUT);//2
      pinMode(4,OUTPUT);//3
      pinMode(5,OUTPUT);//4
      pinMode(6,OUTPUT);//5
      pinMode(7,OUTPUT);//6
      pinMode(8,OUTPUT);//7
      pinMode(12,OUTPUT);//8
      pinMode(9,OUTPUT);//red
      pinMode(10,OUTPUT);//green
      pinMode(11,OUTPUT);//blue
      setPwmFrequency(9,8);
      setPwmFrequency(10,8);
      setPwmFrequency(11,8);
      TIMSK2=1<<TOIE2;
    }

    void loop(void){
      for(int i=0;i<8;i++){
        //LEDValues[i][0]; // Red
        //LEDValues[i][1]; // Green
        //LEDValues[i][2]; // Blue
      }
    }

title: Arduino Uno vs Arduino Micro timers → pins

Answers: 2

body:
> I cannot find any information about the arduino micro. I also don't know exactly what the proper keywords are that i need to find the relation between timers and pins.

* Go to the [products page for the Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro) on the Arduino web site. You will find that the processor is the ATmega32U4.

* Download the [datasheet for the ATmega32U4](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf) - it's on that page.

* Download the [reference schematic for the Micro](https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf) - also on that page.

Now we know the processor, the datasheet tells you about the timers, and the schematic tells you which ATmega32U4 pins are connected to which pins on the Micro board.

---

>  But as the Arduino Micro has no Timer2 TCCR2B i cannot use the same code on the Arduino micro.

True. But it has Timer 1, Timer 3 and Timer 4. You just need to adjust the registers a bit.

---

> Correct, I need to set TCCR1B only one time?

Yes you can do that. Personally I normally stop the timer and then set the parameters in case setting them when it is running has a different effect. eg

    TCCR1A = 0;  // stop timer 1
    TCCR1B = 0;
    TCCR1C = 0;

---
>        TCCR1B=TCCR1B&0b11111000|0x01; //pin 9,10
>
> What do the 0b1111000 refer to?

In this case the first part `TCCR1B & 0b11111000` clears the low-order 3 bits (the rest are ANDed in with 1 so they stay the same as before).

Then it sets the lower-order bit. In this particular case you are setting up a prescaler of 1 times the clock rate.

[![TCCR1b][1]][1]

[![Clock pre-scalers for timer 1][2]][2]

---

>        TIMSK2=1<<TOIE2;
>
>    what does this ?

TIMSK2 is a timer register.

[![TIMSK2][3]][3]

By shifting 1 left "TOIE2" bits it sets that bit (ie., TOIE2 in TIMSK2).

In other words, it enables the overflow interrupt for Timer 2.

---

> On Arduino Micro
> There is no timer 2
> Pin 9,10,12 have the same timer ?

Look at the reference schematic. Yes it looks like it.

[![Micro schematic part][4]][4]

As you can see from that pin 30 (on the chip) is labelled `OC4B` which means it is the "output compare timer 4: B output". That pin has the net name "IO10*" which I presume means it is connected to board pin 10 (pin 30 on the chip).

---

> Also if I understand correctly the Arduino micro has:
>
>    1. a higher PWM range 1024 vs 255 (UNO)??
>    2. a much higher frequency available in on timer4 only for pin 13

No, the Uno has Timer 1 which is 16 bits (up to 65536). The Micro has Timer 4 which is 10 bits and therefore can count up to 1024.

Anyway, the frequency is a function of the clock speed. On either chip, by using a prescaler of 1, and counting up to 1, you can get an 8 MHz frequency (one up, one down from 16 MHz).

The higher number of bits in the timer, the *finer the resolution* - that is you can adjust the frequency in finer steps, and you can adjust the PWM duty cycle in finer steps.

**However** with Timer 4 on the Micro you can, apparently, clock it with 6 times the clock rate (96 MHz) which is used for the USB part of the chip. Setting appropriate bits (I haven't done this personally) you could get that higher frequency.

You can apparently get 96 MHz, 64 MHz or 48 MHz clock frequencies on Timer 4 (as well as the normal ones).

---

*Added in response to comments*

> Pin 12 on the chip has 2 timers, OC0A & OC1C??

Yes, from the datasheet:

> The Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin for output. The outputs of the Output Compare units (OC1C and OC0A) overrides the normal PORTB7 Register when one of them is enabled (i.e., when COMnx1:0 is not equal to zero). When both OC1C and OC0A are enabled at the same time, the modulator is automatically enabled.

---

> What timer do i need to use for let's say pin 9,10,12 on arduino micro?

Looks like Timer 4.

---

> in arduino ide i can only write analogWrite(255)

That is changing the PWM duty cycle for the timers configured in their default way.

Have a look in wiring.c:

 // timers 1 and 2 are used for phase-correct hardware pwm
 // this is better for motors as it ensures an even waveform
 // note, however, that fast pwm mode can achieve a frequency of up
 // 8 MHz (with a 16 MHz clock) at 50% duty cycle

analogWrite changes the duty cycle, not the frequency.

---

>  You can apparently get 96 MHz... so at the end arduino micro can go faster on timer 4

I'm not sure what you mean by "go faster" here.

---

>  but I actually did not solve the problem. I hope you give me a hint to how to make it work.

It isn't clear really what you want to happen.

* What devices are you driving?
* Why do you need high frequencies?
* What is the underlying problem?

---

### Reference

* [Timers and counters](http://www.gammon.com.au/timers) - mainly about the Atmega328P, however a lot of it applies to the other chips as well.

  [1]: https://i.stack.imgur.com/09JE7.png
  [2]: https://i.stack.imgur.com/pqJhv.png
  [3]: https://i.stack.imgur.com/yYVe8.png
  [4]: https://i.stack.imgur.com/CMnIB.png

body:
You can check `pins_arduino.h` file as well.

    // ATMEL ATMEGA32U4 / ARDUINO LEONARDO
    //
    // D0    PD2     RXD1/INT2
    // D1    PD3     TXD1/INT3
    // D2    PD1  SDA   SDA/INT1
    // D3#    PD0  PWM8/SCL OC0B/SCL/INT0
    // D4  A6  PD4     ADC8
    // D5#    PC6  ???   OC3A/#OC4A
    // D6#  A7  PD7  FastPWM  #OC4D/ADC10
    // D7    PE6     INT6/AIN0
    //
    // D8  A8  PB4     ADC11/PCINT4
    // D9#  A9  PB5  PWM16  OC1A/#OC4B/ADC12/PCINT5
    // D10#  A10  PB6  PWM16  OC1B/0c4B/ADC13/PCINT6
    // D11#    PB7  PWM8/16  0C0A/OC1C/#RTS/PCINT7
    // D12  A11  PD6     T1/#OC4D/ADC9
    // D13#    PC7  PWM10  CLK0/OC4A
    //
    // A0  D18  PF7     ADC7
    // A1  D19  PF6     ADC6
    // A2  D20  PF5     ADC5
    // A3  D21  PF4     ADC4
    // A4  D22  PF1     ADC1
    // A5  D23  PF0     ADC0
    //
    // New pins D14..D17 to map SPI port to digital pins
    //
    // MISO  D14  PB3     MISO,PCINT3
    // SCK  D15  PB1     SCK,PCINT1
    // MOSI  D16  PB2     MOSI,PCINT2
    // SS  D17  PB0     RXLED,SS/PCINT0
    //
    // TXLED D30  PD5     XCK1
    // RXLED D17     PB0
    // HWB    PE2     HWB

There is an array inside the same file with name  `digital_pin_to_timer_PGM` that list the timers also.

    const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     TIMER0B,  /* 3 */
     NOT_ON_TIMER,
     TIMER4A,  /* 5 */
     TIMER4D,  /* 6 */
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     TIMER1A,  /* 9 */
     TIMER1B,  /* 10 */
     TIMER0A,  /* 11 */

     NOT_ON_TIMER,
     TIMER4A,  /* 13 */

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
    };


body:
Im making a small, controllable toy car. Im using the L239D motor controller to drive 2 6V DC motors, which I intend to control with a joystick. Using the L239D state table (shown below), I can make the car move forward, backward, left and right.

Thats all good, but I want the car to do all the bits in between those movements (drifting slightly left/right etc depending on joystick location). So far I have two separate functions that look at the x-axis and y-axis value from the joystick, scale them and apply a pwm signal. This works fine when only one function is on but ofcourse, they overwrite each other.

My idea then was to create a variable that takes the displacement of the joystick in both axis and divides them, this will be the duty cycle. I then have a delay at the end of each loop which is sized by this duty cycle. The only problem is that the motor stutters a lot and it dosent work very well at all.

I was wondering if anyone has a better idea for getting full motor control with the joy stick rather than the simple block movements (full right, full left, full forward, full backward). Thanks!

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

  [1]: https://i.stack.imgur.com/9Aw5R.png
  [2]: https://i.stack.imgur.com/JFiwV.png

title: Using L239D with a joystick

Answers: 1

body:
The problem here is that you lack the concept of speed with your motors.

It's not enough to turn the motors on or off in the right direction, you have to control the speed of them.

Your left/right control is fine as it is (without the delay in your loop), which is controlled by the inputs being either on or off to define the flow of current through the motor.  Now all you need to do is control the speed of the motors while they are in those states.

Fortunately there is another pair of inputs to the driver chip that you have completely overlooked: `ENABLE1` and `ENABLE2`.  These can accept a PWM signal and define the ratio of on-to-off for the motor on that channel.

So you can connect a PWM signal to each of those inputs (all the other inputs are just straight digital ON/OFF signals), and setting the duty cycle of those PWM signals defines the speed of the motor (0 = stop, 255 = full speed).

Now all you need to do is interpret the joystick properly, for instance:

* Between centre and half-left: Left = Stop, Right = Forward, Enable Right = percentage of half the joystick range
* Between half-left and full-left: Left = Reverse, Right = Forward, Enable Right = 100%, Enable Left = percentage of half the remaining joystick range

And of course reversed for right turns.

You could incorporate into that the forward/backward position of the joystick to add an overall forward or backward speed to the motors so you have full 2D motion.

It may be better to visualise the joystick in [Polar](https://en.wikipedia.org/wiki/Polar_coordinate_system) space instead of simple Cartesian space.  Convert the X/Y coordinates of the joystick's position into an angle and distance from the centre point.  The distance defines the overall speed, and the angle defines how that speed is split between the left and right motors (enable pins), and the direction of those motors (input pins).


body:
Joysticks usually have two outputs, one for the x-axis and one for the y-axis. Most of the bluetooth modules I have found only have one tx line.. Is there a way to set them up to use one bluetooth module to connect to arduino?

Im thinking of buying another but I'm wondering if anyone has a better idea than this, or if what I'm thinking is even possible.

Thanks!

title: Sending joystick data via bluetooth

Answers: 2

body:
Unless you have a very special joystick and a very special bluetooth module you can't just connect a joystick to the TX pin of a bluetooth module.

Instead you have to have the joystick (I am assuming a 2D analog joystick) to a pair of analog inputs on (for instance) an Ardiuno, which then samples the analog values.  It is then up to you to decide what you do with that sampled data - in your case you want to send it out via serial to the bluetooth module (I assume something like a HC-05 or HC-06).  What that data is, and how you interpret it, is up to you.

You could send the data as plain text, such as:

    512,512
    512,512
    384,512
    229,512
    83,512
    83,938
    82,1012

Each line specifies a pair of analog values and is terminated by a line-feed.  The receiving end then needs to read each line, split it on the `,`, and interpret the two values as X/Y readings.

That's quite inefficient, though, and there are better "binary" methods that use less bytes to send the readings, but that is more advanced.

body:
So your joystick is sending bt signals?

If you can't find an appropiate data sheet to that i advise you link it with your pc, start hterm and analyse what exactly is sent.(requires to link the bt devices)

If your joystick is not able to out bt signals I'm not sure what you are trying to do there and need more info

PS: I already did the following: control a robot with your smartphone via bt

control a robot with an old ps2 joystick via cable


body:
I was looking for a GPS/OBD2 data logger that logs data to an SD card and eventually arrived at the Arduino powered [Freematics Vehicle Data Logger][1]. It's great that it's programmable, but I have no experience with Arduino.

Reading the documentation, it says that I program the device [either by USBasp or Arduino as ISP][2]. The USBasp is a dongle programmer, but I don't know what is meant by Arduino as ISP.

My goal is to use this device to log data. I don't plan to extensive write programs for it. What is the minimum equipment that I need to have in order to be able to write a bit of code and flash it to the device?

  [1]: http://freematics.com/pages/products/freematics-obd-adapter/
  [2]: http://blog.freematics.com/2014/freematics-obd-ii-adapter-programming-guide/

title: What minimum equipment is needed to program the Freematics Vehicle Data Logger?

Answers: 1

body:
"Arduino as ISP" refers to using an Arduino board in place of a USBasp.  It involves loading a specific sketch onto the Arduino then using the SPI port (and a few other pins) as the programming interface to the target.

It is most often used to program blank chips for use in breadboards by people who don't have a USBasp.  Great for moving your project from the Arduino board to a breadboard without having to buy a hardware programmer.


body:
I've been communicating with a teensy arduino over USB using pySerial--which has been simple, but slow. With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. I'm hoping to get over 1MHz at least, but I don't see a path towards that rate.

Are Ethernet shields capable of augmenting for rates over the MHz range? How can I get faster data transfer rates between my computer and arduino? I'm mainly interested in one-way communications (computer directs teensy).

title: Fast Python to arduino communications

Answers: 2

body:
The fastest means of communicating with the Arduino is [SPI](http://www.gammon.com.au/spi). Ethernet shields use that (as do SD cards). It's quite fast, but it has limits. The fastest the SPI clock can go is the CPU (MCU) clock rate divided by 2 (per bit), that is one byte every 16 CPU clock cycles. There is also an overhead of a couple of clock cycles between bytes, so you can reckon on 888,888 bytes absolute maximum (ie. about 868 kHz) on an Arduino running at 16 MHz.

However that's just throwing the data away. It needs to be stored somewhere, compared to something, acted upon. That all takes clock cycles.

That is for the 16 MHz Arduinos. The Teensy 3.1 apparently runs at 72 MHz which is somewhat faster. I haven't timed SPI on that, presumably you can get a faster transmission rate, but I suspect that the ARM processors also take more instructions to do the same thing, so the 72 MHz might not be quite as fast as it looks.

Then you have the issue of how fast you can get data in and out of the Ethernet card, and how fast you can do whatever-it-is you want to do with it, in the processor.

body:
First of all, khz and mhz are not data transfer rates. They are frequencies - "something per second" - did you mean kilobits/second or kilobytes/second (both, confusingly, abbreviated to kbps by various people).

If you have not already done so, you can specify a bitrate for your communications - serial.begin takes a parameter which specifies the speed - most example seem to use 9600 bits/second, you can crank this all the way up to 115,200 bits/second - 12 times the speed. I don't know if this will work with a Teensy, and/or USB. You will probably at least need to specify this in your terminal program and/or pySerial.

I wonder what you are doing that requires 1Mbyte/second communication with an Arduino, and if you can do that a little smarter?

At that rate, the 64kbytes of memory can be filled up in 1/16th of a second.

You can get a faster "information transfer" by increasing the information density - for example, the English word "True" takes up 4 characters = 32 bits , but a logical true value only takes up 1 bit.

If you are processing the data on the Arduino, at 1mbyte/second, you have 72 instructions to do something with that byte before the next one is there - not much time.

You could increase the data rate by pushing the data in in parallel, using multiple pins - e.g. 32 bits in parallel, one on each of 32 pins, one data point per cycle. There would be no practical way to assimilate data at that speed.

If you are sending this from a PC, perhaps some of the data could be processed on the PC before sending?

Another option would be to divide the work over multiple Teensies, with the PC combining the work - e.g. if you have temperature sensors that output 4 byte values, you want to read 250 of them at a rate of 1000 samples per second (= total of 1mbyte/second), then you might be able to run 25 Teensies, each sampling 10 sensors, and each pushing data at 40kbytes/second, rather than one running at 1mbyte/second.

Quite frankly, these are all fairly contrived examples - most sensors can't be read that quickly; even an Arduino's analog read is limited to 10,000 reads per second - if you do nothing else. This produces 100 kbits/second, or 20kbytes per second (each 10-bit read is returned as two bytes, with the remaining 6 bits being 0).


body:
I am trying to use different buttons to activate different methods for an LED strip. However, when one button is pressed after another has been pressed, I want it to interrupt the first buttons method and begin the second. For example: one button sends a rainbow pattern through the LED strip when pressed, however, while it is cycling through the rainbow, the second button is pressed which sends a white cycle through the LED strip. There will be 24 buttons total. I have gotten this to work with 2 buttons but am having trouble getting it to work for a third. The code is below:

         void loop(){

           if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
               stopCycle();
               theaterChaseRainbow(50);
           }
           if (digitalRead(inPin(2)) == HIGH){
               stopCycle();
               theaterChase(strip.Color(127, 127, 127), 50); // White
           }
           if (digitalRead(inPin(3)) == HIGH){
               stopCycle();
               rainbowCycle(0);
           }

         }

         //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
      for (int j=0; j<100; j++) {  //do 100 cycles of chasing
        if (digitalRead (inPin(1)) == LOW) { //checks that other button(s) have not been pressed
          if (digitalRead (inPin(3) == LOW)){
          for (int q=0; q < 3; q++) {
            for (int i=0; i < strip.numPixels(); i=i+3) {
              strip.setPixelColor(i+q, c);    //turn every third pixel on
            }
            strip.show();

            delay(wait);

            for (int i=0; i < strip.numPixels(); i=i+3) {
              strip.setPixelColor(i+q, 0);        //turn every third pixel off
            }
          }
        }
        }
      }
    }

    void rainbow(uint8_t wait) {
      int i, j;

      for (j=0; j < 384; j++) {
       if (digitalRead (inPin(2)) == LOW) { // 3 cycles of all 384 colors in the wheel
        if (digitalRead (inPin(3) == LOW)){
        for (i=0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel( (i + j) % 384));
        }
        strip.show();   // write all the pixels out
        delay(wait);
       }
       }
      }
    }

    uint32_t Wheel(uint16_t WheelPos)
    {
      byte r, g, b;
      switch(WheelPos / 128)
      {
        case 0:
          r = 127 - WheelPos % 128;   //Red down
          g = WheelPos % 128;      // Green up
          b = 0;                  //blue off
          break;
        case 1:
          g = 127 - WheelPos % 128;  //green down
          b = WheelPos % 128;      //blue up
          r = 0;                  //red off
          break;
        case 2:
          b = 127 - WheelPos % 128;  //blue down
          r = WheelPos % 128;      //red up
          g = 0;                  //green off
          break;
      }
      return(strip.Color(r,g,b));
    }

    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for (j=0; j < 384 * 5; j++) {     // 5 cycles of all 384 colors in the wheel
        if (inPin(1) == LOW) {
          if (inPin(2) == LOW) {
        for (i=0; i < strip.numPixels(); i++) {
          // tricky math! we use each pixel as a fraction of the full 384-color wheel
          // (thats the i / strip.numPixels() part)
          // Then add in j which makes the colors go around per pixel
          // the % 384 is to make the wheel cycle around
          strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) );
        }
        strip.show();   // write all the pixels out
        delay(wait);

          }
        }
      }
    }

    void stopCycle(){
        int i;
        for (i=0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, 0);
        }
        strip.show();   // write all the pixels out
    }

title: Multiple buttons activating different methods for an LED strip

Answers: 2

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

Inside each inner loop, just test the switches and `return` if they are pressed.

eg.

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
      for (int j=0; j<100; j++) {  //do 100 cycles of chasing
        for (int q=0; q < 3; q++) {
          for (int i=0; i < strip.numPixels(); i=i+3)
          {
            strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();
          delay(wait);

          // give up if switches pressed
          if (digitalRead (inPin(1)) == HIGH ||
              digitalRead (inPin(2)) == HIGH ||
              digitalRead (inPin(3)) == HIGH )
            return;

          for (int i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

---

> am having trouble getting it to work for a third

If that doesn't help please explain the nature of this "trouble".

---

You may need to debounce the switch presses. And you may need to wait for them to release the switch, eg.

     if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
               stopCycle();
               while (digitalRead(inPin(1)) == HIGH)
                  {  }   // wait for switch release
               delay (10);  // debounce
               theaterChaseRainbow(50);
           }

body:
I would normally do this (pseudocode):

    void loop() {
        static state=state_off;
        if (button_1_pushed) {
            state=state_1;
        } elseif (button_2_pushed) {
            state=state_2;
        }
        if (state==state_off) {
            turn_all_leds_off();
        } elseif (state==state_2) {
            shownextframe_rainbow();
        } elseif (state==state_2) {
            shownextframe_chaser();
        }
        delay(1);
    }

In shownextframe_chaser/shownextframe_rainbow, I would probably work out what should be shown based on the current millis() - e.g. if your chaser has 10 lights, and you want it to pulse over 1 second, then each led should be on for 100 millis, so at any instant, the led that should be on is `(millis()/100)` (assuming the led's are numbered for 0 to 9).


body:
I'm trying to communicate with some industrial hardware, on ModBusRTU, from my Intel Galileo Gen2 board. I use this board to convert UART to RS485 http://linksprite.com/wiki/index.php5?title=RS485_Shield_V2.1_for_Arduino and I can talk serially between Arduino (with SoftwareSerial on pin 2/3) and Galileo (with Serial1 on pin 0/1). So I know the RS485's link is working.

With Arduino Uno I can talk with my devices using ModBusRTU, thanks to this library https://github.com/4-20ma/ModbusMaster

On galileo gen2 I received this warning `WARNING: library ModbusMaster claims to run on [avr, sam] architecture(s) and may be incompatible with your current board which runs on [i586] architecture(s).` because of the different architecture.

Now I'm trying to use the examples of cooking hack's tutorial about modbus and rs485 for Arduino, Raspberry and Galileo but I can't make it works for me. I received tons of compiling errors like these:

    C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp: In member function 'uint8_t ModbusMaster485::ModbusMasterTransaction(uint8_t)': C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:701:50: error: '_crc16_update' was not declared in this scope
    C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:814:52: error: '_crc16_update' was not declared in this scope
    C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp: At global scope:
    C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:881:14: error: prototype for 'unsigned int ModbusMaster485::makeWord(unsigned int)' does not match any in class 'ModbusMaster485'
    In file included from C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:25:0: C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:302:11: error: candidates are: uint16_t ModbusMaster485::makeWord(uint8_t, uint8_t)
    C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:301:14: error: uint16_t ModbusMaster485::makeWord(uint16_t) C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:887:14: error: prototype for 'unsigned int ModbusMaster485::makeWord(uint8_t, uint8_t)' does not match any in class 'ModbusMaster485'
    In file included from C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.cpp:25:0: C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:302:11: error: candidates are: uint16_t ModbusMaster485::makeWord(uint8_t, uint8_t) C:\Intel\arduino-1.6.4\libraries\ModBusMaster485\ModbusMaster485.h:301:14: error: uint16_t ModbusMaster485::makeWord(uint16_t) Error compiling.

Did someone has got ModBus working on Galileo Gen2?

title: Anyone using ModBus RTU on Galileo gen 2?

Answers: 0


body:
I am trying to make a 24 button board that assigns different methods to each button. When a button is pressed, it should interrupt the method of the previous button and begin the new method. Currently, the button has to be held down in order to work. I'm not sure why since the methods should continue without being held down. All 24 methods are similar to the one posted below.

    loop(){
      if (digitalRead(inPin(5)) == HIGH){
        fifthButtonTheatreChaseRedSlow(strip.Color(127,   0,   0), 100); // Red
      }

    void fifthButtonTheatreChaseRedSlow(uint32_t c, uint8_t wait) {
      for (int j=0; j<100; j++) {  //do 100 cycles of chasing
        for (int q=0; q < 3; q++) {
          for (int i=0; i < strip.numPixels(); i=i+3)
          {
            strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();
          delay(wait);

          // give up if switches pressed
          if (digitalRead (inPin(1)) == HIGH ||
                 digitalRead (inPin(2)) == HIGH ||
                 digitalRead (inPin(3)) == HIGH ||
                 digitalRead (inPin(4)) == HIGH ||
                 digitalRead (inPin(6)) == HIGH ||
                 digitalRead (inPin(7)) == HIGH ||
                 digitalRead (inPin(8)) == HIGH ||
                 digitalRead (inPin(9)) == HIGH ||
                 digitalRead (inPin(10)) == HIGH ||
                 digitalRead (inPin(11)) == HIGH ||
                 digitalRead (inPin(12)) == HIGH ||
                 digitalRead (inPin(13)) == HIGH ||
                 digitalRead (inPin(14)) == HIGH ||
                 digitalRead (inPin(15)) == HIGH ||
                 digitalRead (inPin(16)) == HIGH ||
                 digitalRead (inPin(17)) == HIGH ||
                 digitalRead (inPin(18)) == HIGH ||
                 digitalRead (inPin(19)) == HIGH ||
                 digitalRead (inPin(20)) == HIGH ||
                 digitalRead (inPin(21)) == HIGH ||
                 digitalRead (inPin(22)) == HIGH ||
                 digitalRead (inPin(23)) == HIGH ||
                 digitalRead (inPin(24)) == HIGH)
                   return;

          for (int i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

Not sure if it's a hardware issue or a software issue.

title: Buttons for LED strip only work when held down

Answers: 2

body:
It's a software issue.  You are basically saying "If this button is currently pressed down then run this sequence once", rather than "If this button has transitioned from OFF to ON then set my current sequence to X"

You need to learn about the [Finite State Machine](http://hacking.majenko.co.uk/finite-state-machine) and about switching from one state to another (or one selected sequence to another) when a button *changes* state not when it is *in* a state.

So basically the whole logic of your program is flawed and needs re-working.

body:
Related to <https://arduino.stackexchange.com/questions/14320/multiple-buttons-activating-different-methods-for-an-led-strip>

     // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
             digitalRead (inPin(2)) == HIGH ||
             digitalRead (inPin(3)) == HIGH ||
             digitalRead (inPin(4)) == HIGH ||
             digitalRead (inPin(6)) == HIGH ||
             digitalRead (inPin(7)) == HIGH ||
             digitalRead (inPin(8)) == HIGH ||
             digitalRead (inPin(9)) == HIGH ||
             digitalRead (inPin(10)) == HIGH ||
             digitalRead (inPin(11)) == HIGH ||
             digitalRead (inPin(12)) == HIGH ||
             digitalRead (inPin(13)) == HIGH ||
             digitalRead (inPin(14)) == HIGH ||
             digitalRead (inPin(15)) == HIGH ||
             digitalRead (inPin(16)) == HIGH ||
             digitalRead (inPin(17)) == HIGH ||
             digitalRead (inPin(18)) == HIGH ||
             digitalRead (inPin(19)) == HIGH ||
             digitalRead (inPin(20)) == HIGH ||
             digitalRead (inPin(21)) == HIGH ||
             digitalRead (inPin(22)) == HIGH ||
             digitalRead (inPin(23)) == HIGH ||
             digitalRead (inPin(24)) == HIGH)
               return;

Time to learn about loops, buddy. How about:

    for (int i = 1; i <= 24; i++)
      if (digitalRead (inPin (i)) == HIGH)
        return;

My guess about this particular problem is that you are not debouncing. You enter the function, one of the bounces is detected, and you leave the function. I mentioned debouncing in your other, closely-related, thread.

---

Let me show you what a switch bounce looks like. Using a normal switch from my parts drawer, this is what you see when you press it:

[![Switch bounce][1]][1]

See that? It looks to the (fast) Arduino that you pressed the switch 20 or 30 times. That is the physical metal bouncing back and forwards. So if you test for one press, and then stop when you get another, your chances of it working are rather slim. That's why a simple delay of (say) 10 ms after detecting a change in state of the switch can help debounce it.

See: [Switches tutorial](http://www.gammon.com.au/switches)

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


body:
**Explain this line in simple words.**

    TCCR0B=TCCR0B&0b11111000|0x01;

As the variuos arduinos have different chips. They also have different timers and different pins which use them.

Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.

I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me.
Shortcuts like the following.

    TCCR0B=TCCR0B&0b11111000|0x01;

What does that?

    TCCR0B

`TCCR` = Prefix for timers. Correct?

`0` = Timer1 or 0 call it however you want.

`B` = **What is A,B,C and sometimes D for?** What does this?why in that code is the programmer using B and not A,C or D

`TCCR0B=` Timer 0 B is equal to:

`TCCR0B&` **if Timer 0 B return True .. exists "&" ?**

`0b11111000` **What is this?** i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.

`|0x01;` I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.

title: Arduino timers. How they work

Answers: 4

body:
First I'll tackle what

    TCCR0B=TCCR0B&0b11111000|0x01;

means from a pure programming perspective:

Let's break it down into parts:

    TCCR0B = TCCR0B & 0b11111000 | 0x01;

`TCCR0B` is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.

`0b11111000` is a binary representation of a value.  It's the same as the hexadecimal number `0xF8`.  F is 15.  15 in binary is 1111.  8 is 8 in both hexadecimal and decimal.  8 in binary is 1000.  Put the two together and you have 11111000.  Incidentally, in decimal that is 248.

`0x01` is hexadecimal for 1 in decimal - it's also 1 in binary.

Between them are *bitwise* operators - `&` is a bitwise `AND` operation, and `|` is a bitwise `OR` operation.  `AND` calculates which bits in a pair of binary numbers are both on, and `OR` calculates which bits in a pair of binary numbers are on in either of the numbers.

So take the first one first.  Say the `TCCR0B` register contains the value `0x6F`, which is 157 in decimal, or 01101111 in binary.  The first operation is to `AND` that with 11111000:

    01101111
    11111000 AND
    --------
    01101000

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the `&` operator.

Ok, so the next operation is to `OR` it with 0x01:

    01101000
    00000001 OR
    --------
    01101001

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.

So finally the value is then stored in `TCCR0B`.

In summary that specific operation *clears the lower three bits then sets the lowest bit* of TCCR0B.

Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip.  For instance, take the ATMega328P chip from the Arduino UNO board.  Section 14.9.2 "TCCR0B – Timer/Counter Control Register B" of [the datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf) describes that register in detail.  The bit-wise overview looks like this:

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

Those bits all correspond 1:1 to the binary bits from above in the same order.  So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0.  The second stage, ORing 0x01, then sets CS00 to 1.

The datasheet goes on to tell you what those mean:

> * Bits 2:0 – CS02:0: Clock Select
>
> The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

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

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock.  If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)".  So your masking would change to:

    TCCR0B = TCCR0B & 0b11111000 | 0x02;

Or more explicitly so you can see the bits easier:

    TCCR0B = TCCR0B & 0b11111000 | 0b010;

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer.  They each serve a different purpose.  TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.

Not to be confused with OCR0A and OCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs (OC0A as Uno pin D6, and OC0B as Uno pin D5) synchronised from the same timebase. (See sections 14.9.4 OCR0A – Output Compare Register A and 14.9.4 OCR0B – Output Compare Register B in the datasheet)

  [1]: https://i.stack.imgur.com/eQKLG.png
  [2]: https://i.stack.imgur.com/eMoHl.png

body:
The answer, at high level, is: each bit (or group of bits) in a register is, in practice, like a knob that can configure certain parts of the HW.
For each peripheral you want to control, you have to understand the block diagrams, the related knobs and in which registers those knobs are located.
Sometimes there are multiple (almost) identical instances of a certain HW block and in the ATMega case these instances are often addressed with letters.
So registers that have almost identical names, apart from A, B, C, are basically identical, but each of them will affect a separate instance of a certain peripheral.
Depending on which pins or interrupt you want to use, you can choose the specific instance of a certain peripheral.
You should check the ATMega328p programmer's manual (it's 2k pages, but it's easy to find the desired section.)

body:
To add to Majenko's very thorough and excellent answer (which I can't yet upvote because I'm very newbie):
Let's try to hone in on the line of code you need:

    TCCR0B=TCCR0B&0b11111000|0x01;

On that particular Ardiuno, TCCR0B is the register that controls the rate of that particular timer. More specifically, the lowest 3 bits (the last in the 8-bit value) control the prescaler. The manufacturer labels those as CS02, CS01, and CS00. The combination of 1s and 0s in those three bits determines if the clock time is scaled or not, and by how much (or even if there is an external clock source). The reproduced table 14-9 will tell you how much the clock is "slowed down". This lets you create a 1Hz (1-second) timer, for example, rather than the 16Mhz (or whatever your particular board runs at) by scaling down how fast the timer "ticks".
If you google "Arduino hardware timer calculator" or similar, you can find very helpful tools to help you set the clock frequency you want. *Do that,* since there are dangers to setting the wrong values, and your compiler may not catch what can be a serious error.

I only learned about hardware timers after exploring Arduino for a few years. Turns out they are very, very useful!

body:
I understand your question is not about c++ and bit manipulation.

It's not about "Arduino" neither, because your code line does only make sense for a certain avr microcontroller with a register named `TCCR0B`.

Sure, some arduinos are based on such microcontrollers and the c++ compiler used in the arduino toolchain allows access to those hardware registers via their names used in the datasheets.

Details however are beyond "Arduino" and should be looked up in the corresponding controller datasheet.