message:
Arduino ModBus RTU master communication with Power Meter problem

i have an arduino UNO with RS485 module.

I have made this connection:[![RS485 module connection][1]][1]

And i have an problem with communication of this module with power meter
"InePro PRO-1Mod"
([datasheet][2]) over ModBus protocol. I want for example read an **L1 Voltage value**, which i know from the manual (page 24 & 25) that this value is stored in "read holding register" with adrress **5002**. I should communicate with these paramaters:

 - Baud rate 9600
 - 8 data bits
 - even parity
 - 1 stop bit

There is also mention about 120 ohms resistor placed by the power meter (but it is 15cm long cable, and even with the resistor there is no change)

I have tried using many of ModBus libraries and for now none of them doesn't work. I have tried "[Modbus-Master-Slave-for-Arduino][3]" , "[ModbusMaster][4] and now at last i am using this "[simple-modbus][5]".

I think that with that simple modbus library i went far as i can, but it is still doesn't working, but i see on the display of power meter that there is some try to communication (i see a black dot which shows modbus communication)
but i don't receive any useful data.

I am using this code:

        #include <SimpleModbusMaster.h>
    #include <AltSoftSerial.h>

    #define TxEnablePin 2                    // RS485 modbus direction control pin:
    #define baud 9600                           // modbus port speed:
    #define timeout 1000                        // modbus timeout in mSec:
    #define polling 500                         // modbus scan rate in mSec:
    #define retry_count 15

    #define TOTAL_NO_OF_REGISTERS 1// number of registers to poll for:

    AltSoftSerial altSerial;

    enum
    {
     PACKET1,
     TOTAL_NO_OF_PACKETS                       // leave this last entry
    };

    Packet packets[TOTAL_NO_OF_PACKETS];        // array of Packets to be configured

    //struct packetPointer packet1 = &packets[PACKET1];
    unsigned int regs[TOTAL_NO_OF_REGISTERS];   // master register array
    long previousMillis = 0;
    long interval = 1200;
    unsigned long currentMillis;

    void setup() {
     Serial.begin(9600);
     altSerial.begin(9600);
     altSerial.println("Hello World");
     modbus_construct(&packets[PACKET1], 5, READ_HOLDING_REGISTERS, 5000, 2, 0);  //initialize packet
     modbus_configure(&Serial, baud, SERIAL_8E1, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
    }

    void loop() {
     modbus_update();

     float Power;
     unsigned long temp = (unsigned long)regs[1] << 16 | regs[0];
     Power = *(float*)&temp;

      currentMillis = millis();
     if (currentMillis - previousMillis >= interval)
     {
       altSerial.print("Exception errors: ");
       altSerial.println(packets[PACKET1].exception_errors);

       altSerial.print("Failed requests: ");
       altSerial.println(packets[PACKET1].failed_requests);

       altSerial.print("Successful requests: ");
       altSerial.println(packets[PACKET1].successful_requests);
       altSerial.print("Low byte: ");
       altSerial.println(regs[0]);
       altSerial.print("High byte: ");
       altSerial.println(regs[1]);
       altSerial.print("Power ");
       altSerial.println(Power);
       altSerial.println("----------");

       previousMillis = currentMillis;
     }

    }

And i have got only this output in the pc (its repeating of course):

    ----------
    Exception errors: 0
    Failed requests: 5
    Successful requests: 0
    Low byte: 0
    High byte: 260
    Power 0.00
    ----------

Altserial library i am using together with USB2TTL convertor on pins 8 & 9,
to see output.

I should mention that there is only A and B screw terminals on power meter, so i have no option to make common ground connection. I also using an 15cm twisted pair cable UTP.

Can someone help me to make it work ?
I have tried to change adrress of holding register to 0x5000 or 5002, tried changing number of registers.

I have tried to connect rs485 module with USB2TTL to pc and run software called "qModMaster" and it works, but with arduino it doesn't work.

Slave ID (power meter) is 5.

Thank you, for your help.

  [1]: https://i.stack.imgur.com/CWJVM.jpg
  [2]: http://www.ineprometering.com/images/pdf/catalogue/PRO1-user-manual-V2.18.pdf
  [3]: https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino
  [4]: https://github.com/4-20ma/ModbusMaster
  [5]: https://code.google.com/archive/p/simple-modbus/

body:
**I have made it. Now it is working. I only checks A & B cables (tried a new one) and change address of register from 5000 to 0x5000 and now it works. I thought that this library already give 0x before address, because i didn't see it anywhere with 0x before.**

An advice for people with the same problems:
Most of the devices which is using RS485 and ModBus protocol (and have an some kind of display) shows an communication (over 485 & modbus) on display by some kind of mark, for example in my case it was an "dot" which blinks when there's an communication. When this mark is shown, it is sign of that the communication settings is right, so data, parity bit, stop bit & baudrate is OK (data has successfully reached the dest. device).

After that, these devices send you an error message back on its line. So if you have problems with getting data, you should send your message (ask) from the arduino to that device, over an Transmit pin from arduino (of course trough an converter, for example max485) and the Receiving pin (side) connect to your PC through again some kind of converter from UART to USB. (Warning: you should have the same ground potential, so wire all grounds together)

Install some software to communication for modBus on PC (i am using this soft: https://www.simplymodbus.ca/ | you can use demo ) After that let arduino sent an message and receive it by PC. (in simplymodbus look at the "response") read that code and look to the manual for the device you using, where there should be an description of error codes, if not look at this doc.: http://www.simplymodbus.ca/exceptions.htm or [THIS][1]).After that you will have an better look on what is going on and where there is a problem.

  [1]: https://forum.hosteng.com/wndm/HTMLHelp1/Instruction_Set/Modbus_Exception_Codes.htm


sender: user

sender: assistant

body:
I'm using a mp5w pulse meter, the settings:

 - Baud rate : 9600
 - Address : 02
 - Parity : none
 - Stop bit : 1

Modbus memory map table for measurement value /(PV) :

 - Modebus : 31002
 - Address  : 03E9
 - Size    : 5


message:
Propane injection software compiles, uploads, doesn't work

Looking for some help here. I have written out some code to add propane injection for my forklift. It is supposed to read three analog inputs, add them together and multiply the sum by three. There is an interrupt which is triggered by a hall effect sensor which is supposed to fire a solenoid valve for a duration of microseconds. I have mocked this up on a breadboard with a attiny85 pulsing the hall effect pin and nothing happens. Would appreciate some one having a look at the code and letting me know where I went wrong. Thanks.

    const byte interruptPin = 2; //this is the interrupt pin hall sensor//
    int mpPin = A3; //manifold pressure sensor//
    int tpsPin = A4; //throttle position sensor//
    int tunePin = A5; //tune pot 10k//
    volatile byte inj; //this will end up being the duration of the injector pulse//
    int mpValue = 0; //setting manifold variable to zero//
    int tpsValue = 0; //setting throttle positon sensor value to zero//
    int tuneValue = 0; //setting tune value sensor variable to zero//
    int injValue = 0; //setting injection variable to zero//

    void setup() {
     pinMode(12, OUTPUT);  //this is the pin that fires the injector//
     pinMode(interruptPin, INPUT_PULLUP); //set the interrupt pin to high pull up //
     attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);  //set the interrupt to trigger shot isr on low//
    }

    void loop() {
     tpsValue = analogRead(tpsPin); //read the throttle positon sensor//
     mpValue = analogRead(mpPin);//read the manifold pressure sensor//
     tuneValue = analogRead(tunePin); //read the tune sensor//
     injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
    }

    void shot() {
     digitalWrite, 12, HIGH; // initilize injector powerup//
     delayMicroseconds(inj); //delay the calculated value  in microseconds//
     digitalWrite, 12, LOW; //shut down the injector//
    }

body:
I can see two things wrong with your code at first glance.  First is the kind of interrupt you're using:

    attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);

A `LOW` interrupt keeps triggering over and over again *all the time the input is low*.  It's a special interrupt type that is seldom used for anything except waking up the MCU or handling external peripherals with *persistent* interrupt indication.  Instead you should be using `FALLING` which will trigger once and once only when the input transitions from `HIGH` to `LOW`.

    attachInterrupt(digitalPinToInterrupt(interruptPin), shot, FALLING);

Secondly you have two variables that seem to be intended to do the same thing - store the delay time for your output pulse.  And that's caused confusion:

    injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

... and then later ...

    delayMicroseconds(inj); //delay the calculated value  in microseconds//

In your comments you reference the second variable, but the code uses the first one. Change that so it uses just one (volatile) variable:

    inj = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

Alternatively, and perhaps much safer, is to assign the result of the calculation inside a *critical section*, in which case having two variables is useful:

    injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
    noInterrupts();
    inj = injValue;
    interrupts();

This will prevent your interrupt triggering whilst the value is being calculated and placed into the `inj` variable which could result in the `inj` variable containing gibberish, which could cause your engine to explode.


message:
Properly using separate tabs with Arduino IDE

I'm trying to split up a large project of mine into separate tabs in the Arduino IDE and I'm having more than a few troubles with it. My main trouble is finding a way to have routines in extra tabs access the Serial object; because it's really hard to debug things with `Serial.println()` otherwise. All I get, though, is "'Serial' was not declared in this scope".
There appears to be some kind of trick to this? I've noticed that "byte" or "bool" needs to be declared in .cpp tabs and .h tabs but not on the main one?
Is there some kind of easy way to set this up so that I don't need to constantly `#include <stdbool.h>` and `typedef unsigned char byte;`?

Current issue: Main file:

    void setup() {
      Serial.begin(500000);
      PrintMessage();
    }

    void loop() {
    }

driver.ino file:

    byte PrintMessge () {
      Serial.println("printin");
    }

and on compiling:

    error: 'PrintMessage' was not declared in this scope

EDIT: Found a silly typo. Problem solved.

body:
Tabs are actually quite simple:

* If it's named `<something>.ino` it will get merged with the main tab. It's just like working in one big file and you don't need to do anything special.
* If it's named `<something>.cpp` or `<something>.c` it's a completely separate *translation unit* and has to be manually "enroled" into the Arduino system by including the `Arduino.h` header.

So it's simplest to just name them as INO files not CPP files and you don't have to do anything special:

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

  [1]: https://i.stack.imgur.com/BjL38.png
  [2]: https://i.stack.imgur.com/luNa2.png


body:
This question is more about C/C++ header basics rather than Arduino. Anyways, you should have the following file structure: Code in `.cpp`files, Header in `.h` files. Main sketch either `.ino` or `.cpp` (for cpp remember that you must explicitly write out the function prototypes!)

So for your small example that would be:

`main.ino`:

    #include "driver.h"
    void setup() {
      Serial.begin(500000);
      PrintMessage();
    }

    void loop() {
    }

`driver.cpp`

    #include "driver.h"
    byte PrintMessage () {
      Serial.println("printin");
      return 0; //previously had no return although returning 'byte'.
    }

`driver.h`

     //Always use include guards
     #ifndef DRIVER_H
     #define DRIVER_H

     #include <Arduino.h>
     //All function prototypes from driver.cpp.
     byte PrintMessage();

     #endif /* DRIVER_H */

Also corrected a typo from `PrintMessge` to `PrintMessage`. This is the "professional" way to do it, seperate implementation and header files.


message:
Changing Arduino Outputs into Binary

I am new to Arduino so please give me some advice on this really simple problem. I am currently using an Arduino Mega in a school project to make 4 capacitive sensors which are supposed to receive an input when you touch the sensors, and I have programmed the arduino such that you will light up an LED upon touching the sensors.

Now the problem is after I light up the LEDs the serial data monitor gives me many different numbers when I am touching the sensors. Is it actually possible for me to tweak my program such that outputs of my sensor will show up as a single line of '0' when the sensor is not being touched and '1' when the sensor is being touched? This would really help me in the quantifying of some of the data I would wish to collect from my experiments with the sensors.

My code is

    #include <CapacitiveSensor.h>

    CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
    CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
    CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
    CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);

    void setup()
    {
       cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1
       cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
       cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
       cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);

       Serial.begin(9600);
       pinMode(3,OUTPUT);
       pinMode(6,OUTPUT);
       pinMode(9,OUTPUT);
       pinMode(12,OUTPUT);
    }

    void loop()
    {
     long sensor1 =  cs_2_4.capacitiveSensor(50);
     long sensor2 =  cs_5_7.capacitiveSensor(50);
     long sensor3 =  cs_8_10.capacitiveSensor(50);
     long sensor4 =  cs_11_13.capacitiveSensor(50);
    Serial.print("\t");
    Serial.println(sensor1, BIN);  // print sensor output
    Serial.print("\t");
    Serial.print(sensor2, BIN);
    Serial.print("\t");
    Serial.print(sensor3, BIN);
    Serial.print("\t");
    Serial.print(sensor4, BIN);

        if(sensor1 >= 1000)
       {
        digitalWrite(3,HIGH);
       }
       else{
        digitalWrite(3,LOW);
       }
         if(sensor2 >= 1000)
       {
        digitalWrite(6,HIGH);
       }
       else{
        digitalWrite(6,LOW);
       }
        if(sensor3 >= 1000)
       {
        digitalWrite(9,HIGH);
       }
       else{
        digitalWrite(9,LOW);
       }
        if(sensor4 >= 1000)
       {
        digitalWrite(12,HIGH);
       }
       else{
        digitalWrite(12,LOW);
       }
       }

and the output that I end up receiving is

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

Hence it would be really great if I could tweak my code such that the output on the serial monitor would be '0' when there is no output(Not touching sensor) and '1' when there is an output (touching sensor)

Thanks a lot for the help once again!

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

body:
It sounds like what you want isn't really "binary", nor the bit-to-characters expansion of the touch readings.

Rather it sounds like what you want to do is to print the character '0' or '1' for the state of each button.  You already have the decisioning code for your outputs, so you can simply extend it for the serial prints:

    if(sensor1 >= 1000) {
       digitalWrite(3,HIGH);
       Serial.print("1");
    } else{
       digitalWrite(3,LOW);
       Serial.print("0");
    }

and so on, with the next set having tabs and the last a newline.

Worth noting, intermixing the printing and digital outputs will put some time delay between the outputs (potentially quite a bit if the evaluation gets ahead of the serial buffers), so another option could to do all the outputs and then all the prints, or store the decisions in a bit mask for later printins, etc.


body:
`capacitiveSensor` returns an analog value so you need to set a threshold for the point where 0 (AKA `false`) becomes 1 (AKA `true`):

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

    long touchThreshold = 123;  // Adjust this according to your application

...

    boolean sensor1 = (cs_2_4.capacitiveSensor(50) > touchThreshold) ? true : false;

If you don't recognize that syntax, it's the [conditional operator](http://www.cplusplus.com/doc/tutorial/operators/#conditional) but you could just as well use `if`.


message:
DC motors not running using PWM and L298N motor driver

I'm just beginning to understand Arduino. Please bear with me. I have a collision avoidance car running on Arduino Uno, WB291111 L298N motor driver, SG90 servo, Arduino Shield v5, and HC-SR04 ultrasonic sensor. Also, I have the entire setup running on 8.4v batteries. If I just use HIGH/LOW on the motors, it will run without any problems. But if I use the PWM to run the motors on different speeds, it will NOT run at all. The sensor and servo works, but not the motors.  See my codes below. Let me know if you need further details. Any help is greatly appreciated.

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

    //our L298N control pins
    const int enA = 10;
    const int in1 = 6;
    const int in2 = 7;

    const int enB = 9;
    const int in3 = 4;
    const int in4 = 5;

    //sensor pins
    #define trig_pin A2
    #define echo_pin A1

    #define maximum_distance 500
    boolean goesForward = false;
    int distance = 100;

    NewPing sonar(trig_pin, echo_pin, maximum_distance);
    unsigned int uS;

    #define SERVO_PIN 11
    Servo servo_motor;

    void setup(){
      Serial.begin(115200);
      pinMode(enA, OUTPUT);
      pinMode(enA, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);

      servo_motor.attach(SERVO_PIN);

      servo_motor.write(115);
      delay(2000);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
    }

    void loop(){

      int distanceRight = 0;
      int distanceLeft = 0;
      delay(50);

      if (distance <= 20){
        moveStop();
        delay(300);
        moveBackward();
        delay(200);
        moveStop();
        delay(300);
        distanceRight = lookRight();
        delay(200);
        distanceLeft = lookLeft();
        delay(200);

        if (distance >= distanceLeft){
          turnRight();
          moveStop();
        }
        else{
          turnLeft();
          moveStop();
        }
      }
      else{
        moveForward();
      }
        distance = readPing();
    }

    int lookRight(){
      Serial.print("Look Right");
      servo_motor.write(50);
      delay(500);
      int distance = readPing();
      delay(100);
      servo_motor.write(115);
      return distance;
    }

    int lookLeft(){
      Serial.print("Look Left");
      servo_motor.write(170);
      delay(500);
      int distance = readPing();
      delay(100);
      servo_motor.write(115);
      return distance;
      delay(100);
    }

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

    }

    void moveStop(){
      Serial.print("Stop");

      digitalWrite(in3, LOW);
      digitalWrite(in1, LOW);
      digitalWrite(in4, LOW);
      digitalWrite(in2, LOW);
    }

    void moveForward(){

      //if(!goesForward){

        //goesForward=true;

        Serial.print("Forward");

        digitalWrite(in1, HIGH);
        digitalWrite(in3, HIGH);

        digitalWrite(in2, LOW);
        digitalWrite(in4, LOW);

        analogWrite(enA, 250);
        analogWrite(enB, 250);

      //}
    }

    void moveBackward(){

      //goesForward=false;

      Serial.print("Backward");

      digitalWrite(in2, HIGH);
      digitalWrite(in4, HIGH);

      digitalWrite(in1, LOW);
      digitalWrite(in3, LOW);

    }

    void turnRight(){
      Serial.print("Right");

      digitalWrite(in1, HIGH);
      digitalWrite(in4, HIGH);

      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);

      delay(200);

      digitalWrite(in1, HIGH);
      digitalWrite(in3, HIGH);

      digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);

    }

    void turnLeft(){
      Serial.print("Left");

      digitalWrite(in2, HIGH);
      digitalWrite(in3, HIGH);

      digitalWrite(in1, LOW);
      digitalWrite(in4, LOW);

      delay(200);

      digitalWrite(in1, HIGH);
      digitalWrite(in3, HIGH);

      digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    }

body:
According to the [Servo reference page][1] it's not possible to use Servo library and PWM outputs on the pins 9 and 10.

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

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


message:
Turn on each of the LEDs in order, by setting the cycle delay to 100 milliseconds

I have a tutorial to finish and I don't know the code I have to use to make all (4 LEDs) to turn on in order. So this is my code and my simulation. Thanks in advance!

[![Figure 1][1]][1]

My Code:

    void setup() {
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(6, OUTPUT);
    }

    void loop() {
      digitalWrite(13, HIGH);
      digitalWrite(12, HIGH);
      digitalWrite(9, HIGH);
      digitalWrite(6, HIGH);
      delay(100); // Wait for 100 millisecond(s)

      digitalWrite(13, LOW);
      digitalWrite(12, LOW);
      digitalWrite(9, LOW);
      digitalWrite(6, LOW);
      delay(100); // Wait for 100 millisecond(s)
    }

EDITED:
I have to follow this one. I guess my simulator is correct.

[![Figure 2][2]][2]

  [1]: https://i.stack.imgur.com/3UGDd.jpg
  [2]: https://i.stack.imgur.com/OIQmy.jpg

body:
Your code switches them all ON and OFF simultaneously.

What I read from your question is you want to turn them on in order.
In this case, use a simple state diagram. This means you have to create variable (preferably an enumeration), e.g.:

    enum EState { FIRST_ON, SECOND_ON, THIRD_ON, FOURTH_ON };

    EState _state;

You can better use better names than FIRST_ON, ..., but I do not know what your lights mean.

In the setup, you initialize _state, e.g.

    _state = FIRST_ON;

Than in the loop you check and change the state:

    switch (_state)
    {
    case FIRST_ON:
        digitalWrite(13, HIGH); // Assuming this is the first light
        digitalWrite(12, LOW); // Put the others off
        ...
        ...
        _state = SECOND_ON; // Set the next state
        break;

    case SECOND_ON:
        digitalWrite(13, LOW); // Assuming this is the first light
        digitalWrite(12, HIGH); // Put the second LED on
        .. // Put the third/fourth off
        _state = THIRD_ON; // Set the next state
        break;

        // Do the same for THIRD_ON and FOURTH_ON

    default: // in all other cases
         break; // Should not happen
    }

    delay(100: // Wait for 100 milliseconds

Note, to not complicate the example, I've written out (mostly) the lines like you:

    digitalWrite(13, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(6, HIGH);

However, since these are almost copies (4 in the state diagram), it is best to write a separate function:

    void SwitchLedsOn(int led1State, int led2State, int led3State, int led4State)
    {
      digitalWrite(13, led1State);
      digitalWrite(12, led2State);
      digitalWrite(9, led3State);
      digitalWrite(6, led4State);
    }

Now you can use in the first state case:

    case FIRST_ON:
        SwitchLedsOn(HIGH, LOW, LOW, LOW); // Switch only first on
        break;

And do similar with the other states.


body:
add this to loop() end

     digitalWrite(13, HIGH);
     delay(100);
     digitalWrite(12, HIGH);
     delay(100);
     digitalWrite(9, HIGH);
     delay(100);


body:
I see in your second diagram that you are controlling the ground side of the LEDs. digitalWrite(PinNumber, HIGH) will turn an LED OFF, digitalWrite(PinNumber, LOW) will turn an LED ON. Using delay() in a sketch should be avoided.

    void setup(){
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(6, OUTPUT);
      digitalWrite(13, HIGH);
      digitalWrite(12, HIGH);
      digitalWrite(9, HIGH);
      digitalWrite(6, HIGH);
    }

    void loop(){
      digitalWrite(13, LOW);
      delay(100);
      digitalWrite(12, LOW);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      digitalWrite(6, LOW);
      delay(100);
      digitalWrite(13, HIGH);
      digitalWrite(12, HIGH);
      digitalWrite(9, HIGH);
      digitalWrite(6, HIGH);
      delay(100);
    }


message:
Designing around Output pin limitations

I'm new to Arduino and am working on a project with my son.  We are using the [LillyPad USB][1] board ([schematic][4]) to drive a bunch of [LEDs][2] ([LED Datasheet][5]).  Our project is based loosely off of the ['Turn Signal Biking Jacket'][3].

Our project calls for 7-11 LEDs in parallel on a single circuit.  In the 'Turn Signal' project the LEDs are driven off of a **pair** of output pins (1 HIGH and 1 LOW).  In a circuit that looks like this...

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/nTDrd.png)

<!-- End schematic -->

Is this ideal?  Would it make more sense to connect the LED-chain to Vcc and have the return line connected to a single output set to LOW (to turn on the lights)?

If we were to have 3-4 of these LED-chains on at once, do I have to be concerned with total draw on the microcontroller?

Help? Thoughts?

  [1]: http://www.pighixxx.com/test/portfolio-items/lilypad-usb/
  [2]: https://www.sparkfun.com/products/13902
  [3]: http://www.instructables.com/id/turn-signal-biking-jacket/
  [4]: https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf
  [5]: https://www.sparkfun.com/datasheets/DevTools/LilyPad/APT3216QWF-D.pdf

body:
If you know the forward voltage of the LEDs you can easily do some calculations.

For a typical red LED the forward voltage is around 2V.  Other colours vary.  So we can work out that, at 5V supply, each LED with its own 150R resistor, would take:

         V    5-2
    I = --- = --- = 20mA
         R    150

With 11 LEDs in parallel on at once that would be 0.02 * 11 = 220mA.

**That is far more than the 25mA an IO pin is able to supply, so you will damage the Arduino doing it like that.**

Instead you will need to switch each chain of LEDs with a transistor of some form.  I'd choose a logic-level N-channel MOSFET as a "low-side" switch:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/NnjzS.png)

<!-- End schematic -->

Now your Arduino doesn't care about the current - all it sees is the MOSFET.

If your LED forward voltages are less than 2.5V you can also chain them together to halve the current:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/CJGP1.png)

<!-- End schematic -->

Since the forward voltage is now double you use a smaller resistance to set the current (R=V/I, where V is 5-2Vf).


message:
Arduino with Ultrasonic sensor integrated but vibration motor not working according to the code

Here's my code after editing the measurement had error. Now the ultrasonic measurement is working but the vibration motor is not vibrating.

    #define trigPin1 8
    #define echoPin1 7
    #define motorPin1 13

    long duration, distance, UltraSensor;

    void setup()
    {
      Serial.begin(9600); // to use the serial monitor.
      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      //pinMode(motorPin1, OUTPUT);

    }

    void SonarSensor(int trigPin, int echoPin)
    {
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;
      delay(100);
    }

    void loop()
    {
      SonarSensor(trigPin1, echoPin1);
      UltraSensor = distance;
      Serial.print(distance); // print out the distance on Serial Monitor
      Serial.println("cm");
    //
      if (distance <= 60 && distance >= 45) // Checking the distance, you can change the value
      {
        digitalWrite(motorPin1, HIGH); // motor on
        delay(200);
        digitalWrite(motorPin1, LOW); // motor off
        delay(200);
      }
      else if(distance < 45 && distance >=30)
      {
        digitalWrite(motorPin1, HIGH); // when greater than 100cm
        delay(100);
        digitalWrite(motorPin1, LOW);
        delay(100);
      }
      else if(distance < 30)
      {
       digitalWrite(motorPin1, HIGH);
       delay(50);
       digitalWrite(motorPin1, LOW);
       delay(50);
      }
      else
      {
        digitalWrite(motorPin1, LOW);
      }
    }

body:
I think you have to uncomment the line that defines the motor as an output device.

 //pinMode(motorPin1, OUTPUT);


message:
Create a sketch that allows me to run a DC motor and LED sequence at the same time

I need a program created that will both run a DC motor and an LED sequence at the same time. The image is what the DC motor code should do.

    /*
    -==:: 3 Volts DC Motor Driver with Dual 555 Timer IC ::==-
      * Control Pin from 555 IC is needed to STOP the motor
      * Trigger Pin from 555 IC is needed to drive forward or backward
      * PWM on Trigger Pin is used to set the speed
      * Note : Forward and Backward is interchangeable via Motor connection.
     */

    int controlPin = 2; // 555 pinout 5
    int triggerPin = 3; // 555 pinout 2

    // the setup routine runs once when you press reset:

    void setup()  {
      pinMode(controlPin, OUTPUT);
      pinMode(triggerPin, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop()  {
    //  move FORWARD;
        digitalWrite(controlPin, HIGH);
        digitalWrite(triggerPin, HIGH); //full speed
        delay(3000);
    //    PWM testing to control motor speed
    //    analogWrite(triggerPin, 128+70); //minimum speed (128+70)
    //    delay(3000);

    //  STOP;
        digitalWrite(controlPin, LOW);
        digitalWrite(triggerPin, HIGH);
        delay(3000);

    //  move BACKWARD;
        digitalWrite(controlPin, HIGH);
        digitalWrite(triggerPin, LOW); //full speed
        delay(3000);

    //    PWM testing to control motor speed

    //    analogWrite(triggerPin, 128-70); //minimum speed (128-70)
    //    delay(3000);

    //  STOP;
        digitalWrite(controlPin, LOW);
        digitalWrite(triggerPin, HIGH);
        delay(3000);
    }

As for the LED code I have no idea. I just found this code on the web. The important thing is that the codes execute at the same time continuously.

body:
As stated in the comments, the Arduino can only execute 1 command at a time. There is no real multi-threading on this hardware. But you can to the work in sequence so fast, that you won't notice the difference with motors or LEDs. Here it is important to use non-blocking code, which doesn't block the execution of other code, when it is only waiting (the `delay()` function is just busy waiting).

For doing anything non-blocking (as setting LEDs or changing the state of a motor) you can use the `millis()` function. Refer to the `BlinkWithoutDelay` example from the Arduino IDE. For a very simple sequence (as blinking) you can directly use the code from the example. Basically you use a timestamp, which holds the last time, the blink code was executed. On every iteration of the `loop()` function you check, if a certain time has passed since the timestamp have been taken. If so, execute the code again and update the timestamp:

    unsigned long timestamp=0;
    void loop(){
      if(millis()-timestamp > 500){
        digitalWrite(led_pin,!digitalRead(led_pin));
        timestamp = millis();
      }
    }

This code would toggle the led_pin each 500ms.

For coding complex sequences you can make a state machine. For this you create a numeric state variable. In the `loop()` function you use a `switch`-`case`-statement, to execute the right code for each state of your programm. Also directly in the `loop()` function you change the state variable depending on the time through the above code. This would look somewhat like this:

    int state = 0;
    unsigned long timestamp = 0;
    void loop(){
      if(millis() - timestamp > 1000){
        state++;
        timestamp = millis();
      }

      switch(state){
        case 0:
          digitalWrite(led_pin,!digitalRead(led_pin));
          //  move FORWARD;
          digitalWrite(controlPin, HIGH);
          digitalWrite(triggerPin, HIGH); //full speed
          break;
        case 1:
        case 2:
          digitalWrite(led_pin,!digitalRead(led_pin));
          break;
        case 3:
          digitalWrite(led_pin,!digitalRead(led_pin));
          // stop moving
          digitalWrite(controlPin, LOW);
          digitalWrite(triggerPin, HIGH);
          break;
        case 4:
        case 5:
          digitalWrite(led_pin,!digitalRead(led_pin));
          break;
        case 6:
          digitalWrite(led_pin,!digitalRead(led_pin));
          //  move BACKWARD;
          digitalWrite(controlPin, HIGH);
          digitalWrite(triggerPin, LOW); //full speed
          break;
        case 7:
        case 8:
          digitalWrite(led_pin,!digitalRead(led_pin));
          break;
        case 9:
          digitalWrite(led_pin,!digitalRead(led_pin));
          // stop moving
          digitalWrite(controlPin, LOW);
          digitalWrite(triggerPin, HIGH);
          break;
        case 10:
        case 11:
          digitalWrite(led_pin,!digitalRead(led_pin));
          break;
        case 12:
          state = 0;
          break;
      }
    }

This code would toggle the led_pin every second and also doing the moto sequence `3s forward, 3s stop, 3s backwards, 3s stop`. This sequence loops forever.

When you only want to let the led blink continuously, it would be easier to exclude this part of the code from the state machine, but I wanted to show how this principle would work (for example if you want to include a complex blinking sequence).


message:
Array, hexadecimal and serial write

I am trying to write a pice of code which send to a receiver the frequency to listen.

As per its documentation, it should receive the following sequence:

> Example with **123.456** MHz
>
>  Command to send (frequency converted in 4 bytes, followed by 2 instruction bytes
>
> 0x**12** 0x**23** 0x**56** 0x00 0x01

To be able to memorize six frequencies, I fill an array:

    uint32_t mem_freq[6] = {
       0x121050,
       0x126500,
       0x120500,
       0x121700,
       0x121825,
       0x118700,
    };

My concern is that when I do :

    Serial.write(mem_freq[mem_index]);
    //Serial.write(0x00);
    //Serial.write(0x01);
Only 1 byte is sent, and it's hard to debug as the serial console displays only ascii characters.

When I use Serial.print instead, mem_freq[2] shows correctly 0x120500

After Majenko's answer, I tried this:

    Serial.print(0x123456 >> 16,HEX);
    Serial.print(0x123456 >> 8,HEX);
    Serial.print(0x123456,HEX);
    Serial.print(0x00,HEX);
    Serial.print(0x01,HEX);

And it outputs:

> 12123412345601

Is this normal ?

body:
You need to manually split your values into bytes. You can either do that by storing them as individual bytes (as shown by Ignacio), or by using bit shifting:

    Serial.write(mem_freq[mem_index] >> 16);
    Serial.write(mem_freq[mem_index] >> 8);
    Serial.write(mem_freq[mem_index]);

That sends the bits 16-23 (0x12) then bits 8-15 (0x10) followed by bits 0-7 (0x50).


body:
That's because you need to use an array of arrays, and send three bytes.

    uint32_t mem_freq[6][3] = {
      {0x12, 0x10, 0x50},
       ...
    };

     ...
      Serial.write(mem_freq[mem_index], 3);
     ...


message:
Changing outputs infinitely for no reason

Im a student and working on a arduino project for IoT competition and me and my team have built a house and I made this code below.
For some reason when I upload it to my Arduino MKR1000 it constantly turns D6 and D8 on and right after their both on it turns them off and so on for ever. I cant figure out why is it doing that because its only these 2 but not the rest of them.

Quick help would be appreciated.

Please note that I'm by any means a PRO at this but I do know my share about programming.

            //Definiramo ispis na serial port
    #define BLYNK_PRINT Serial

    //Ucitavamo biblioteke
    #include <SPI.h>
    #include <WiFi101.h>
    #include <BlynkSimpleMKR1000.h>

    // Autorizacijski kod za aplikaciju Blynk
    char auth[] = "Token";

    // Podatci za WiFi
    char ssid[] = "SSID";
    char pass[] = "PASSWORD";

    // ----- Inicializacija ledica -----
    const int ledBorDim = 2;
    const int ledKuh = 6;
    const int ledTrp = 7;
    const int ledKup = 8;
    const int lediceUlaz = 9;
    const int ledSpav = 10;

    // ----- Inicializacija gumbova -----
    const int gumbKuh = 11;
    const int gumbKup = 12;
    const int gumbSpav = 13;
    const int gumbBor = 14;

    // ----- Kontrolne varijable -----
    int stanjeLedKuh = 0;
    int stanjeLedKup = 0;
    int stanjeLedBor = 0;
    int stanjeLedSpav = 0;

    int gumbStanjeKuh = 0;
    int gumbStanjeSpav = 0;
    int gumbStanjeBor = 0;
    int gumbStanjeKup = 0;

    //Led kuhinja
    BLYNK_WRITE(V3)
    {
      int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
      Serial.print("ledKuh = "); //Ispis na ekran trenutno stanje
      Serial.println(pinValue);
      if (pinValue == 1)
      {
        digitalWrite(ledKuh, HIGH);
        stanjeLedKuh = 1;
      } if (pinValue == 0)
      {
        digitalWrite(ledKuh, LOW);
        stanjeLedKuh = 0;
      }
    }

    //Ledica za kupaonicu
    BLYNK_WRITE(V5)
    {
      int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
      Serial.print("ledKup = "); //Ispis na ekran trenutno stanje
      Serial.println(pinValue);
      if (pinValue == 1)
      {
        digitalWrite(ledKup, HIGH); //Promjena stanja na izlazu arduina
        stanjeLedKup = 1;
      } if (pinValue == 0)
      {
        digitalWrite(ledKup, LOW); //Promjena stanja na izlazu arduina
        stanjeLedKup = 0;
      }
    }

    //Paralelni spoj ledica na ulazu
    BLYNK_WRITE(V6)
    {
      int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
      Serial.print("lediceUlaz = "); //Ispis na ekran trenutno stanje
      Serial.println(pinValue);
      if (pinValue == 1)
      {
        digitalWrite(lediceUlaz, HIGH); //Promjena stanja na izlazu arduina
      } if (pinValue == 0)
      {
        digitalWrite(lediceUlaz, LOW); //Promjena stanja na izlazu arduina
      }
    }

    //Dimmer za Boravak
    BLYNK_WRITE(V1)
    {
      int pinValue = param.asInt(); //Ucitamo vrijednost
      Serial.print("Dimmer vrijednost: "); //Ispisemo na serial
      Serial.println(pinValue);
      analogWrite(ledBorDim, pinValue); //Na izlaz postavljamo vrijednost
      if (pinValue == 0)
      {
        Blynk.virtualWrite(V50, 1);
        stanjeLedBor = 0;
      } else if (pinValue > 0)
      {
        Blynk.virtualWrite(V50, 0);
        stanjeLedBor = 1;
      }
    }

    BLYNK_WRITE(V50)
    {
      int pinValue = param.asInt();
      if (pinValue == 1)
      {
        analogWrite(ledBorDim, 255);
        Blynk.virtualWrite(V1, 255);
        stanjeLedBor = 1;
      } if (pinValue == 0)
      {
        digitalWrite(ledBorDim, LOW);
        Blynk.virtualWrite(V1, 0);
        stanjeLedBor = 0;
      }
    }

    void gumbKuhinja()
    {
      gumbStanjeKuh = digitalRead(gumbKuh);
      if (gumbStanjeKuh == LOW)
      {
        if(stanjeLedKuh == 1)
        {
          digitalWrite(ledKuh, LOW);
          Blynk.virtualWrite(V3, 0);
          Serial.println("Ledica na V3/D6 je LOW");
          stanjeLedKuh = 0;

        } else if (stanjeLedKuh == 0)
        {
          digitalWrite(ledKuh, HIGH);
          Blynk.virtualWrite(V3, 1);
          Serial.println("Ledica na V3/D6 je HIGH");
          stanjeLedKuh = 1;

        }
        delay(500);
      }
    }

    void gumbKupaonica()
    {
      gumbStanjeKup = digitalRead(gumbKup);
      if (gumbStanjeKup == LOW)
      {
        if(stanjeLedKup == 1)
        {
          digitalWrite(ledKup, LOW);
          Blynk.virtualWrite(V5, 0);
          Serial.println("Ledica na V5/D8 je LOW");
          stanjeLedKup = 0;

        } else if (stanjeLedKup == 0)
        {
          digitalWrite(ledKup, HIGH);
          Blynk.virtualWrite(V5, 1);
          Serial.println("Ledica na V5/D8 je HIGH");
          stanjeLedKup = 1;
        }
        delay(500);
      }
    }

    void gumbSpavaca()
    {
      gumbStanjeSpav = digitalRead(gumbSpav);
      if (gumbStanjeSpav == LOW)
      {
        if(stanjeLedSpav == 1)
        {
          digitalWrite(ledSpav, LOW);
          Blynk.virtualWrite(V6, 0);
          Serial.println("Ledica na V6/D10 je LOW");
          stanjeLedSpav = 0;
        } else if (stanjeLedSpav == 0)
        {
          digitalWrite(ledSpav, HIGH);
          Blynk.virtualWrite(V6, 1);
          Serial.println("Ledica na V6/D10 je HIGH");
          stanjeLedSpav = 1;
        }
        delay(500);
      }
    }

    void gumbBoravak()
    {
      gumbStanjeBor = digitalRead(gumbBor);
      if (gumbStanjeBor == LOW)
      {
        if(stanjeLedBor == 1)
        {
          analogWrite(ledBorDim, 0);
          Blynk.virtualWrite(V1, 0);
          Serial.println("Ledica na V1/D2 je 0");
          stanjeLedBor = 0;
        } else if (stanjeLedBor == 0)
        {
          analogWrite(ledBorDim, 255);
          Blynk.virtualWrite(V1, 1);
          Serial.println("Ledica na V1/D2 je 255");
          stanjeLedBor = 1;
        }
        delay(500);
      }
    }

    void setup()
    {

      pinMode(ledBorDim, OUTPUT);
      pinMode(ledKuh, OUTPUT);
      pinMode(ledKup, OUTPUT);
      pinMode(lediceUlaz, OUTPUT);
      pinMode(ledSpav, OUTPUT);

      pinMode(gumbKuh, INPUT);
      pinMode(gumbKup, INPUT);
      pinMode(gumbSpav, INPUT);
      pinMode(gumbBor, INPUT);

      // Debug console
      Serial.begin(9600);
      //Povezivanje na WiFi i na aplikaciju Blynk
      Blynk.begin(auth, ssid, pass);
    }

    void loop()
    {
      Blynk.run();
      gumbKuhinja();
      gumbKupaonica();
      gumbSpavaca();
      gumbBoravak();
    }

Serial outpout:

    Ledica na V6/D10 je HIGH
    Ledica na V1/D2 je 255
    Ledica na V6/D10 je LOW
    Ledica na V1/D2 je 0
    Ledica na V6/D10 je HIGH
    Ledica na V1/D2 je 255
    Ledica na V6/D10 je LOW
    Ledica na V1/D2 je 0
    Ledica na V6/D10 je HIGH
    Ledica na V1/D2 je 255
    Ledica na V6/D10 je LOW
    Ledica na V1/D2 je 0
    Ledica na V6/D10 je HIGH
    Ledica na V1/D2 je 255

[![Breadboard schematic][1]][1]

Little label reading D14 means that that pin isnt suppoast to go to D4 but to D14 of the MKR1000 but since i dont have that board in the program im stuck with arduino Uno.<br>
Short explanation of the code...
We build a house out of styrofoam and placed 6 Led's around and almost all can be controlled from the Blynk app on my device. Also there are 4 buttons controlling 4 Led's. I have it setup so that when i press a button it changes the state of a particular LED and then sets the appropriate value on the app (If LED is on then set app value to 1). Pretty much that that about this code. Sorry if you cant understand but I had to write it in my native language since this is going to be a compettition and I was told that they wouldn't like if the code was in english for some reason.

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

body:
You had the following general problem:

The code you were using was configuring a pin into `INPUT` mode and reading the value on it. On this pin you conencted a button **without extern pullup or pulldown resistor**. This means that if the button is **not pressed**, it is not connected to anything and thus a **floating pin**. You cannot realibly read the value of the floating pin, as its voltage level may be on pretty much anything. It picks up interference like an antenna.

To solve this the button pin must be pulled to known voltage level if it is not connected (aka button is not pressed). We achieve this by using a resistor which is on one end connected to the button pin and on the other end connected to either VCC (+5V) or GND (0V). This has the effect that when the button is not pressed, the resistor pulls the voltage level of this pin up (if connected to VCC), or down if connected to GND.

We can either attach a resistor (e.g. 10K Ohm) in the circuit or active the internal (weak) pull-up resistors in our microcontroller. In Arduino, this is achieved by using `pinMode( buttonPin, INPUT_PULLUP)`.

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

In this circuit with `INPUT_PULLUP` on D2, we have:

* if the button is not pressed down, no connection to GND is made. The activated pull-up resistor will pull the voltage level of D2 to HIGH
* if the button is pressed down, it makes a connection to GND and overrides the pullup resistor. Pin D2 now reads LOW.

The logic can of course also be inverted -- you can use a PULLDOWN resistor and instead of connecting the button to GND on the other side connect it do 5V. This make the button read LOW when unpressed and HIGH pressed.

So the modified code must be changed from

      pinMode(gumbKuh, INPUT);
      pinMode(gumbKup, INPUT);
      pinMode(gumbSpav, INPUT);
      pinMode(gumbBor, INPUT);

to

      pinMode(gumbKuh, INPUT_PULLUP);
      pinMode(gumbKup, INPUT_PULLUP);
      pinMode(gumbSpav, INPUT_PULLUP);
      pinMode(gumbBor, INPUT_PULLUP);

and the logic which detects a button pressed must be changed to trigger an action when the pin is LOW (because a PULLUP is used, button reads LOW when pressed, HIGH else).

So from code of the form

    void gumbBoravak()
    {
      gumbStanjeBor = digitalRead(gumbBor);
      if (gumbStanjeBor == HIGH)
      {
        /* LED toggling and debouncing */
        delay(500);
      }
    }

To

    void gumbBoravak()
    {
      gumbStanjeBor = digitalRead(gumbBor);
      if (gumbStanjeBor == LOW)
      {
        /* LED toggling and debouncing */
        delay(500);
      }
    }

Also I recommend you to watch this youtube video to learn more about floating pins and pullup/pulldown resistors: [Pull up Resistor Tutorial][2]

  [1]: https://i.stack.imgur.com/yq9bD.png
  [2]: https://www.youtube.com/watch?v=wxjerCHCEMg


message:
A SoftwareSerial library for SAMD boards

So I've got three boards that I'm using to test this ([modified][1]) code:

    int sensor1Pin = A0;
    int sensor2Pin = A1;
    int sensor3Pin = A2;

    float sensors[] = {0,0,0};

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

    void loop(){

    sensors[0] = analogRead(sensor1Pin);
    sensors[1] = analogRead(sensor2Pin);
    sensors[2] = analogRead(sensor3Pin);

    Serial.print(sensors[0]);
    Serial.print(",");
    Serial.print(sensors[1]);
    Serial.print(",");
    Serial.println(sensors[1]);
    }

An Uno, a Feather M0, and an MKR1000.
The code will only work on the Uno because it's AVR-based whereas the other two boards are SAMD. When running on a feather, you get this error:

    /home/ghylama/Arduino/libraries/SoftwareSerial_master/SoftwareSerial.cpp:260:2: error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
         #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

However, the resolution of the Uno is too low for my purposes (its DAC has a resolution of 10, whereas I need a resolution of 12, minimum). Are there any libraries/workarounds that I can use for this purpose?

I've tried SoftwareSerial, NeoSWSerial, and [this one][2].

  [1]: http://www.hackerscapes.com/2014/11/how-to-save-data-from-arduino-to-a-csv-file-using-processing/
  [2]: https://github.com/arduino-org/Arduino/commit/1364019868e2ad044c87dd0f143052a92eebda98

body:
I will restate the problem as I have understood it: You want more Serial objects, aka more UART ports.

On your Adafruit Feather M0 with its SAMD21G18 Cortex-M0+ MCU, you have six SERCOM peripherals which you can arbitrarily configure to be a UART, I2C or SPI port. Each peripheral can have its connections routed to several different pins on the board. It is a very versatile piece of hardware.

Don't use a SoftwareSerial library made for AVR MCUs when you have the hardware. Adafruit's guide shows how you can reconfigure those SERCOMs to get additional `Serial` objects.

https://learn.adafruit.com/using-atsamd21-sercom-to-add-more-spi-i2c-serial-ports?view=all#creating-a-new-serial


message:
Interrupt crashes code when implemented

I've got a mini weather-station with a Davis Anemometer Vantage Pro that uses a reed switch to detect rotations. Using the rotations it then can convert to MPH. When using it alone, I have no problem measuring the wind speed. It measures the rotations over a 3 second period, and finds the average wind speed over those 3 seconds; however, when implemented into a group of code that also writes Temperature, Humidity, and Accelerometer data to an SD card, it crashes my code. For the sake of keeping this comment shorter, I am using code from http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed, and am implementing into the code below. It's a big chunk, but the important stuff should be the ISR_rotation and enabling interrupts at the start of the loop.

    // going to include all the libraries we need and definitions
    #include "SD.h" //sd card
    #include"SPI.h" //sd card
    #include "SHT1x.h" //temp/humid
    #include <Wire.h> //accelerometer
    #include <Adafruit_MMA8451.h> //accelerometer
    #include <Adafruit_Sensor.h> //accelerometer
    #include <math.h> //for wind speed
    //define pins and functions
    #define dataPin 6 //data pin for temp/humid
    #define sckPin 7 //serial clock for temp/humid
    #define WindSensorPin (2) //pin for wind sensor
    SHT1x th_sensor(dataPin, sckPin); //caling sht1x.h
    Adafruit_MMA8451 mma = Adafruit_MMA8451(); //calling the accelerometer library

    //WindSpeed stuff
    volatile unsigned long Rotations; // cup rotation counter used in interrupt routine
    volatile unsigned long ContactBounceTime=0; // Timer to avoid contact bounce in interrupt routine
    float WindSpeed; // speed miles per hour

    //SD card stuff
    const int chipSelect = 10;
    String dataString =""; // holds the data to be written to the SD card
    File sensorData;

    //Temp/Humid stuff
    float humid; // humidity value
    float temp_c; // temperature value

    void setup(){
      // Open serial communications
      Serial.begin(9600);
      Serial.print("Initializing SD card...");
      pinMode(chipSelect, OUTPUT); //sd writing
      pinMode(WindSensorPin, INPUT); //wind data
      attachInterrupt(digitalPinToInterrupt(WindSensorPin), isr_rotation, FALLING);//""wind interrupt""

      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
      // don't do anything more:
      return;
      }
      //accelerometer setup
      if (! mma.begin()) {
        Serial.println("Couldnt start");
        while (1);
      }
      Serial.println("MMA8451 found!");
      mma.setRange(MMA8451_RANGE_2_G);
      Serial.print("Range = "); Serial.print(2 << mma.getRange());
      Serial.println("G");
    }

    //
    void loop(){
      //This interrupt portion is for incrementing Rotations
      Rotations = -22; // Set Rotations count to 0 ready for calculations
      //interrupts(); // Enables interrupts
      //delay (3000); // Wait 3 seconds to average
      //noInterrupts(); // Disable interrupts
      //convert to mp/h using the formula V=P(2.25/T) where T is the delay in seconds
      //V = P(2.25/3) = P * 0.75
      //WindSpeed = Rotations * 0.75;

      //read the temperature/humidity sensor
      humid=th_sensor.readHumidity();
      temp_c=th_sensor.retrieveTemperatureC();

      //read the 'raw' data in 14-bit counts for accelerometer
      //mma.x for x direction, mma.y for y direction, mma.z for z direction
      mma.read();
      //Convert 14 bit to SI units (m/s^2)
      sensors_event_t event;
      mma.getEvent(&event);
      delay(3000);
      WindSpeed = Rotations * 0.75;
      //read the wind speed data

      //build the data string
      dataString = String(temp_c) + "," + String(humid) + "," + String(event.acceleration.x) + "," + String(event.acceleration.y) + "," + String(event.acceleration.z);// + "," + String(WindSpeed); //to CSV
      saveData(); // save to SD card
      //for testing with serial monitor to see if we are obtaining correct values
      Serial.print("Temperature: ");
      Serial.print(temp_c);
      Serial.print(", Humidity: ");
      Serial.println(humid);
      Serial.print(" X: ");
      Serial.print(event.acceleration.x);
      Serial.print(" Y: ");
      Serial.print(event.acceleration.y);
      Serial.print(" Z: ");
      Serial.println(event.acceleration.z);
      Serial.print("Rotations: ");
      Serial.println(Rotations);
      delay(3000);
    }

    //
    void saveData(){
    if(SD.exists("data.csv")){ // check the card is still there
      // now append new data file
      sensorData = SD.open("data.csv", FILE_WRITE);
      Serial.println("Data written");
        if (sensorData){
        sensorData.println(dataString);
        sensorData.close(); // close the file
        }
      }
    else{
      Serial.println("Error writing to file/Card removed");
      }
    }

    // This is the function that the interrupt calls to increment the rotation count
    void isr_rotation () {
    if ((millis() - ContactBounceTime) > 15 ) { // debounce the switch contact.
      Rotations++;
      ContactBounceTime = millis();
      }
    }

When any wind information and interrupts are commented out, I have no problem at all with writing to SD card and getting the correct data from the accelerometer and sht10. I must be doing something wrong with the interrupt, but I'm not sure. I've read to not include any serial prints, delays, keep em short, etc. and it works alone. It crashes right after running the setup (before it can serial print any information), which makes me believe it's something with the interrupt. I've tried commenting out noInterrupts() and it returns trash data for rotations, so that's not usable. In case it's important, the memory usage is in the 60% range, so that shouldn't be relevant.

Thanks for any help or advice you have.

EDIT: After totally removing the interrupt() and noInterrupts() portion, I get trash data for rotations that changes depending on the debounce timing (higher debounce limit=fewer triggered rotations). I seem to get a constant Rotations range of 20-23 that does pretty accurately depict how many rotations I add (for example spinning 8 times gets me around 30). I also prettied it up the code a little bit.

body:
Your basic flaw is that you turn interrupts off (prior to commenting those lines out), and then attempt to use the SD card which almost certainly will want to use interrupts.

Your technique of turning interrupts on, and then doing a big delay, is not one I like. I comment on that sort of thing in [my page about interrupts](http://www.gammon.com.au/interrupts), in particular in [reply #10](http://www.gammon.com.au/forum/?id=11488&reply=10#reply10). The essence of that reply is:

---

## Timing an interval

I have seen example code suggesting you count things for a second by turning interrupts off for a second and then on again. I don't recommend this, because for one thing, you can't do serial prints if interrupts are off.

### Example (not recommended):

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

    volatile unsigned long events;
    const unsigned long INTERVAL = 1000;  // 1 second

    void eventISR ()
      {
      events++;
      }   // end of eventISR

    void setup ()
      {
      Serial.begin(115200);
      attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
      }   // end of setup

    void loop ()
      {
      events = 0;       // reset counter
      interrupts ();    // allow interrupts
      delay (INTERVAL); // wait desired time
      noInterrupts();   // stop interrupts

      Serial.print ("I counted ");
      Serial.println (events);
      }  // end of loop

(This is effectively what your code does).

That may work for simple situations, but turning interrupts off means that the Serial prints won't work until they are turned on again (which they may not be in a more complex sketch).

It is better to use the millis() result and just detect when the time limit is up.

### Improved sketch:

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

    volatile bool counting;
    volatile unsigned long events;

    unsigned long startTime;
    const unsigned long INTERVAL = 1000;  // 1 second

    void eventISR ()
      {
      if (counting)
        events++;
      }  // end of eventISR

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
      }  // end of setup

    void showResults ()
      {
      Serial.print ("I counted ");
      Serial.println (events);
      }  // end of showResults

    void loop ()
      {
      if (counting)
        {
        // is time up?
        if (millis () - startTime < INTERVAL)
          return;
        counting = false;
        showResults ();
        }  // end of if

      noInterrupts ();
      events = 0;
      startTime = millis ();
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      counting = true;
      interrupts ();
      }  // end of loop

In loop() here we wait for the interval (1 second in this case) to be up, otherwise we return, effectively doing nothing. You could of course do other things instead of just returning.

If the time is up we display the count.

If counting is not currently active (and presuming we want it to be active) we remember the start time, reset the counter to zero, and let it start counting up.

That code seemed to work OK up to 100 kHz, although the counts were getting a bit inaccurate. You can do more precise timings by using the hardware counters / timers. Details at [my Timers and counters page](http://www.gammon.com.au/timers).


message:
simultaneously read 16 hall sensor and maximum current allowed by Arduino

My question is about maximum current allowed by Arduino.

I know it's 200mA in Arduino and 40mA in every pin (lower in arduino mini). Just wondering if simultaneously read 16 hall sensor (than can be all activated at the same time) is too much.
My calculation is 200 / 16 = 12.5 mA máximum current I can drive to a pin from a sensor, but it's enough to read the sensor? Specs from 3144 hall sensor says it outputs 25mA when activated. Can I put a resistante between output's sensor and Arduino pin?

I'm planning to use Arduino mini and sensor hall 3144.

Sorry for my english, and thanks in advance!

p.s: The original idea was read all 64 sensors with one Arduino, but breaking it into several arduinos is easiest as my electronics knowledge is seriously limited :)

body:
Since this sensor doesn't need to be driven directly from a pin, the maximum current for one pin is not important here. The hall sensor uses two of it's pins as supply voltage. The output pin is an Open-Collector pin. So it will be connected to GND trough a transistor depending on the magnetic field. If you use an external pullup resistor (as connection between OUTPUT and positive supply voltage), you get somewhat like a voltage divider. Since the hall sensor seems to behave as a switch, there will only be two possible states. When the magnetic field is low, the transistor doesn't let the current flow. The pullup resistor can pull the pin to the positive supply voltage (5V -> 1 as digital value). If the magnetic field is high enough, the transistor will open the connection to GND. Now a maximum of 25mA of current can flow throw it to GND. The voltage of the pin is now determined by the voltage divider the transistor and the pullup resistor build. You can calculate the virtual "resistance" of the transistor in this state with Ohm's law

> R = U/I

(R is resistance, U is voltage and I is current) With 5V supply voltage and 25mA current you get a resistance of 200 Ohm. Since you just want to use the sensor as a switch, you only have to ensure, that the pin cannot be pulled to a significantly greater value than 0V. **So grab a resistor, that is significantly higher than 200 Ohm and use it as pullup resistor.** Keep in mind, that you always must use the pullup resistor with the supply voltage, that runs the Arduino. A higher voltage can fry the Arduinos components.

Then you connect this pin to a digital pin of the Arduino, which you configure as INPUT. In this state the pin has a high impedance, so that the current, that flows into it, is really small (it CAN source 25mA, but it does not have to. The current depends on your external circuit). So this isn't something you have to bother about.

This leaves us with the supply current, that the sensor needs to work. In the datasheet it says, that at a supply voltage of 8V the supply current is at maximum 9mA. For 16 sensors this gives us a total of 144mA, which is still comfortable inside the 200mA the Arduino can provide. So you should be able to drive all of them safely.

That said, if you want to add more components, that draw current, it might be better so source the current you need not over the Arduino but directly from your power source (if this is possible for you). Depending on the current you may need, it can also be good, to get an external voltage regulator (if your supply doesn't directly give you 5V), that can provide enough current.


body:
As Gerben mentioned in a comment, you could set up a [matrix of the sensors](https://nerdclub-uk.blogspot.com.au/2015/08/multiplexing-array-of-hall-sensor-inputs.html).

Since the 3144 effectively is a switch to ground (when the magnet comes close it pulls the data line low) you would wire them up like a keypad matrix. I recently did [an answer](https://arduino.stackexchange.com/a/49888/10794) about a keypad matrix. If you wanted 64 sensors you would only need 16 Arduino pins (8 for the rows and 8 for the columns).

The keypad matrix I described already drives the rows low, so that is the right polarity for the sensors. You would just need a pull-up for the columns, say 10k. The sensor then just has to sink 5/10000 amps (0.5 mA) which is well within spec.

The supply voltage to the sensors can be provided independently of the Arduino (however 5V would be reasonable). Since the sensors apparently usually consume 4.4 mA, then 64 would consume 282 mA, which is probably quite reasonable to supply from the Arduino 5V pin.

The diodes mentioned in the keypad matrix answer are probably a sensible precaution if you are likely to have more than one sensor activated at once.


message:
Electric meter pulse counting using LLC

I am trying to create an electric meter reading setup for Arduino, and I have been searching for it and almost every posts available is using LDR sensor.

http://www.reuk.co.uk/wordpress/solar/flashing-led-on-electricity-meter/
https://jonarcher.info/2014/03/arduino-based-electricity-monitor/

And since it is using LDR, the system should be kept in a dark area, or that the LDR is taped to the flashing LED so that no other light source will interfere the sensor.

But I wanted to have a different setup, and what I am thinking is:

1. inside the electric meter, tap into the blinking LED
2. From the LED, connect it to an LLC (https://www.sparkfun.com/products/12009)
3. From the LLC, connect it to the Arduino
4. Arduino will sense/detect the pulse of the LED.

Is this a possible setup? Will it not fry the Arduino or the LLC? Will Arduino be able to detect the pulse?

If not, are there any other options? can I use discrete components instead? (I will be the one creating the circuit connection for the LED and Arduino, using resistor, diodes, etc.)

body:
When you aren't using the same power supply as the product you are interfacing with, it's usually a good idea of have some form of electrical isolation, which is what the LDR+LED was doing -- there was no way for a voltage spike to reach the Arduino, nor was there any way that different "ground" potentials could cause problems. (Imagine if the ground reference for the meter was floating at a high voltage with respect to earth-ground, but your Arduino power supply's negative line was referenced to earth ground.)

A good way to get electrical isolation is with an [opto-coupler][1], also called an opto-isolator, which is essentially an LED and a photo-transistor inside the same package. The LED side is completely electrically isolated from the photo-transistor side, but light can pass from the LED to the phototransistor.

You would connect the opto-coupler so that current passes through the LED side when the pulse happens, and with a pull-up or pull-down resistor on the phototransistor side, which gets pulled down or up (depending on the circuit) when the LED is on.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/iCJ4v.png)

<!-- End schematic -->

  [1]: https://en.wikipedia.org/wiki/Opto-isolator


message:
Pro Mini atmega168 voltage woes

I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?

I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?

body: Bypass the regulator, and connect the battery directly to the VCC pin. However, running at 16Mhz requires at least 3.8 Volts, according to the datasheet. Lower voltages may work, but aren't guarantied.


message:
RGB LED strip green LEDs cannot be dimmed to less than 50%

I have an RGB LED strip which I want to control with my arduino uno, everything works fine, except for the green LEDs.
They cannot be dimmed to less than 50%, because they will simply turn off.

I have this test code in my setup:

    Serial.write("dimming green test started");
    for(int x = 255; x > 0; x--) {
        analogWrite(greenPin,x);
        Serial.write(" - g:");
        Serial.print(x);
        delay(6);
      }
      Serial.println();
      Serial.write("dimming green test done");
      Serial.println();

And the green LEDs are fully turned on in the beginning, and at about 127, the just turn off. All the other colors are perfectly dimmable.
I checked the energy usage, and green does only use a little more than the other colors, so that's not the problem.

**Are green LEDs not dimmable? Or is this just an optical effect?**

(I use a setup very similar to this one with one difference: but only use 5V, because my LED strip only needs 5V) [![setup][1]][1]

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

body:
`analogWrite` only works on pins that support PWM. Those are the pins with the `~` next to it.

On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.


message:
Wire.h library works on Uno but won't compile for ATtiny85

**TL;DR:**

 - Arduinos are current hungry so I want to switch my microcontroller
 - code works on Uno, I change upload to ATtiny85, code doesn't compile
 - Wire.h breaks at the TWBR input
 - Should I keep trying to fix this or should I just use ATmega328P without the Arduino?

---

---

---

So I'm working on a project where I send data from an IMU (MPU6050) to a phone using Bluetooth LE (HC08) with a bit of signal filtering by a microcontroller in between. I've been using Pro Minis but the amperage consumption by these boards is ridiculous, so I'm trying to replace these with some ATtiny85's that I have laying around.

The problem is, the Wire.h library won't compile for the ATtiny85. It's also worth noting that the default MPU6050 code mandates use of an interrupt pin, which ATtiny's don't have, so I've modified the code to work without it (I'm not sure if that's part of the problem).

    #include <SoftwareSerial.h>
    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #include "Wire.h"

    //==============================================================================
    // MPU6050 initialization code
    MPU6050 mpu;
    uint16_t packetSize;
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    Quaternion q;
    VectorInt16 aa;
    VectorInt16 aaReal;
    VectorInt16 aaWorld;
    VectorFloat gravity;

    //==============================================================================
    // microcontroller initialization code
    int avg_counter = 0;
    int pts_to_avg = 15;
    int * x_array = (int*)malloc(sizeof(int) * 25);
    int * y_array = (int*)malloc(sizeof(int) * 25);
    int * z_array = (int*)malloc(sizeof(int) * 25);

    //==============================================================================
    // HC-08 initialization code
    const byte rxPin = 3;
    const byte txPin = 4;
    SoftwareSerial bleSerial(rxPin, txPin);

    //==============================================================================
    void setup() {
      // MPU6050 setup code ========================================================
      Wire.begin();
      TWBR = 24;
      mpu.initialize();
      mpu.dmpInitialize();
      mpu.setXAccelOffset(-1343);
      mpu.setYAccelOffset(-1155);
      mpu.setZAccelOffset(1033);
      mpu.setXGyroOffset(19);
      mpu.setYGyroOffset(-27);
      mpu.setZGyroOffset(16);
      mpu.setDMPEnabled(true);
      packetSize = mpu.dmpGetFIFOPacketSize();
      fifoCount = mpu.getFIFOCount();

      // microcontroller setup code ================================================

      // HC-08 setup code ==========================================================
      // make sure your HC-08 is set to the same baud as below!
      bleSerial.begin(19200);
      delay(100);
    }

    //==============================================================================
    void loop() {
      while(fifoCount < packetSize){
        fifoCount = mpu.getFIFOCount();
      }

      if(fifoCount == 1024){
        mpu.resetFIFO();
        bleSerial.println(F("FIFO overflow!"));
      }else{
        if(fifoCount % packetSize != 0){
          mpu.resetFIFO();
        }else{
          while(fifoCount >= packetSize){
            mpu.getFIFOBytes(fifoBuffer, packetSize);
            fifoCount -= packetSize;
          }

          mpu.dmpGetQuaternion(&q,fifoBuffer);
          mpu.dmpGetAccel(&aa, fifoBuffer);
          mpu.dmpGetGravity(&gravity, &q);
          mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
          mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);

          // points are averaged to keep the baud low w/o FIFO overflow
          if(avg_counter <= pts_to_avg){
            // add live data to this array and hold onto it to be averaged
            x_array[avg_counter] = aaWorld.x;
            y_array[avg_counter] = aaWorld.y;
            z_array[avg_counter] = aaWorld.z;
            avg_counter++;
          }else{
            // average data from the array
            int x_average=0;
            int y_average=0;
            int z_average=0;

            // sums the data in #_average
            for(int i = 0; i < avg_counter; i++){
              x_average += x_array[i];
              y_average += y_array[i];
              z_average += z_array[i];
            }

            // divides by avg_counter (which should == pts_to_avg)
            x_average /= avg_counter;
            y_average /= avg_counter;
            z_average /= avg_counter;

            // resets counter so the array data can be overwritten with future data
            avg_counter = 0;

            // prints data to serial port (if BT is connected, sends via BT)
            bleSerial.print(x_average);
            bleSerial.print(",");
            bleSerial.print(y_average);
            bleSerial.print(",");
            bleSerial.println(z_average);
          }
        }
      }
    }

When using Arduino as ISP, selecting "Board: ATtiny25/45/85", "Processor: ATtiny85", & "Clock: Internal 1MHz", the following error showed up:

    exit status 1
    'TWBR' was not declared in this scope

this error did *not* occur when compiling for the Uno. If you comment out TWBR, then you get an enormous error message (I'll only paste a bit):

    In file included from c:\users\auphynne\appdata\local\arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2\avr\include\avr\io.h:99:0,

                     from C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:25:

    C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:15: error: 'TWINT' undeclared (first use in this function)

        TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                   ^

    C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:28: error: 'TWSTA' undeclared (first use in this function)

        TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                                ^

    C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:40: error: 'TWEN' undeclared (first use in this function)

        TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                                            ^

    exit status 1
    Error compiling for board ATtiny25/45/85.

To try to remedy this, I went into

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c

and hardcoded this line from

    // initialize twi prescaler and bit rate
    cbi(TWSR, TWPS0);
    cbi(TWSR, TWPS1);
    TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

to

    // initialize twi prescaler and bit rate
    cbi(TWSR, TWPS0);
    cbi(TWSR, TWPS1);
    TWBR = 24;

and I still got the same gruesome error message.

Pins are what you'd expect, 5v power to both modules and grounded, plus:

 - Uno D4 -> HC08 RXD
 - Uno D3 -> HC08 TXD
 - Uno SCL -> MPU6050 SCL
 - Uno SDA -> MPU6050 SDA

(again note that the interrupt pin is not used, and this worked quite well when building on the Uno! I got data on my phone's BT serial terminal app so that doesn't seem to be the problem)

**Any ideas on how I can get Wire.h to compile on my ATtiny85?**

**Or... should I just abort and go with the ATmega328P** (without the accompanying Uno) since it comes in the Quad Flat SMD package? (footprint matters for the long term)

body:
You get this error, because the ATTiny85 doesn't have full I2C hardware. It only as an USI (Universal Serial Interface). This can be utilized to do the rest of the I2C protocol via software. There are some libraries out there to do that, most of them are somewhat named `TinyWire`. There were dedicated libraries for master and slave operation named `TinyWireM` and `TinyWireS`. And I composed one library with both functionalities (and some more) in [TinyWire][1]. The last one - I think - is not usable for you, because the`SoftwareSerial` library needs the PinChangeInterrupt to work, but TinyWire uses it for detecting stop conditions on the I2C bus.

So for your case you can use the [TinyWireM][2] library. Note that the master operations need exact timing. Using to much interrupts in this time can cause problems in transmission. Test it and disable interrupts, if it is needed.

  [1]: https://github.com/lucullusTheOnly/TinyWire
  [2]: https://github.com/adafruit/TinyWireM


body:
If you want Wire.h library to work on attiny85 use:

https://github.com/SpenceKonde/ATTinyCore

I did and it compiles.


message:
DS18B20 sending variable via Enthernet shield

I am trying to send temperature read from DS18B20 to a web server. I know two things: to read a temperature, and to send something to web server. What I don't know is how to convert float that temperature reading function is giving to me to string that I need to send to the server.

I am reading temperature with OneWire and DallasTemperature libraries (just a standard sketch ending with:

    sensors.requestTemperatures();
    Serial.println(sensors.getTempCByIndex(0));//sensors.getTempCBy... returns float, from my understanding

I am sending data via ethernet shield, and important part is:

     client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + String(sensors.getTempCByIndex(0)) + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret=111 HTTP/1.1");

I know that the problem is that String(sensors.getTempCByIndex(0)) is not converting to right value. Arduino just stops working there, if that makes sense. At least serial communication stops working, since I don't see any more output...

Basically, TL:DR, I think that the question is how to convert float to string in Arduino? I have read a million topics on this but still cant figure it out, especially sicne it works for temp2 and humidity in example above.

body:
> Having re-read the question just before posting this answer, I find it odd that the DHT temp and humidity (also floats) work for you - how odd

Use `dtostrf`

    char tStr[9] = { 0 }; // buffer to store the string - length 9, because at most you need 8 chars "-23.5678" , plus null terminator
    dtostrf(sensors.getTempCByIndex(0), 7, 3, tStr)

Note: `dtostrf` returns char pointer to `tStr`

The 7, 3 is ... 7 = total length of string, 3 = number of decimal digits - So depending on your resolution, you can change those values

    Resolution     Arguments to dtostrf
     9             5, 1                  -nn.n
    10             6, 2                  -nn.nn
    11             7, 3                  -nn.nnn
    12             8, 4                  -nn.nnnn

Of course, you can use any arguments for any resolution, the table just shows what you would need if you wanted to show the exact data coming in

For example, I use resolution 12, but I'm not really interested in displaying more than tenths of a degree - so I use `5,1` for the format


message:
Keypad password check issue

I am working on a school project, basically I have to create a lock system that opens a fictive gate when the correct code is entered. We have been asked to simulate our system before actually building it. So, I made the following circuit in Proteus(Labcenter Electronics' simulation software):

[![][1]][1]

Here's what my system should do: A variable contains the correct code and the user must type a code on the keypad, and if it is correct, a green LED turns on and the LCD screen displays "Acces Granted!" if the code is wrong, the screen will display "Access refused!". It's a basic system, but I'm trying to make it as simple/short as possible(I have to explain it in an oral presentation, so the simpler the better) and for some reason, I can't get my code to work. Ideally, I'd like to have the LCD display a * for each character typed, liked on a real security system, but I haven't managed to do that either. I've been working on it for hours, trying different variants and etc.. but nothing seems to work the way I want to. BTW, my circuit works perfectly fine and the initialisation part of my code is therefore correct as well. Can anyone help me figure out what's wrong with my code and how I can make it better?

Here's my code so far:

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

    #include <LiquidCrystal.h>
    #include <Keypad.h>

    //define LED pins
    #define redLED 11
    #define greenLED 10

    String codeSerrure = "87362";   //correct code that opens the imaginative gate
    String enteredCode = "";
    int keyPressed;

    const byte rows = 4;
    const byte cols = 3;

    char touches_digicode [rows] [cols] = {

      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins [rows] = {25, 26, 27, 28};
    byte colPins [cols] = {24, 23, 22};

    Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup(){
      lcd.begin(16, 2);
      pinMode(redLED, OUTPUT);
      pinMode(greenLED, OUTPUT);
      digitalWrite(redLED, HIGH);
    }

    void loop(){
      lcd.setCursor(0,0);
      lcd.print(" Entrez le code");

      keyPressed = leDigicode.getKey();
      enteredCode += String(keyPressed);
      if(enteredCode.length() >= 5){
        if(enteredCode == codeSerrure){
          digitalWrite(greenLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces autorise!");
          delay(4000);
          digitalWrite(greenLED, LOW);
          digitalWrite(redLED, HIGH);
          enteredCode = "";
        }
        else{
          digitalWrite(redLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces refuse!");
          delay(4000);
          enteredCode = "";
        }
      }
      if(keyPressed == "#"){
        lcd.clear();
        enteredCode = "";
      }
    }

The problem is that when I run this code in the simulation software, the LCD displays "Acces refuse!" and the red LED is on. No matter what keys I press (on the keypad) nothing happens. So the problem is that my code jumps straight to the else statement, inferring that the password typed is wrong (although no password was actually typed). I think the error is in here:

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

    keyPressed = leDigicode.getKey();
      enteredCode += String(keyPressed);
      if(enteredCode.length() >= 5){
        if(enteredCode == codeSerrure){

Btw, forgive the french words, I am french. Also, I forgot to say, the # key should, clear the entered code. Any explanations, code samples or links would help.

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

body:
The `getKey()` Funktion returns the define `NO_KEY` if no key was pressed, which is set in Keys.h as the NULL char (char with the value 0). In every loop cycle you are adding one character with value 0 to your string. But all functions, that handle strings, will stop, when they find a character with value 0 (it is the delimiter of C strings). Also a string with many NULL chars in it will not be matched to a string only consisting oft digits.

So you should check the return value of getKey for the NO_KEY define:

    if(keyPressed != NO_KEY){
      enteredCode += String(keyPressed);
    }

This avoids adding NULL chars to your string.


body:
After reading all of your comments, I made some changes to my code and I was able to figure out a few other things that weren't working before. I think, because of the way I had coded my password checking function it made all the rest more complicated. I have also implemented the erase key feature, so a press of the * or # keys, erase the entered code. I still need to implement the feature that displays a * on the lcd each time the user presses a key, but I a not sure of what way to do this. Anyways, here's my working code if you're interested:

    #include <LiquidCrystal.h>
    #include <Keypad.h>

    //define LED pins
    #define redLED 11
    #define greenLED 10

    String codeSerrure = "87362";
    String enteredCode = "";
    char keyPressed;

    const byte rows = 4;
    const byte cols = 3;

    char touches_digicode [rows] [cols] = {

      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins [rows] = {25, 26, 27, 28};
    byte colPins [cols] = {24, 23, 22};

    Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup(){
      lcd.begin(16, 2);
      pinMode(redLED, OUTPUT);
      pinMode(greenLED, OUTPUT);
      digitalWrite(redLED, HIGH);
    }

    void loop(){
      lcd.setCursor(0,0);
      lcd.print(" Entrez le code");

      keyPressed = leDigicode.getKey();
      if(keyPressed != NO_KEY){
        if(keyPressed == 0x23 || keyPressed == 0x2A){
          lcd.clear();
          enteredCode = "";
        }
        else{
          enteredCode += String(keyPressed);
        }
      }

      if(enteredCode == codeSerrure){
          digitalWrite(greenLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces autorise!");
          delay(4000);
          digitalWrite(greenLED, LOW);
          digitalWrite(redLED, HIGH);
          enteredCode = "";
          lcd.clear();
      }
      else if(enteredCode.length() >= 5){
          digitalWrite(redLED, HIGH);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("  Acces refuse!");
          delay(4000);
          enteredCode = "";
          lcd.clear();
      }
    }

Thank you to everyone for the help (I'm a noobie)! I'm aware that my code is problably not the best way to do what I'm trying to do, so any suggestions and upgrades to the code you could give me are very welcome. Thanks again!

**The final version of my code with all the features working can be found in [this thread][1], for those interested.**

  [1]: https://stackoverflow.com/questions/49016981/arduino-mega2560-keypad-password-check/49048637#49048637


message:
Does the position in which you mount an IMU matter?

Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.

When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project?  I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?

For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?

body:
If the axes of measurement don't line up with the axes of motion, then comparing the IMU outputs to vehicle-relative (VR) coordinates will require some vector arithmetic to convert one to the other. It can be done, but requires some engineering time to code it and processor time to run.

It wasn't clear to me at a quick read whether your chosen IMU can do the coordinate translation itself, or your MCU has to do it. In either case, the computation will always reduce the accuracy of the original data, maybe a lot, maybe inconsequential, but expect some degradation.

Bottom line is: if you can line them up, things get simpler.


message:
sending 16 bit command via SPI to a NCV7719 (half bridge)

I am trying to send a 16 bit command to a Half bridge (data sheet here http://www.onsemi.com/pub/Collateral/NCV7719-D.PDF) to open one of the transistors to turn on an LED. at the bottom of the data sheet (page 13) it says which bit needs to be a 1 or a 0 in order to activate the half bridge. This is the code I wrote but it isn't work (I'm assuming I'm not sending the 16 bits properly). Can someone figure out why this isn't working?

    #include <SPI.h>

    void setup() {
      // put your setup code here, to run once:
      pinMode(10,OUTPUT);
      pinMode(8,OUTPUT);
      digitalWrite(8,HIGH);
      SPI.begin();

    }

    void loop() {
      // put your main code here, to run repeatedly:

      //pulling pin low to decide to write to device
      digitalWrite(10,LOW);

      //function to send information
      //truning on half bridge 4
      SPI.transfer(0000010000000000);
    delay(500);
      //finish transfering data
      digitalWrite(10,HIGH);

    }

body:
SPI writes in 8-bit bytes. So the writes need to look like this:

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

      SPI.transfer(0b00000100);  // first byte
      SPI.transfer(0b00000000);  // second byte

Possibly in the other order depending on which byte the device expects first.


message:
Trigger external interrupt on Arduino Uno R3 with an LED and a button

I want to cause the external interrupt on digital pin 2 (`PD2` on ATmega328). I have chosen *any logic change* mode. Here is my code:

    void setup()
    {
        DDRD &= ~( 1 << DDD2 );//PD2 on input mode
        EICRA |= ( 1 << ISC00 );//any logic change
        PORTD |= ( 1 << PORTD2 );//pull-up enable
        EIMSK |= ( 1 << INT0 );//turns on INT0

        DDRD |= ( 1 << DDD5 );//PD5 on output mode
        PORTD |= ( 1 << PORTD5 );//turn on PD5

        SREG |= ( 1 << 7 );//global interrupts enabled
    }

    void loop()
    {

    }

    ISR( INT0_vect )
    {
        if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
        {
             PORTD &= ~( 1 << PORTD5 );//turn off led
        }
        //and vice-versa
        else
        {
             PORTD |= ( 1 << PORTD5 );
        }
    }

Here is how I connect things.

*NOTE:* I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

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

The problem is when I push the button no interrupt occurs. What am I doing wrong?

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

body:
Pin 2 is pulled up by internal R then pulled up when button is pressed?
Connect button to GND.


message:
Stop Arduino Timer after some seconds

I'm building a basic program that when a button is pressed, a buzzer comes on.

I would like however to make it so that the buzzer stops after a short period of time (e.g. 5-7 seconds).

Here is the code I have so far which is pretty basic I know forgive me but I have no clue on how to go forward.

    // Setting The Pin Numbers
    const int touchsensor = 2;     // the number of the touchsensor pin
    const int buzzer =  4;         // the number of the LED pin

    // variables:
    int touchsensorState = 0;      // variable for reading the touchsensor status

    void setup() {
      // initialize the buzzer as an output:
      pinMode(buzzer, OUTPUT);
      // initialize the touchsensor as an input:
      pinMode(touchsensor, INPUT);
    }

    void loop() {
      // read state of the pushbutton value:
      touchsensorState = digitalRead(touchsensor);

      // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
      if (touchsensorState == HIGH) {
        // buzzer will emit sound:
        digitalWrite(buzzer, HIGH);
      } else {
        // buzzer will not sound:
        digitalWrite(buzzer, LOW);
      }
    }

body:
You can time this with the `millis()` function. Refer to the BlinkWithoutDelay example from the Arduino IDE.

Then you set a timestamp, when the button is pressed:

<!-- language: c -->

    if(touchsensorState == HIGH) timestamp = millis();

And then you are checking this timestamp against the current time:

<!-- language: c -->

    if(millis() - timestamp > duration){
      digitalWrite(buzzer, HIGH);
    } else {
      digitalWrite(buzzer, LOW);
    }

`duration` is the timespan during which the buzzer should stay on after the button was released. If you want to turn it of, regardless of the button state, you can add a boolean flag to your if-statement, to set the timestamp only, when the button was pressed first:

<!-- language: c -->

    if(!button_pressed && touchsensorState == HIGH){
      timestamp = millis();
      button_pressed = true;
    }

In this case you have to reset the `button_pressed` variable to `false`, when you are turning of the buzzer in the `millis()`-else-statement


body:
You set a `timestamp = millis()` when the button is pushed and then you disable the buzzer only when `millis() - timestamp > timeout`

    if (touchsensorState == HIGH) {
        // buzzer will emit sound:
        digitalWrite(buzzer, HIGH);
        timestamp = millis();
    }
    if(millis() - timestamp > timeout) {
        // buzzer will not sound:
        digitalWrite(buzzer, LOW);
    }


message:
MPU6500 via SPI

I'm trying to communicate with an MPU6500 sensor via SPI as I need the fastest possible update rate. I have trouble finding an easy to understand sample code, or perhaps a lightweight library how to configure and initialize the sensor and read gyro / accelerometer data via SPI.

So far I started adapting the code and info found at https://playground.arduino.cc/Main/MPU-6050 thought it would be fairly easy to use SPI instead of I2C "Wire", and adapt the configuration and registers based on the datasheet, but I realized there's too many possible pitfalls.

Any recommendations?

body:
For anyone who has not yet figured this out, its very simple.

Basically, for SPI communication with the sensor MPU 6500, its a bit different from what I2C has to offer.

In I2C, basically you will find the data packet is as follows:

(7 bit Slave Address + Read/Write Bit), but in SPI it is as follows:

(Read/Write Bit + 7 Bit Register Address), notice we dont even need the slave address in SPI as the Chip Select is connected from processor(Master) to Sensor(Slave).

So for SPI, lets say you want to write a value 64 to register 0x6B, then:
Transmission_data[2];
Transmission_data[0] = 0x6B;
Transmission_data[1] = 64;

Lets say you want to read a value from register 0x43, which is GYRO_X_High Byte value, then,
Transmission_data[1];
Transmission_data[0] = 0x43 | 0x80; // you need to or it with 0x80(decimal = 128)

Thanks...Hope this helps someone in need of help for SPI as I struggled too in finding this information.