message:
Arduino TCP Server establishes connection with client but does not receive data

I am trying to send and receive data with the **TCP** server but I am not receiving data.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>

    // Parametros de conexion a red WIFI.
    const char* ssid = "bits";
    const char* password = "12345";

    // Start a TCP Server on port 5000
    WiFiServer server(5000);

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid,password);
      Serial.println("");
      //Wait for connection
      while(WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
     Serial.println(WiFi.localIP()); // IP

      // Start the TCP server
      server.begin();
    }

    void loop() {
      TCPServer();
    }

    void TCPServer () {
       WiFiClient client = server.available();
        if (client) {
          Serial.println("We have a new client");
          Serial.println("Hello, client!");
            if (client.available() > 0) {
                char thisChar = client.read();
                Serial.println("We got data");
                Serial.println(thisChar);
                delay(200);
            }
        }
    }

**Test Capture**: In the capture it is seen that the code is executed until the following instruction.

    Serial.println("We have a new client");
    Serial.println("Hello, client!");

[![Test rec][1]][1]

[![Test sen][2]][2]

  [1]: https://i.stack.imgur.com/TIgBT.png
  [2]: https://i.stack.imgur.com/t1jTS.png

body: You have created a TCP server. You need to connect other clients to it to start data send and receive process between them. If you just simply run this and wait, then you probably won't get anything because nobody is attempting to connect to it.


sender: user

sender: assistant

body:
I found the solution by modifying the code

    void TCPServer () {
       WiFiClient client = server.available();
      if (client)
      {
        Serial.println("New Client");

        while(!client.available()&&client.connected())
        {
        delay(1);
        }

        String linea1 = client.readStringUntil('r');
        Serial.println(linea1);
      }
    }

[![test2][1]][1]

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


message:
Directly powering a single 32x16 RGB LED matrix (without external PSU)

All the guides I've found suggest to use an external PSU to power an [RGB matrix like this][1].

However I know it is possible to blink the LEDs at high rates (eg. 2ms) and still give the impression to the eyes they are fully on. I've verified this myself on a small 4x4 matrix, but I am not sure if the same can be done with these bigger matrices.

In my case I could tolerate reduced brightness and color space, but I'd like to power the matrix with the Arduino's 5V pin directly.

  [1]: https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/powering

body:
When powered through USB, the total current consumption is limited to 500mA by the USB interface. If you are using the power connector, the total current is limited by the on board 5V regulator to 1A.

The board will also require some current, so you can draw around **400mA**, if powered through USB or **900mA**, if powered through the connector; from the 5V pin.

While the matrix on average may not draw than 300 - 400mA, the voltage regulator can overheat and shut off temporarily, and you will never be able to reach 900mA. The regulator is linear, so any extra voltage you supply will result in waste heat.

It is best to get a buck converter or power the matrix externally. You won't be wasting as much power, and avoiding possible thermal shutoff.


body:
I've received yesterday [the 32x16 LED matrix I've ordered from AliExpress][1] and I've done some measurements with a multimeter in series with the power wire.

[LED multiplexing][2] does not seem a good idea as [the matrix is already doing that internally][3].

Instead I've found that using the **minimum color intensity** helps a lot reducing the current usage.

E.g. for blue use `matrix.Color333(0, 0, 1)` instead of `matrix.Color333(0, 0, 7)`; for white use `matrix.Color333(1, 1, 1)` instead of `matrix.Color333(7, 7, 7)`, etc.

With the minimum brightness I've measured:

 - All blue LEDs lit = ~170mA
 - All LEDs lit as white (red+blue+green) = ~400mA

In the average case (not all LEDs are lit) I am getting around **250mA**, so I should definitely be fine powering the matrix directly from the 5V pin if I keep the brightness as low as possible.

  [1]: https://www.aliexpress.com/store/product/P10-Indoor-1-8-Scan-SMD3528-3in1-RGB-Full-color-LED-display-module-320-160mm-32/314096_1615047851.html
  [2]: https://en.wikipedia.org/wiki/Multiplexed_display
  [3]: https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/how-the-matrix-works


message:
7805 powered Atmega328 Stops working when input of 7805 exceeds 7volts

[![Pulldown at Q1 added][1]][1][![New Modified Circuit][2]][2][![Old Sketch][3]][3]I am developing a circuit with atmega328, the MCU is powered by a LM7805.
The input of 7805 is given by a variable supply. Till the input of 7805 is 7volts, the output voltage is 4.9volts and current is around .75amps. Now if the input voltage of 7805 is increased, the current also increases and the MCU stops working(sometimes work with being reset after a few seconds), please help me out guys... i need to connect those circuits to my car battery, so it must work with 12volts.

I added capacitors and diodes as per Majenko mentioned. Now the situation is a) The circuit is working at 12V, b) With single C817 , output voltage of mcu is 3.5V, c)I used 56 ohms resistance, which is giving 1.2V to the input of C817, d) The Collector to Emitter resistance of C817 is 1520 ohms when turned on, this is creating a voltage drop of 3volts. e) This output is turning the led on, but being unable to switch the relay.

**Circuit Upate**

This the modified circuit, which solves the problem. But i have some questions, in the modified circuit if BC547 is used then its not working because the collector voltage which should be around 0.2 remains 1.8 volts, but replacing the BC547 with BC337 solves the problem(Collector voltage becomes around 0.3).
[![The Modified Circuit][4]][4]

  [1]: https://i.stack.imgur.com/qjlq6.png
  [2]: https://i.stack.imgur.com/o1eu2.png
  [3]: https://i.stack.imgur.com/hlrCX.png
  [4]: https://i.stack.imgur.com/bvXUX.png

body:
It looks like the reason for the MCU drawing high current is operating the LEDs in half a dozen optical isolators without current-limiting resistors.  The part number of your isolators apparently is PC817, for which the suggested LED current is 5 to 20 mA at about 1.2 to 1.4 forward volts.  But if you don't limit the current, they are likely to draw 50 to 100 mA each when turned on.  Add a series resistor, say 220 to 330 Ω, in series with each isolator.

At this point, it's possible you may have damaged your ATmega328 by overheating it, due to drawing too much current from its outputs.  You probably should run some tests with simple sketches to see if they all work ok.

Note, it probably would make sense to use a buck regulator rather than a linear regulator in the 12 V environment.  MP1584-based buck regulator boards (“Mini DC 4.5~28V to DC 3.3V MP1584 3A Step-down Converter Regulator Module”), about 2x2 cm, are about a dollar on ebay and handle 2 amps typically.


body:
There are a number of basic but vitally important components missing from your schematic. Namely input and output capacitors on the voltage regulators, which would result in oscillation and thus overheating (which would then shut them down through thermal overload), decoupling capacitors on the main chip, reverse biased diodes across the relay coils (maybe as well a small capacitor would be beneficial in parallel), and resistors to limit the current through your opto isolators.

Here is a version of your schematic with the missing components added in red. I have omitted the values - your job is to *read the datasheets* and work out the correct values to use.

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

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


message:
Temperature sensor bugs

My project is based on a moving fan using DHT11 sensors. I have used 2 void loops and the IDE is showing an error

>"exit status 1
redefinition of 'void loop()'"

One doubt: Can we use 2 void loops in the code? Please see and identify the errors.

2nd doubt: `dht DHT;` shows error
>"exit status 1
'dht' does not name a type" for my version of Arduino 1.8.1

    #include <DHT.h>
    #include <DHT_U.h>
    #include <Adafruit_Sensor.h>

     // Including library for dht
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    #define dht_dpin 12
    dht DHT;
    #define pwm 9

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

    void loop() {
      // put your main code here, to run repeatedly:
      // put your setup code here, to run once:
      lcd.begin(16, 2);
      lcd.clear();
      lcd.print(" Fan Speed");
      lcd.setCursor(0,1);
      lcd.print(" Controlling");
      delay(2000);
      analogWrite(pwm, 255);
      lcd.clear();
      lcd.print("Circuit Digest ");
      delay(2000);
    }

    void loop() {
      DHT.read11(dht_dpin);
      int temp=DHT.temperature;
      lcd.setCursor(0,0);
      lcd.print("Temperature:");
      lcd.print(temp);   // Printing temperature on LCD
      lcd.print("oC");
      lcd.setCursor(0,1);
      if(temp <26 ) {
        analogWrite(9,0);
        lcd.print("Fan OFF");
        delay(100);
      } else if(temp==26) {
        analogWrite(pwm, 51);
        lcd.print("Fan Speed: 20%");
        delay(100);
      } else if(temp==27) {
        analogWrite(pwm, 102);
        lcd.print("Fan Speed: 40%");
        delay(100);
      } else if(temp==28) {
        analogWrite(pwm, 153);
        lcd.print("Fan Speed: 60%");
        delay(100);
      } else if(temp==29) {
        analogWrite(pwm, 204);
        lcd.print("Fan Speed: 80%");
        delay(100);
      } else if(temp>29) {
        analogWrite(pwm, 255);
        lcd.print("Fan Speed: 100%");
        delay(100);
      }
      delay(3000);
    }
    }

body:
Here, below is updated version of your code.

Before running this code, you have to download DHT library. Just click on `Click Here` and you find good explanation & library of DHT11 Sensor. Becuase this library I usually preferred for my code. So, please download it and then run my code.

[Click Here][1]

And two void() loop never used. Put your all logic in one void() loop.

Note: This is not tested code. So if you face any problem then update me.

    #include <dht.h>                // DHT library
    #include<LiquidCrystal.h>       // LCD library

    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

    dht DHT;

    #define DHT11_PIN 12

    #define pwm 9

    float temp;

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

      pinMode(pwm, OUTPUT); //Pin as OUTPUT
    }

    void loop()
    {

     int chk = DHT.read11(DHT11_PIN);
     temp = DHT.temperature;
     Serial.print("Temperature = ");
     Serial.print("\t");
     Serial.print(temp);
     delay(1000);

     lcd.begin(16, 2);
     lcd.clear();
     lcd.setCursor(0, 0);
     lcd.print("Fan Speed");
     lcd.setCursor(0, 1);
     lcd.print("Controlling");
     delay(2000);
     lcd.clear();
     lcd.setCursor(0, 0);
     lcd.print("Circuit Digest");
     delay(2000);
     lcd.clear();
     lcd.setCursor(0, 0);
     lcd.print("Temperature:");
     lcd.setCursor(10, 0);
     lcd.print(temp);

     lcd.setCursor(0, 1);

     if(temp < 26 )
     {
        analogWrite(pwm, 0);
        lcd.print("Fan OFF");
        delay(100);
     }
     else if(temp == 26)
     {
        analogWrite(pwm, 51);
        lcd.print("Fan Speed: 20%");
        delay(100);
     }
     else if(temp == 27)
     {
        analogWrite(pwm, 102);
        lcd.print("Fan Speed: 40%");
        delay(100);
     }
     else if(temp == 28)
     {
        analogWrite(pwm, 153);
        lcd.print("Fan Speed: 60%");
        delay(100);
     }
     else if(temp == 29)
     {
        analogWrite(pwm, 204);
        lcd.print("Fan Speed: 80%");
        delay(100);
     }
     else if(temp > 29)
     {
        analogWrite(pwm, 255);
        lcd.print("Fan Speed: 100%");
        delay(100);
      }
    }

  [1]: https://arduino-info.wikispaces.com/DHT11-Humidity-TempSensor


message:
What is the definition of these arduino commands, and how do they affect the circuit?

I don't know if I am allowed to ask this question because really I could just look this up on google. The reason I'm asking here is because in google when you look up the definitions for the following commands, they treat you like you have good knowledge of arduino boards work. I however want to be treated as a beginner who just started learning arduino boards.

So I want to know the definitions of the following commands in a way that I could learn and teach new beginners without getting them confused.

So I want to know the clear definitions of these following commands:

**analogWrite and also why does it have a limit of 255? what does this 255 mean?**

**analogRead  and also why does this have a limit of 1023? what does this mean?**

**digitalWrite and also how does this differ from analogWrite?**

**digitalRead and also how does this differ from analogRead?**

**Loop and setup also what is the void before it?**

**Variables and also how they are declared?**

**Map and also what does it map and how?**

**Serial.write and also how does this differs from analogWrite and digitalWrite?**

**If/else commands and when they should and shouldn't be used?**

Like I said, I do not know whether the question is appropriate, but could be helpful to all the beginners learning Arduino.

body:
These are a lot of different questions. However, you can find most of the Arduino related answers in the official reference:
[Arduino reference Guide][1]

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

Some other answers:

- how to declare variables:

<type> <variable_name>

e.g.

    int x;

SerialWrite sends data to the serial port/UART, analogWrite and digitalWrite puts a voltage to a pin (simplified).

AnalogWrite is normally used for a value that has a range (like the intensity of a led), digitalWrite for an On/Off state (can also be for a led but just on/off).

if/else commands can be used to make a program make a decision.

e.g.

    if (a == 10)
    {
        Serial.println("10");
    }
    else
    {
        Serial.println("Not 10");
    }

void means 'nothing' ... in principle it means the functions (setup and loop) do not return any value. You can also define functions which return a value, e.g.

    int add(int a, int b)
    {
        return a + b;
    }

Read in any C/C++ manual about the commands, get a beginner programmers handbook.

The limit of a pin, means the value cannot be more than 255 or 1023. This means that the range of the value you can get/set is between 0 and 255 or 1023.
The map command can be used to make a value within the range required.


message:
Problem when using PROGMEM on array holding notes for speaker on Arduino

The problem I've been having is a little weird. I'm trying to set up audio for my Arduino project and have been playing around with the example included in the IDE. The problem is whenever I try to make the array of notes go into PROGMEM, it makes the outputted note higher than the one I put in. I don't want it to do that.
In case it is relevant, the code I have is as follows:

        #define tuneSize 2
        // notes in the melody:
        const int melody[tuneSize] PROGMEM /*This is what's screwing it up*/= {
          NOTE_AS3, 0
        };

        // note durations: 4 = quarter note, 8 = eighth note, etc.:
        int noteDurations[tuneSize] = {
          6, 16
        };

        void setup() {
          // no need to repeat the melody.
          // iterate over the notes of the melody:
          for (int thisNote = 0; thisNote < tuneSize; thisNote++) {

            // to calculate the note duration, take one second
            // divided by the note type.
            //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
            int noteDuration = 1000 / noteDurations[thisNote];
            tone(8, melody[thisNote], noteDuration);

            // to distinguish the notes, set a minimum time between them.
            // the note's duration + 30% seems to work well:
            int pauseBetweenNotes = noteDuration * 1.30;
            delay(pauseBetweenNotes);
            // stop the tone playing:
            noTone(8);
        }
    }
(Pitch.h can be found in the Arduino example tab under digital)

My circuit has an 8 ohm resistor on pin 8. That's it.

The only thing I can think is that since the PROGMEM is slower, the data doesn't get to the speakers as fast thus making the output weird. Does anyone know how to fix this issue? Also, just having it on SRAM is not ideal because I'm working with a display and the lib it uses uses a lot of SRAM.

body:
You can not directly dereference something ("access an array") that is in flash memory. You have to use pgm_read_xxx functions from <[avr/pgmspace.h][1]> .

In your case you should probably write something like this:

    tone(8, pgm_read_word(&melody[thisNote]), noteDuration);

Pgm_read_word reads two bytes. You could also call that inside your tone() function, the function would take the pointer in flash as an argument.

 I would also recommend you using integer types from <[stdint.h][2]>, because they have defined sizes. Pure int is most likely 32-bit on your PC, but 16-bit on the AVR (I have learned this the hard way when my algorithm ran fine on the PC but gave totally junk output on the AVR).

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html


message:
Data sent via UART Bluetooth different than SerialMonitor

I am using a 9-axis accelerator on an Arduino Uno (Atmega 328P processor) with a BLE Nordic rRF8001 chipset.

I am trying to send the accelerometer data via bluetooth to a smart phone (android).

The problem I am having is that the data shown on the serial monitor (which is correct, is not the data that is received via bluetooth. I think it has something to do with either the casting of the variables or that I am screwing up when converting the formats. Below is where I'm currently at and what I have tried.

The error I'm having is that the accelerometer data shown on the serial monitor screen (which is correct):

 1. A_x: -0.12 A_y: 0.53 A_z: 0.83
 2. A_x: -0.12 A_y: 0.53 A_z: 0.83
 3. A_x: -0.12 A_y: 0.53 A_z: 0.83

Does not agree with what the smart phone receives: (See image 1)
[![enter image description here][1]][1]

If I hard code in the x,y,z values in the arduino sketch

 1. float x = (float) 0.52;
 2. float y = (float) 0.52;
 3. float z = (float) 0.52;

I get the following results (see image 2):
[![Accel. Data][2]][2]

And here is the Arduino sketch I am working with:

    //-------------------------------------------------------------------------------
    //  TinyCircuits 9 Axis and Nordic BLE TinyShield Example Sketch

    #include <Wire.h>
    #include "RTIMUSettings.h"
    #include "RTIMU.h"
    #include "RTFusionRTQF.h"
    #include <SPI.h>

    #include "lib_aci.h"
    #include "aci_setup.h"
    #include "uart_over_ble.h"
    #include "services.h"

    #if defined (ARDUINO_ARCH_AVR)
    #define SerialMonitorInterface Serial

    #elif defined(ARDUINO_ARCH_SAMD)
    #define SerialMonitorInterface SerialUSB
    #endif

    #define DISPLAY_INTERVAL 100

    RTIMU *imu;                                           // the IMU object
    RTFusionRTQF fusion;                                  // the fusion object
    RTIMUSettings settings;                               // the settings object

    unsigned long displayInterval = 50;
    unsigned long lastDisplay;
    unsigned long lastRate;
    int sampleCount;

    #define BLE_DEBUG false
    uint8_t ble_rx_buffer[21];
    volatile uint8_t ble_rx_buffer_len = 0;
    volatile uint8_t ble_can_sleep = false;
    volatile uint8_t ble_connection_state = false;

    #ifdef SERIAL_POR_MONITOR
      #define SerialMonitor SERIAL_PORT_MONITOR
    #else
      #define SerialMonitor Serial
    #endif

    void setup(void)
    {
    //  SerialMonitorInterface.begin(230400);
      SerialMonitor.begin(230400);

      int errcode;

      while (!SerialMonitor);

      Wire.begin();
      imu = RTIMU::createIMU(&settings);                        // create the imu object

      SerialMonitorInterface.print("ArduinoIMU starting using device "); SerialMonitorInterface.println(imu->IMUName());
      if ((errcode = imu->IMUInit()) < 0) {
        SerialMonitorInterface.print("Failed to init IMU: "); SerialMonitorInterface.println(errcode);
      }

      if (imu->getCalibrationValid())
        SerialMonitorInterface.println("Using compass calibration");
      else
        SerialMonitorInterface.println("No valid compass calibration data");

      lastDisplay = lastRate = millis();
      sampleCount = 0;

      // Slerp power controls the fusion and can be between 0 and 1
      // 0 means that only gyros are used, 1 means that only accels/compass are used
      // In-between gives the fusion mix.

      fusion.setSlerpPower(0.02);

      // use of sensors in the fusion algorithm can be controlled here
      // change any of these to false to disable that sensor

      fusion.setGyroEnable(true);
      fusion.setAccelEnable(true);
      fusion.setCompassEnable(true);
      BLEsetup();
    }

    void loop() {
      aci_loop();//Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
      unsigned long now = millis();
      unsigned long delta;

      if (imu->IMURead()) {                                // get the latest data if ready yet
        fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
        sampleCount++;
        if ((delta = now - lastRate) >= 1000) {
          /*SerialMonitorInterface.print("Sample rate: "); SerialMonitorInterface.print(sampleCount);
            if (imu->IMUGyroBiasValid())
            SerialMonitorInterface.println(", gyro bias valid");
            else
            SerialMonitorInterface.println(", calculating gyro bias - don't move IMU!!");
          */
          sampleCount = 0;
          lastRate = now;
        }
        if ((now - lastDisplay) >= displayInterval) {
          lastDisplay = now;
          RTVector3 accelData = imu->getAccel();
          RTVector3 gyroData = imu->getGyro();
          RTVector3 compassData = imu->getCompass();
          RTVector3 fusionData = fusion.getFusionPose();
          char sendBuffer[30] = " ";
          uint8_t sendLength = 0;
          //displayAxis("Accel:", accelData.x(), accelData.y(), accelData.z());        // accel data
          //displayAxis("Gyro:", gyroData.x(), gyroData.y(), gyroData.z());            // gyro data
          //displayAxis("Mag:", compassData.x(), compassData.y(), compassData.z());    // compass data
          //displayDegrees("Pose:", fusionData.x(), fusionData.y(), fusionData.z());   // fused output
          float x = (float)(accelData.x() );//* RTMATH_RAD_TO_DEGREE);
          float y = (float)(accelData.y() );//* RTMATH_RAD_TO_DEGREE);
          float z = (float)(accelData.z() );// * RTMATH_RAD_TO_DEGREE);
    //      float x = (float) 0.52;
    //      float y = (float) 0.52;
    //      float z = (float) 0.52;
          sendLength = sprintf(sendBuffer, "% 2.3d % 2.3d % 2.3d", x, y, z);
          if (sendLength > 20)sendLength = 20;
          if (!lib_aci_send_data(PIPE_UART_OVER_BTLE_UART_TX_TX, (uint8_t*)sendBuffer, sendLength))
          {
            SerialMonitorInterface.println(F("TX dropped!"));
          }
          SerialMonitorInterface.println();

          SerialMonitor.print(" A_x: "); SerialMonitor.print(x);
          SerialMonitor.print(" A_y: "); SerialMonitor.print(y);
          SerialMonitor.print(" A_z: "); SerialMonitor.println(z);

        }
      }
    }

Any thoughts on why the data sent over BLE is incorrect?

  [1]: https://i.stack.imgur.com/oP2bk.png
  [2]: https://i.stack.imgur.com/gRiIf.png

body:
The problem has nothing to do with the bluetooth. It is purely down to how you are formatting the data:

    % 2.3d % 2.3d % 2.3d

`d` is a signed integer. You can't format a floating point value as a signed integer, it just messes up.

Also I don't think the Arduino's `sprintf` even has floating point support by default (it makes it all too big).

So you will need to find another way to format your data. Maybe use `dtostrf()` instead.


message:
ATTiny85 VirtualWire AnalogRead 1

My **ATTiny85** is connected to a **433 transmitter** and an **analog sound sensor**. The 433 is working fine (using **VirtualWire**) but when I send the reading from the sensor all I receive is a 1.

What I would like to receive is the value between 0 and 1024 like when I print the sensor to serial. I cannot check it because the ATTiny85 had no serial out.

My code is a combination of snippets I found online, I am not happy with all the magic to format the data that needs sending. I would also like to send "Reading: 637" in stead of just the number but I find the concatenation Google results extremely complicated.

Should this code send the sensor data like 672?
Could there maybe be some Fuse setting blocking the AnalogRead?

    #include <VirtualWire.h>

    const int transmit_pin = PB0;
    const int sensor_pin = PB4;
    int sensor_data;
    char sensor_msg[4];

    void setup()
    {
      vw_set_tx_pin(transmit_pin);
      vw_setup(2000);
    }

    int count = 1;

    void loop()
    {

      sensor_data = analogRead(sensor_pin);
      itoa(sensor_data,sensor_msg,4);
      vw_send((uint8_t *)sensor_msg, strlen(sensor_msg));
      vw_wait_tx(); // Wait until the whole message is gone
      _delay_ms(1000);
      count = count + 1;

    }

**Receiver Code as requested**
This is a Pro Mini (clone) and it has an LCD attached so I can see what is going on.

    #include <VirtualWire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27,16,2);

    const int receive_pin = 11;
    char* testje;
    void setup()
    {
        delay(1000);
        Serial.begin(9600); // Debugging only
        Serial.println("setup");

        // Initialise the IO and ISR
        vw_set_rx_pin(receive_pin);
        vw_setup(2000);  // Bits per sec

        vw_rx_start();       // Start the receiver PLL running

        lcd.init();
        lcd.backlight();
        lcd.home();
        lcd.clear();
        lcd.print("hello");
        delay(1000);
        lcd.clear();
    }

    void loop()
    {
      char buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;

      if (vw_get_message(buf, &buflen)) {
        int i;
        // Message with a good checksum received, print it.
        Serial.print("Got: ");

        for (i = 0; i < buflen; i++) {
           Serial.print((char)buf[i]);
        }
     Serial.println();
        Serial.println(buf);
        lcd.clear();
        lcd.print(buf);
      }
    }

body:
I would double check the pin numbers for the attiny. They look like port bit numbers but that might just work by chance.

    const int transmit_pin = PB0;
    const int sensor_pin = PB4;

A quick double check with the [attiny/pins_arduino.h][1] give:

    // ATMEL ATTINY45 / ARDUINO
    //
    //                 +-\/-+
    // Ain0 (D5) PB5  1|    |8  Vcc
    // Ain3 (D3) PB3  2|    |7  PB2 (D2) Ain1
    // Ain2 (D4) PB4  3|    |6  PB1 (D1) pwm1
    //           GND  4|    |5  PB0 (D0) pwm0
    //                 +----+

As you have found they should be defined as:

    const int transmit_pin = 0; // Physical pin 5
    const int sensor_pin = 4;   // and pin 3

This type of issue could be avoided by using strong data typing and object oriented design. Please see for instance Cosa [ATtinyX5.hh][2] and [GPIO.hh][3].

Cheers!

[Here][4] is something that does basically the same as the sender. Cosa supports attiny and Arduino boards "out-of-the-box".

  [1]: https://github.com/damellis/attiny/blob/master/variants/tiny8/pins_arduino.h#L33
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Board/Arduino/ATtinyX5.hh
  [3]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/GPIO.hh
  [4]: https://github.com/mikaelpatel/Cosa-Domotica/blob/master/RF433/DomoticaAnalogPin/DomoticaAnalogPin.ino


message:
Persistence of user input after reboot

I am creating an application where user input is required. After a user browses through available choices (via buttons and LCD) depending on the choice of the user a function is run from several available.

When the user reboots the Arduino, it starts from the default function, making the user reselect the choice they want..

Is there a way to have persistence of the choice of the user after a reboot?
So that, when a user makes a selection, after a reboot, the arduino will have this selection (=the function that corresponds to this selection) by default.

Maybe if the user input (the buttons) write to an EEPROM or something like this? So that the arduino reads the value from the component?

If such a solution exists, due to limitations i would like to have only one wire for communication with the device.

EDIT: I am using Arduino Due

body:
Better than that: Zero wires.

The Arduino has EEPROM built in.


message:
Button press with Arduino repeated many times

I have 5V -> button -> 10K resistor -> PIN2 setup with Arduino UNO.

My code is very simple:

    int count = 0;

    void setup() {
      pinMode(2, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      int state = digitalRead(2);
      Serial.println(state);
      if (state == HIGH) {
        count++;
        Serial.print("Hi");
        Serial.println(count);
      }
      delay(1000);
    }

If the button is pressed print "HiX", but what I get is very strange. When I press the button only once I get this:

    0
    0
    0
    0
    0
    1
    Hi1
    1
    Hi2
    1
    Hi3
    1
    Hi4
    1
    Hi5
    1
    Hi6
    1
    Hi7
    1
    Hi8
    1
    Hi9
    1
    Hi10
    0

The button press is registered 10 times.

What am I doing wrong ?

body:
I can't comment that's why I'm writing this as an answer but,

Are you doing exactly this this to wire the button?

 [![https://www.arduino.cc/en/uploads/Tutorial/button.png][1]][1]
I'd like to see your schematic but from what you describe there's a pull-down connection missing

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


body:
there could be some stray capacitance that's holding the charge.

generally for cases like that, put the buttons active low + pull-up to avoid cases like yours.


body:
Try out this code and schematic. It may solve your problem of debouncing.

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

    const int buttonPin = 2; // Push Button at Pin 2

    int buttonState = 0;
    int lastButtonState = 0;

    int counter = 0;

    void setup()
    {
      pinMode(buttonPin, INPUT_PULLUP); // Push Button with pull-up
      Serial.begin(9600);
    }

    void loop()
    {
      buttonState = digitalRead(buttonPin);

      if (buttonState != lastButtonState)
      {
        if (buttonState == HIGH)
        {
          counter++;
          Serial.println("Hi !");
          Serial.print("Number of button pushes:  ");
          Serial.println(counter);
        }
        else
        {
          Serial.println("Button off");
        }
        delay(50); // Delay a little bit to avoid bouncing
      }
      lastButtonState = buttonState;
    }

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


body:
I think it's not a problem of debouncing...
There is a delay(1000) in the loop so after 1 second, the switch is not bouncing anymore.
But switching to VCC is the problem. Connect the switch to GND and use the internal pullup resistors (pinMode(2, PULLUP).
The switch then pulls it down to ground. Now it is floating and probably still HIGH after opening the switch....


message:
Why my Galileo isn't getting a IP address?

I have an Ethernet cable connected to my router. I connected the other end to my laptop and got a successful connection. When I plug it into my Arduino Galileo gen2, even with Ethernet port green light on, I got nothing when I run this:

    delay(1000);
    system("ifconfig eth0 > /dev/ttyGS0");

This is my output:

    eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:00
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:41 Base address:0x8000

What I'm doing wrong?

body: I really don't know why, but after I initialized the Ethernet interface`ifconfig eth0 up` it started working properly. I don't know why this time this command was needed and the others didn't.


message:
Working or functionality Serial.begin(9600)

In recent practice, I found out some new things.

`Serial.begin(9600);`

What is mean of this line of code?

Why here, we always write `9600`?

And can we write manually number means instead of 9600 let's say 10000?

body:
    Serial.begin(9600);

This line starts Serial communication with a baud rate of 9600. Serial communication is used to transmit data between your application and external systems (including your PC, other Arduinos, sensors, and other ICs).

Most of the time this is included to allow the application to output information via the Serial Monitor when connected to you PC.

Documentation for this is here:
https://www.arduino.cc/en/reference/serial

From the documentation: "For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200."
- [source](https://cdn.arduino.cc/reference/en/language/functions/communication/serial/begin/)


body:
`Serial.begin(9600);`

`What is mean of this line of code?`

Serial.begin(9600) doesn't actually print anything.

If you want to print "Hello world!" to the serial monitor then you have to use this line of code. Rather it initializes the serial connection at 9600 bits per second.

It is used for kind of handshaking means both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

`Why here, we always write 9600?`

And 9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Ardunio to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Ardunio IDE's serial monitor) to the same speed in order to see the data being sent.

`And can we write manually number means instead of 9600 let's say 10000?`
No, we can't write. There is a specific baud rate available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.


message:
Can I make a USB Device with only data output

**This is about how USB ports/devices work**

Lets say i have a USB port on my computer

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

If I have an arduino board or something similar, am I able to connect output to Data+ and sort of make my own USB keyboard.
**What I aim to achieve is send without having to receive**

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

**1)** Would I need to connect it to both D+ and D- so it forms a circuit in order for the USB port to read the data? (or would the data simply be read and then disappears so I don't have to worry about two wires?)

If Yes: **2)** If I manage to forcefully push electricity through the wire onto the Data pins, would I only need one wire?

Else: **3)** is this physically impossible and the whole universe would explode if I tried?

  [2]: https://i.stack.imgur.com/Qzef3.png
  [3]: https://i.stack.imgur.com/k35HS.png

body:
USB is a host-managed protocol. A USB device *must* be able to receive in order to operate, since the host notifies the device when it should send data back to the host.

The D+ and D- lines are *not* independent; the signaling state of the line is determined by examining *both* lines regardless of whether the host or the device is transmitting.

USB Made Simple


body:
D+ and D- are not send and receive. The two signals are complementary to each other and bidirectional.

They form a *low voltage differential pair*. When one is high the other is low and vice versa.

Both have to be connected for USB signals to get through.

The data is sent down both wires at once, but only in one direction at a time (half duplex).

There is far more data going through USB than the data you are sending. The data you see is the end result of a complex protocol negotiation between your device and the host.


message:
What bootloader does the Arduino Micro come with?

I've been looking to modify the Arduino Micro bootloader (specifically changing the VendorID and ProductID) of the Arduino. What bootloader comes pre-installed on the Arduino Micro? and how would I go about building and uploading a modified bootloader?

body:
Try looking at https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c

Inside that is:

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

    /** Device descriptor structure. This descriptor, located in SRAM memory, describes the overall
     *  device characteristics, including the supported USB version, control endpoint size and the
     *  number of device configurations. The descriptor is read out by the USB host when the enumeration
     *  process begins.
     */
    const USB_Descriptor_Device_t DeviceDescriptor =
    {
     .Header                 = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},

     .USBSpecification       = VERSION_BCD(01.10),
     .Class                  = CDC_CSCP_CDCClass,
     .SubClass               = CDC_CSCP_NoSpecificSubclass,
     .Protocol               = CDC_CSCP_NoSpecificProtocol,

     .Endpoint0Size          = FIXED_CONTROL_ENDPOINT_SIZE,

     .VendorID               = DEVICE_VID,
     .ProductID              = DEVICE_PID,
     .ReleaseNumber          = VERSION_BCD(00.01),

     .ManufacturerStrIndex   = 0x02,
     .ProductStrIndex        = 0x01,
     .SerialNumStrIndex      = NO_DESCRIPTOR,

     .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
    };

...

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

    /** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
     *  and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
     *  Descriptor.
     */
    const USB_Descriptor_String_t ProductString =
    {
     .Header                 = {.Size = USB_STRING_LEN(16), .Type = DTYPE_String},

     #if DEVICE_PID == 0x0036
     .UnicodeString          = L"Arduino Leonardo"
     #elif DEVICE_PID == 0x0037
     .UnicodeString   = L"Arduino Micro   "
     #elif DEVICE_PID == 0x003C
     .UnicodeString   = L"Arduino Esplora "
     #else
     .UnicodeString   = L"USB IO board    "
     #endif
    };

> and how would I go about building and uploading a modified bootloader?

You would run the Makefile which is in the same directory as the above file. Then send the resulting .hex file to your device.


message:
Master doesn't receive the correct values in a master/slave SPI link

I've been struggling for 3 weeks looking for a solution to my problem concerning SPI communication.

So, I need to establish a SPI communication between two Arduino devices: for instance, the master sends a letter 'a' to the slave; the slave receives it and does some processing. In my case, it should set one of his  8 pins to high then read all pins and send the report back to the master.

The part where the master sends 'a' and the slave processing it works fine but the master doesn't seem to receive the correct values. Instead it always receives 0.

Here's the code:

______
Slave:
===

    #include <SPI.h>;

    volatile byte command = 0;
    byte ett =8; //nbr of test points
    byte motif= 0b000000000 ; //intiatition of my varible which will contain my pin's states
    byte end[8] = { 2,3,4,5,6,7,8,9}; //array containing the pins

    void setup (void) {
      Serial.begin (9600);
      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);
      // turn on SPI in slave mode
      SPCR |= _BV(SPE);
      // turn on interrupts
      SPCR |= _BV(SPIE);
    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect) {
      byte c = SPDR;
      switch (command) {
        //////////////Slave traitement/////////////
        // no command? then this is the command
      case 0:
        command = c;
        SPDR = 0;
        break;

      case 'z': ////case 'z", set all pins to INPUT
        for (int i=0; i<8; i++){
          pinMode (end[i], INPUT);
        }
        break;

      case 'a': // //if 'a' : Set one pin to high then read all pin's satete to verify if there is any open circuit or short circuit
        for (int j = 0; j < ett; j++) {
          pinMode(end[j], INPUT);   // set all pins as INPUT
        }
        motif = 0;
        pinMode(end[0], OUTPUT);  // Set one pin as OUTPUT
        digitalWrite(end[0], HIGH); // Set the output pin to HIGH
        Serial.println();
        Serial.print(" ");
        for (int k = 0; k < ett ; k++) { // scan
          if (digitalRead(end[k]) == HIGH) {
            // if pin == HIGH add '1' to my vector
            Serial.print("| ");
            motif = motif + 1; // +1
          } else { // if pin == LOW
            Serial.print(". ");
          }
          motif = motif << 1; // shift left
        }
        Serial.print(" -MOTIF LU= ");
        Serial.print(motif, BIN);
        SPDR = byte (motif); //SPDR is the SPI Data Register: it contains the data that will be sent to the Master
        Serial.print(" ");
        break;
      }
    }

    void loop (void) {
      // if SPI not active, clear current command
      if (digitalRead (SS) == HIGH)
        command = 0;
    }

Master:
===

    #include <SPI.h>

    byte CS0=10;
    byte CS1=9;

    void setup (void) {
      Serial.begin (9600);
      Serial.println ();
      digitalWrite(SS, HIGH);  // ensure SS stays high for now
      // Put SCK, MOSI, SS pins into output mode
      // also put SCK, MOSI into LOW state, and SS into HIGH state.
      // Then put SPI hardware into Master mode and turn SPI on
      SPI.begin ();
      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);
    }  // end of setup

    byte transferAndWait (const byte what) {
      byte a = SPI.transfer (what);
      delayMicroseconds (1000);
      return a;
    } // end of transferAndWait
    ///traitement au niveau du maitre

    void loop (void)  {
      byte esclave0_testpin0;
      /////////////Set the first slave's pin to High then read all pins
      digitalWrite (CS0,LOW); //activate the slave
      transferAndWait ('a'); // set first slave's pin to high
      esclave0_testpin0 = transferAndWait ('z'); //read all slave's pins and report it in the variable esclave0_testpin0
      digitalWrite (CS0,HIGH); //disactivate the slave
      Serial.println ("test_0");
      Serial.println (esclave0_testpin0, BIN);
      delay (1000);  // 1 second delay
    }  // end of loop

body:
In slave, **command is always 0**. You problably meant:

    void loop(void) {
        command = (digitalRead(SS) == HIGH ? 0 : 1);
    }

and at ISR:

    ISR (SPI_STC_vect) {

        byte input = SPDR;
        byte output = 0;

        if (command) {

            switch (input) {

                case 'a':
                    //...
                    break;

                case 'z':
                    //...
                    break;
            }
        }

         // send data back
         SPDR = output;
    }

As a best practice, avoid to implement the logic within the ISR and use global _volatile_ variables to pass state changes to the code in the main loop. Probably you will have to implement a circular buffer to receive from and send to the SPI bus...


message:
Programming Other Atmel chips using Arduino

Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

body:
> Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

Do you mean if the "Arduino as ISP" sketch and an Arduino would work to flash another Atmel AVR MCU? If so the answer is yes but I guess that you also want to generate code for the new MCU. In that case there is some work to be done before that is possible.

Start by reading about how to [install additional cores][1] and the [guideline for a custom core][2]. Then select an custom core to study. [Here][3] you will find the files you need to provide to support a new AVR based MCU.

Cheers!

  [1]: https://www.arduino.cc/en/Guide/Cores
  [2]: http://playground.arduino.cc/Main/CustomizeArduinoIDE
  [3]: http://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips


message:
How to send HTTP request to specific port using Ciao?

I currently have a working REST client on my Arduino, but the requests always go to port 80, how do I make it send the request to a specific port?

This is my current code:
```c++
/*
File: RestClient.ino
This example makes an HTTP request after 10 seconds and shows the result both in
serial monitor and in the wifi console of the Arduino Uno WiFi.

Note: works only with Arduino Uno WiFi Developer Edition.

http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient
*/

    #include <Wire.h>
    #include <UnoWiFiDevEd.h>

    void setup() {

     const char* connector = "rest";
     const char* server = "download.arduino.org";
     const char* method = "GET";
     const char* resource = "/latest.txt";

     Serial.begin(9600);
     Ciao.begin();

     pinMode(2, INPUT);

     delay(10000);
     doRequest(connector, server, resource, method);
    }

    void loop() {

    }

    void doRequest(const char* conn, const char* server, const char* command, const char* method){
     CiaoData data = Ciao.write(conn, server, command, method);
     if (!data.isEmpty()){
      Ciao.println( "State: " + String (data.get(1)) );
      Ciao.println( "Response: " + String (data.get(2)) );
      Serial.println( "State: " + String (data.get(1)) );
      Serial.println( "Response: " + String (data.get(2)) );
     }
     else{
      Ciao.println ("Write Error");
      Serial.println ("Write Error");
     }
    }
```

If I add for example ``:8080`` to the end of the ``server`` variable, it does not work.

How do I make that request go to a specific port?

body:
You can find a portdefinition on your arduino in this path:

/usr/lib/python2.7/ciao/connectors/restserver/restserver.json.conf

    {
     "name" : "restserver",
     "description" : "REST server connector for the Ciao Core",
     "authors": ["Arduino Team <swdev@arduino.org>;"],
     "repository" : "https://github.com/arduino-org/Ciao",
     "version" : "0.0.2",
     "params" : {
                "port" : 80
                 },
     "log" : {
             "level" : "info"
             }
    }

The confusing part is that your Arduino has a server client connection on it self from the cpu/linino server to the mcu/arduino client.

[https://www.arduino.cc/en/Reference/CiaoRestServer][2]

  [1]: http:///usr/lib/python2.7/ciao/connectors/restserver/restserver.json.conf
  [2]: https://www.arduino.cc/en/Reference/CiaoRestServer


message:
Using AA batteries to power Arduino and GPS unit

I'm more of a software guy, so I need your help to figure out the power issue with my Arduino.

What I would like to do is using a GSM/GPS unit ([Ai-Thinker A7][1]) with Arduino Nano as a car tracking system. I have USB cables in the car, so I can plug it into my Arduino and power both while I'm driving. To power the unit while I'm not driving, I thought using rechargeable batteries would be a good idea. I'm planning to use GPS via SMS activation, so I hope fully charged batteries will be enough to power it for at least a week. But I'm confused about a couple of things.

Rechargable batteries are 1.2V. So technically I can use 5 of them and power my Arduino and the GPS unit (which requires 5V), right? However, for a similar unit at Adafruit [they say that a LiPo battery is a must][2]. Well, I think it is because GPS unit draws more power while using GPS and stuff. So, in this case are AA batteries out of the question? Will I fry anything if I build the system as follows?

[![Circuit][3]][3]

If AA batteries happen to be fine, do I need another piece in my design, such as [this one][4]?

At last, I have no idea if I need any diode, capacitor, resistance or sth else for this system. I would appreciate further comments about my design.

  [1]: http://www.electrodragon.com/product/gsm-gprs-gps-module-a7-breakout
  [2]: https://learn.adafruit.com/adafruit-fona-808-cellular-plus-gps-breakout?view=all#faqs
  [3]: https://i.stack.imgur.com/FYRd1.jpg
  [4]: https://www.amazon.com/SMAKN-Lithium-Battery-Charging-Charger/dp/B00HJNX0DU

body:
I suggest using 6 or 8 AA's (eg 6 alkalines or 8 NiMH) and a  MP1584EN DC DC Power Stepdown Buck Converter (about a dollar on ebay, 1.5 to 3 times that on Amazon).  Note, the hole pattern does not match up with breadboard spacing: [![enter image description here][1]][1]

The batteries would tie in via a couple of diodes (preferably Schottky), as shown below.  When the 12 V supply is off, the converter would be powered by 9.6 V from eight rechargeable AA's.  When the  12 V supply is on, no current is drawn from the AA's.  The converter output should be adjusted to 5V before being connected to the Nano or other devices it powers.

Using a buck regulator has two advantages vs a linear regulator: battery current is lower (allowing the battery pack to be more efficient as it discharges) and less energy is wasted as heat.

Note, it might make sense to remove the power LED from the Nano, to save 3 to 5 mA of 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/U8txA.png)

<!-- End schematic -->

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


message:
Replacing BT module with 433 MHz transreceiver module

I have made a prototype where I can send data from one arduino to another via Bluetooth(hc-05), they are working fine, but now I want to replace the BT module with RF module, how can I do that???

body:
Yes, use [VirtualWire][1] or [RadioHead][2]. You might need to "evolve" your protocol to handle message fragmentation and loss. RadioHead has support for that.

Cheers!

  [1]: http://www.airspayce.com/mikem/arduino/VirtualWire/
  [2]: http://www.airspayce.com/mikem/arduino/RadioHead/


message:
Why does my Arduino Nano send the wrong voltage on a digital output PIN?

Adruino nano powered by 12v through **VIN** pin.

Normally I expect ~12v on digital output pin, when i write HIGH to this pin, and ~0v when i write LOW. But what I have instead

    digitalWrite(pin, HIGH); // I have 1.5v on pin
    digitalWrite(pin, LOW);  // I have 0.5v

Algorithm is quite simple - On push button toggle output pin state.
Connections:

* **VIN** - +12v
* **GND** - ground
* **d2** - input pin (0 0, 12 - 1, button);
* **d3** - output pin (we change state of this pin)

Input works as expected.

<!-- 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/35iul.png)

<!-- End schematic -->

body: The arduino is powered by 12v but regulates down to 5v or 3v for the microcontroller. Then your output pin current is important. Anything over 20mA will result in a large voltage droop due to the ESR of the pin. Highly depends on your circuit and your full code.


body:
The microcontoller in an Arduino operates on 5 Volts (or perhaps 3.3 Volts).  An on-board voltage regulator reduces the 12 Volt input to 5 volts for the ICs on the board.

Connecting the pull-up resistor (R1 in your drawing) to 12 Volts may damage the microcontroller (especially if it is really 100 Ohms as your drawing shows).  The pullup resistor must be connected to the 5 Volt pin on the Arduino board.

The output voltage of an Arduino pin should be near 5 Volts, but may be less if you place a heavy (high-current) load on it.


body:
As others have said, you should not pull d2 to 12 V. You are
sending about (12 V − 5 V) ÷ 100 Ω
= 70 mA into the high-side diode that protects that input pin.
This diode is only rated for 1 mA, thus you will likely fry it in a
short time.

To avoid the damage, you could increase the value of R1 in order to
lower that current to a safe value, but it would be simpler and safer to
completely remove the resistor and use the internal pullup instead, as
in

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

    pinMode(2, INPUT_PULLUP);

As for the measured output on d3, you expect 5 V when the pin is
written `HIGH`. Your 1.5 V reading is suspicious. My guess is that
you forgot to

    pinMode(3, OUTPUT);

In this case, writing the pin to `HIGH` does not have the expected
effect. Instead, it activates the internal pullup, which should make the
pin read 5 V, but then even a very small load (about 0.1 mA)
can make the voltage drop to 1.5 V.

If you are really getting 1.5 V while the pin mode is set to
`OUTPUT`, then you are really pulling far too much current from the pin.
My guess would be around 130 mA (a 26 Ω output resistance is
typical). The **absolute maximum rating** for the pin is 40 mA, so
again, you are going to fry something.


message:
Problem Uploading to arduino nano (atmega 328p)

I am using Arduino 1.8.1 and arduino nano (mega 328p) and ftdi driver.
In device manager it seems no problem, because it is detected as COM99. But it says a problem while uploading to the board as picture given.
Please Helpp..

[![This error that make me crazy][1]][1]

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

body:
Looking at the error in the end about the invalid library, it seems a configuration problem and not a communication problem.

Try:

- Close and reopen the Arduino IDE (and check again)
- Remove the library and add it again (in the Manage library options in the menu), close/reopen the Arduino IDE (and check again)
- Reinstall the Arduino IDE (and check again)


message:
Assigning float to 10 decimal place for longitude,latitude

I'm quite a novice in arduino programming. I am doing a small home project and I am using sim808 to obtain GPS data.

My question is quite simple but i can't find any solution online.

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat, 10);
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon, 10;

This code display Longitude and Latitude data on serial monitor to 10 decimal place perfectly.

But when after setting the Longitude and Latitude to float.When I use this code, I don't get a valid gps data.

    Longitude = (sim808.GPSdata.lon, 10 );
    Latitude = (sim808.GPSdata.lat, 10 );

Please help, Thanks.

(edited)
I understand my error in coding for the above.

In fact, I am using a DF robot shield sim 808 for vehicle tracking. I am uploading my GPS data, longitude, latitude and speed to Ubidots. The only difficulty is in saving accurate data.

I am using this codes

    Longitude = sim808.GPSdata.lon;
    Latitude = sim808.GPSdata.lat;
    Speedperkm = sim808.GPSdata.speed_kph;

    client.add("Longitude", Longitude);
    client.add("Latitude", Latitude);
    client.add("Speed per Km", Speedperkm);

The code is working fine but only GPS data of 2 decimal place is being uploaded. If data of up to 6 decimal place is uploaded then the system will more accurate.

That my problem that I am trying to solve.

body:
You always should calculate with the maximum resolution (not rounding to 10 digits), so use:

    Longitude = sim808.GPSdata.lon;
    Latitude = sim808.GPSdata.lat;

For printing you can use the code you have.

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat, 10);
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon, 10);


body:
> But when after setting the Longitude and Latitude to float.When I use
> this code, I don't get a valid gps data.

Some statements in C/C++ are not what they might seem. The value of the statements:

    Longitude = (sim808.GPSdata.lon, 10 );
    Latitude = (sim808.GPSdata.lat, 10 );

Are actually the same as:

    sim808.GPSdata.lon;
    Longitude = 10;
    sim808.GPSdata.lat;
    Latitude = 10;

Which is then optimized to:

    Longitude = 10.0;
    Latitude = 10.0;

That is, when using list notation, the value of the expression is the same as the value of last expression in the list.

The other answers have covered the fact that [float and double on Arduino (AVR-GCC)][1] are only 32-bit, and that gives [6 to 9 significant decimal digits precision][2].

Cheers!

  [1]: https://gcc.gnu.org/wiki/avr-gcc
  [2]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format


message:
Turning an LED on when an error occurs, then turn it off after 2 seconds

I am currently working on making some test equipment for µUSB cables. The code is supposed to recoqnise when an error in the cable occurs. Most of it works as expected, but I have some trouble understanding the use of millis() timers.
I, therefore want to ask, in the code below, how can I make my program pick up on an missing connection in the cable and make sure it turns on the LED always? And secondly, how can I make it stay on for 2 seconds, even if the cable has "fixed" itself again (i.e. the connection has returned)?

*Update*
It seems that I have misunderstood the assignment. The program should turn on a LED, when an error is present and keeps this on while the error is present (already fixed this in the code). When the connection has been regained a timer should start, which turns off the LED after two seconds. (Here's the trouble I'm having, I can't seem to pinpoint where and how this timer should start)

    case microUSB:
      if (Vcc_Ext_val > 50)
      {
        digitalWrite(ActivateLoad, HIGH);
        LoadActivated = true;

      }
      else if (Vcc_Ext_val < 30)
      {
        digitalWrite(ActivateLoad, LOW);
        LoadActivated = false;
      }
      if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10)|| (USB_DM_VAL < 10))
      {
        PulseCurrentMillis = millis();
        if (FirstPulse == true)
        {
        digitalWrite(RedIntLED, StateLEDON);
        FirstPulse = false;
        }
        if (PulseCurrentMillis - PulseLastMillis >= PulseInterval)
        {
          PulseLastMillis = PulseCurrentMillis;
          if (LEDState == StateLEDON)
          {
            LEDState = StateLEDOFF;
          }
          else
          {
            LEDState = StateLEDON;
          }
        }
        digitalWrite(GreenIntLED, StateLEDOFF);
        digitalWrite(RedIntLED, LEDState);
      }
      else
      {
        digitalWrite(GreenIntLED, StateLEDON);
      }
      break;

body:
Look at one of the timer libraries such as [SimpleTimer][1]. It handles the timing for you and calls a routine you specify at the appropriate time. Your code just has to call its run() function frequently - once in every loop() iteration is typical.

Update:

Either library should work for you; neither should disturb the hardware timers or millis(), which depends on them. Try one of the timer example programs, blinking two leds at different rates for example, and expand or adapt from there.

  [1]: http://playground.arduino.cc/Code/SimpleTimer


body:
When you turn on the led, record the time.

After that, turn off the led if

1. The led is on and

2. Sufficient time has passed.

edit: this is what I would do.

    //detect if sufficient time has passed
    //1. turn on the led on button high -> low transition
    //2. turn off the led after certain time (LED_DLY)
    uint8_t led_ctrl(void) {
     static uint32_t led_timeoff=0;        //time to turn the led off
     uint32_t time_now = millis();        //take time now

     //if sufficient delay has passed, turn the led off
     if (isLED_ON() && (time_now >= led_timeoff)) {    //if led is already on
      LED_OFF();            //turn off the led
     }

     //if the button has experienced a the falling edge, turn on the led and set up the time to turn the led off
     if (btn_pressed()) {
      LED_ON();            //turn on the led
      led_timeoff = time_now + LED_DLY;      //set up the time to turn off the led
     }

    }

it is almost a literal implementation of what I wrote above.

here is the code in action, responding to button's falling edge with a 150ms delay turn off for the led: the button is on D12 and the led on D8.

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

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

fairly straight forward, isn't it?


body:
I have made it work now.

The working code is as following, if anyone else gets the same issue.

    case microUSB:
      if ((Vcc_Ext_val > 50) && (USB_DP_VAL > 10) && (USB_DM_VAL > 10) && (digitalRead(RedIntLED) == StateLEDON))
      {
        if (FirstStart == true)
        {
          StartMillis = millis();
          FirstStart = false;
        }
        PulseCurrentMillis = millis();
        if ((PulseCurrentMillis - StartMillis >= PulseInterval) && (digitalRead(RedIntLED) == StateLEDON))
          {
            PulseLastMillis = PulseCurrentMillis;
            digitalWrite(RedIntLED, StateLEDOFF);
          }
      }
      if (Vcc_Ext_val > 50)
      {
        digitalWrite(ActivateLoad, HIGH);
        LoadActivated = true;

      }
      else if (Vcc_Ext_val < 30)
      {
        digitalWrite(ActivateLoad, LOW);
        LoadActivated = false;
      }
       if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10) || (USB_DM_VAL < 10))
        {
          FirstStart = true;
          digitalWrite(GreenIntLED, StateLEDOFF);
          digitalWrite(RedIntLED, StateLEDON);
        }
        else
        {
          digitalWrite(GreenIntLED, StateLEDON);
        }
      break;


message:
Can i burn an Arduino sketch .hex directly using USBASP?

I am unable to upload sketches to my Arduino Uno board using the upload option in the IDE. I have done quite a few tests to find the reason but everything seems to be working fine when tested separately. I found that I can program the ATMega328 board when placed on a breadboard using an USBASP progammer and avrdude. So will it work if I burn the .hex generated in Arduino IDE using avrdude and USBASP by placing the ATMega on a breadboard? I would then want to replace the IC on the UNO board back for my application. Thanks for your time and help in advance.

body:
Sure you can - but you don't even need to remove the chip from the Uno.

The 6 pin header at the end of the board (used for SPI) is also the ISP header for the main chip. Just plug your USBASP into there (you can get adaptors for it for $0.99 off eBay) and program it direct.

I think there's even an option in the IDE's menu to select the USBASP as the programmer (or there used to be on earlier versions).


message:
Problem uploading to board

avrdude: stk500_getsyn(): not in sync_resp=0*00
    avrdude: stk500_disable: protocol error, expect=0*14,resp=0*51

These are the errors occurring when I am trying to upload to the board.
I've tried all the suggestions that suggested in this. When I am trying to burn the bootloader the same error is showing.

body:
I don't know if I got the exact error (maybe another sync error), but what helped in my case (in this order, try again every time):

- Reinsert the USB cable
- Use a different (shorter) USB cable
- Put the USB cable in another USB port
- Restart the Arduino IDE
- Restart the computer
- Reinstall the Arduino IDE
- Go to device drivers (control panel), check for COM ports, remove Arduino and reinstall


message:
is it possible to write two threads in arduino & switch between data & AT command mode dynamically?

I need to recieve data from a android phone and also estimate distance of phone from the HC 05 module , So i want to write two threads or functions. In one part i want recieve data from android phone store it in a variable and in other enter AT command mode to see RSSI of the phone.

body:
You can switch between command and "online" modes, but you cannot use both at once. While in command mode you can't be receiving data, and while in online mode you can't be sending commands.

You would have to periodically switch between the two in your program at a time when you know you won't be receiving data (or you don't mind losing that bit of data).

And no, the Arduino doesn't have the concept of threads. There are a number of libraries that do emulate threads to a certain extent, but they are (usually) cooperative multi-tasking (one "thread" has to manually "yield" to another) and as such are pretty pointless, since you can get the same effect with a decent finite state machine.


body:
Receiving serial characters is partially done in hardware and partially in the Arduino firmware.
The only thing you need to do here is:
- check if you've received a full message.
- handle the message (if a full message has been received)

For the ultrasonic sensor, you'll have to:
- Start a measurement.
- wait for a response.
- convert the response.

You can't do these exactly at the same time. But none of these will/should take up 100% of your "processor time".
So we'll have to "share the time" of your microcontroller.

Though, timing may be critical in some of these parts. So for this, we will have to make sure that there is no delay in, for example, handling the ultrasonic sensor.
(I'm not sure, and can't check since I'm on my phone, if Arduino uses interrupts for receiving characters from serial, which may mess up my logic below if these interrupts aren't prioritized well or the time an arduino RX interrupt takes so long it will influence your ultrasonic sensor readings significantly.)

But, you'll want to handle the ultrasonic responses as fast as possible, since this timing indicates the distance between an object. And you don't want to use processor speed while waiting for the result.We will probably want to use an interrupt here (if polling doesn't give a good enough result). See the Arduino page in interrupts, or use a HC-sr04 library that is non-blocking or interrupt/event-based

Now you can, if the ultrasonic sensor doesn't require any attention. Check and handle your serial buffer. (I believe there even is an option in the Arduino library to set a callback for a line end).

By doing the above. You can be sure that your ultrasonic readings are stable. And as long as the ultrasonic routines don't consume all processing time (which they shouldn't), you'll have time to handle your serial messages.
Also have a look at state machines and non-blocking code, to avoid making your "subroutines" block eachothers execution while waiting for a result.


message:
smaller program bigger sketch

I'm working on a program composed by several classes.

I reduced the size of a single class of (more or less) one hundred lines (4kb of stuff)

I expected a smaller sketch but surprisingly it is increased in size (few bytes).

How is it possible?It's something about the compiler?

body:
A compiler translates c/cpp to target assembly language.

To keep it short, some c/cpp language statements or keywords can be used to shorten the code (in c/cpp)... but the mechanics behind all that to translate to assembly can generate more instructions than you thought.

It would maybe be easier to explain if you put some example...


message:
Sending serial bits in arduino

I am a newbie in Arduino and serial communication. I am working on a project that use Arduino to send data bits to an actuator using RS232 communication protocol. In order to control the actuator, an instruction consists of 6 bytes must be sent with 9600 baud, no hand shaking, 8N1 format.

Here are the instructions:
Byte 1 - Device, Byte 2 - Command, Byte 3 - Data(LSB), Byte 4 - Data, Byte 5 - Data, Byte 6 - Data(MSB)

For example to send 1, 20, 1, 1, 0, 0 (Move the actuator to absolute position of 257 microsteps)
![code](https://holland.pk/uptow/i4/1565d661d79e1d3843a4811763298c2b.jpg)
This is my draft code. How can I send start and stop bit? I am confused on sending start and stop bit. The Serial.write() is sending binary data as a byte. Does it mean that I write Serial.write(20), the compiler will send the data in 00010100 binary format? I am quite frustrated with serial communication.

body:
The start and stop bit are already included as part of the UART protocol. When you send a byte it first sends the start bit, then the byte, then the stop bit. You don't need to do anything to make those bits send.

`20` is actually sent as `0001010001`

So your code will just be a series of `Serial.write()` calls for each byte you want to send.

    Serial.write(1);
    Serial.write(20);
    Serial.write(1);
    Serial.write(1);
    Serial.write(0);
    Serial.write(0);

Or as an array:

    uint8_t data[6] = {1, 20, 1, 1, 0, 0};
    Serial.write(data, 6);


body:
Read the language reference: https://www.arduino.cc/en/Reference/Serial
..and for write(): https://www.arduino.cc/en/Serial/Write
....notice that it "writes" the bytes or buffers you define. You have already defined the baud rate and started the serial channel, then all you need to do is pass the characters or strings you want to send to the write function.

In your application it may be best to build a 6 character command string and send it all at once as a string. You must then remember that With "write" you are responsible for "writing" the cr and lf which is probably needed as a command terminator in your receiving device.

For your kind of application it may also be possible to use "println" which appends a cr/lf automatically for you. It depends on your protocol.


message:
'setup' does not name a type?

Was trying to work some code that I found online to suit my needs and it continues to show the same error **'setup' does not name a type**. I have tried setting it to void, Void as well as rewriting the code but still the same issue arises and I was wondering how to fix this issue.

This program will at some point compile data from 3 different sensors and do its various calculations within these separate loops and print to serial in a table that can then be saved or exported. The only sensor attached at the moment is a ultrasonic sensor that measures the distance it is from a surface. (last 2 groups of code have a basic print function just so the loop is occupied)

Here is the code:

    #include <CapacitiveSensor.h>

    long timeCounter; // milliseconds counter
    long timePassed; // The actual milliseconds time
    int trigPin = 2;
    int echoPin = 3;

    long delay1 = 10;    // ms for cycle of event 1
    long delay2 = 5;     // ms for cycle of event 2
    long delay3 = 25;    // ms for cycle of event 3
    long delay4 = 10;

    // Counters for the number of triggered events before the
    // corresponding event starts
    int countEvent1, countEvent2, countEvent3, countEvent4;

    int TRIGGER = 5; // ms to trigger the milliseconds timer

    int MAX1 = 2; // Number or triggered milliseconds to start event1
    int MAX2 = 1; // Number or triggered milliseconds to start event2
    int MAX3 = 5; // Number or triggered milliseconds to start event3
    int MAX4 = 2;

    // Initialisation
    setup {
         timeCounter = millis(); // read the actual internal time
         timePassed = 0; // we start with no time passed

         countEvent1 = 0;
         countEvent2 = 0;
         countEvent3 = 0;
         countEvent4 = 0;
    }

    // Infinite cycle
    loop() {

         // Read the actual time
         timePassed = millis() - timeCounter;
         // The smallest unit of time that should trigger an event is for event 2 (5 ms)
         // so our trigger should count this smaller unit

         // Check if the time passed after last reading is the trigger time
         if(timePassed >= TRIGGER) {
              if(++countEvent1 == MAX1){
                   // Reset the trigger and start the event
                   event1();
                   countEvent1 = 0;
              } // Event 1

              // It's time to manage the events
              if(++countEvent2 == MAX2){
                   // Reset the trigger and start the event
                   event2();
                   countEvent2 = 0;
              } // Event2

              // It's time to manage the events
              if(++countEvent3 == MAX3){
                   // Reset the trigger and start the event
                   event3();
                   countEvent3 = 0;
              } // Event3

              if(++countEvent4 == MAX4){
                   // Reset the trigger and start the event
                   event4();
                   countEvent4 = 0;
              } // Event4

         } // Trigger

    } // LOOP

    // ============ Event functions ==============

    event1() {
      long duration, distance;
      digitalWrite(trigPin,HIGH);
      delay(100);
      digitalWrite(trigPin, LOW);
      duration=pulseIn(echoPin, HIGH);
      distance =(duration/2)/29.1;
    }

    event2() {
    Serial.print("work")
    }

    event3() {
    Serial.print("work")
    }

I am very new to coding so there will be stupid mistakes hidden amongst this I can guarantee it.

body:
Function declarations start with a type:

    void setup() {

    }

    void loop() {

    }

void means the function doesn't return a value.


body:
Yeah you never defined setup or loop which need the void before them.

    void setup(){

    }

    void loop(){

    }


body:
All your functions (including setup and loop) need a type as part of the declaration. This for example:

    event2() {
    Serial.print("work")
    }

Should be:

    void event2() {
      Serial.print("work");
      }

Note also the semicolon after the `Serial.print` function call.

I have [a page that explains the basics](https://www.gammon.com.au/forum/?id=13900).

On that page is a diagram that breaks down what a function declaration looks like:

[![Function definitions][1]][1]

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


body:
You have a problem with function definition. Let me explain with an example.

    int kPinLed = 8; // LED - Pin 8

    void setup()
    {
      pinMode(kPinLed, OUTPUT); // LED as output
    }

    void loop()
    {
      ledFun(); //Create LED Function
    }

    //Now write function's code with type, here "void"

    void ledFun()
    {
      digitalWrite(kPinLed, HIGH); //LED ON
      delay(1000);
      digitalWrite(kPinLed, LOW);  //LED OFF
      delay(1000);
    }

Same things you have to do with your code. Just write properly function's type. I hope this will help you.


body:
> error 'setup' does not name a type. I have tried setting it to void

the correct typing of it is this:

    void setup(void) {
    ...
    }

    void loop(void) {
    ...
    }


message:
Swapping 5V and GND for a 2 wire motor

I have a 2-wire brushed DC motor in a servo housing which either pushes left or right (and "center" when unplugged).

To push to one side I connect a wire to 5V and the other to GND, to push to the other side I just need to swap the wires.

How can I achieve this with the arduino without any physical rewiring?

body: What you want is called a H-bridge, and it is what a standard Arduino motor shield does.


body:
I think you need arduino motor shield.

[![Shield][1]][1]

[Click Here][2]

Just click on above link, you find a good tutorial about arduino motor shield. I hope it might be helpful.

  [1]: https://i.stack.imgur.com/1Bt4R.jpg
  [2]: http://playground.arduino.cc/Main/AdafruitMotorShield


message:
How can I split a string into multiple parts?

I currently gather a string via bluetooth to my arduino and the string only has 5 different letters. "HELLO". I now wish to store these individual letters in a string on their own. Right now i have this code:

First I create a single string:

    String readString;

Then I read my BTLEserial which is where I get the value that is being sent to the arduino and i store it in my string:

    char c = BTLEserial.read();
    readString += c;

`readString` now has the value "HELLO". Now i want to split it and what I have tried is to do it like this:

    String stringOne = readString.substring (0,1); //H
    String stringTwo = readString.substring (1,2); //E
    String stringThree = readString.substring (2,3); //L
    String stringFour = readString.substring (3,4); //L
    String stringFive = readString.substring (4,5); //O

But with this i do not get the correct values in each string.

Appreciate every help I can get! :)

body:
String are the not the recommended way to use with Arduino although try using single parameter instead of two like substring(1) and let me know

    char data[5];
    for(int i=0;i <5 ;i++)
    {
     data[i]=Serial.read();
    }
    char data1=data[0];
    char data2=data[1];

so on and so forth ..


body:
I think it would be easier if you used a char array. Here's some sample code.

    char recievedData[100]
    int numChars = 0
    //Now we are in the receiving loop
    recievedData[numChars] = BLTEserial.read()
    numChars++

Now that you have a character array with all of the members, you can simply use the numChars variable to figure out how much you got from the serial buffer (for example, using it as the upper limit for a for loop).


body:
An array is 0 indexed, which means that number 5 is out of index. "Hello" should be index valued 0-4 and not 0-5.

Here is a better code to try out:

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

    void loop() {

 String recivedMessage = "";

 // Read
 while (Serial.available())
 {
  recivedMessage += Serial.read();
 }

 // Print debug
 Serial.print("recivedMessage: ");
 Serial.println(recivedMessage);

 //// Uncomment the row under if you are not sure that the splitting is working
 // recivedMessage = "Hello";

 // Split
 char first = recivedMessage.substring(0, 1)[0]; // H
 char second = recivedMessage.substring(1, 2)[0]; // E
 char third = recivedMessage.substring(2, 3)[0]; // L
 char forth = recivedMessage.substring(3, 4)[0]; // L
 char fifth = recivedMessage.substring(4)[0];  // 0

 // Print debug
 Serial.print("Cut message: ");
 Serial.println(first);
 Serial.println(second);
 Serial.println(third);
 Serial.println(forth);
 Serial.println(fifth);
}


message:
Using an Arduino and multiplexer for writing to multiple outputs

I'm attempting to use the multiplexer setup in this [article][1] with my Arduino Uno to control the output of LED's, as a way to fully understand the principles of multiplexing.

I'm working to modify the code in the article to switch from reading potentiometer values to writing voltage values to the LED's.

Below is the modified sketch; the biggest modified change is the loop in the `writeMux` function:

    //Mux control pins
    int s0 = 8;
    int s1 = 9;
    int s2 = 10;
    int s3 = 11;

    //Mux in "SIG" pin
    int SIG_pin = 3;

    //Voltage value to write to the LEDs
    int testValue = 255;

    void setup(){
      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);
      pinMode(SIG_pin, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
    }

    void loop(){
      for(int i = 0; i < 9 ; i ++){
        delay(1000);
        writeMux(i);
      }
    }

    int writeMux(int channel){
      int controlPin[] = {s0, s1, s2, s3};

      int muxChannel[10][4]={
        {0,0,0,0}, //channel 0
        {1,0,0,0}, //channel 1
        {0,1,0,0}, //channel 2
        {1,1,0,0}, //channel 3
        {0,0,1,0}, //channel 4
        {1,0,1,0}, //channel 5
        {0,1,1,0}, //channel 6
        {1,1,1,0}, //channel 7
        {0,0,0,1}, //channel 8
        {1,0,0,1}, //channel 9
    //    {0,1,0,1}, //channel 10
    //    {1,1,0,1}, //channel 11
    //    {0,0,1,1}, //channel 12
    //    {1,0,1,1}, //channel 13
    //    {0,1,1,1}, //channel 14
    //    {1,1,1,1}  //channel 15
      };

      //loop through the 4 sig
      for(int i = 0; i < 4; i ++){
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }

      //read the value at the SIG pin
      analogWrite(testValue, SIG_pin);

      //return the value
      return 0;
    }

Below is a photo of my circuit:

However, none of the LED's light up.

I'm fairly certain that this is more of a problem with the code rather than the circuit...any advice is appreciated!

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

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

  [1]: http://bildr.org/2011/02/cd74hc4067-arduino/
  [2]: https://i.stack.imgur.com/Jac4a.jpg
  [3]: https://i.stack.imgur.com/OLidG.jpg

body:
According to the [analogWrite() documentation][1], apparently the trouble are that you have swapped the args.

The syntax are `analogWrite(pin, value)`, so, the piece

    //read the value at the SIG pin
    analogWrite(testValue, SIG_pin);

may work if you simply change to

    //read the value at the SIG pin
    analogWrite(SIG_pin, testValue);

That with respect to code, and i hope it helps you. At the other hand, the circuit, may be a bit dangerous (and can damage the Arduino or the mux) to use LEDs without a current limiter series resistor (330 - 1K Ohm would be nice values, 1/4 W). At least, by a light sight in a [datasheet of the CD74HC4067][2], shows max currents of +/- 25 mA per pin. Similar currents can be driven by the Arduino (Atmega 328P).

So, all depends on the internal construction of the 4067, if are a transparent mux, maybe just with a single resistance in the `SIG_pin` in that range of resistances, would be fine.

**Edit - Some Circuit Troubleshooting**

There are some other little tests that you can do after that change in code:

1. Open the wire that goes from the Arduino to the common of the mux, then place at the output of the same Arduino pin, a LED-resistor series. Then change in program only the value of `testvalue` at the beginning of the code and check if the led changes their intensity according to that. That would be an Ok for that pin of the Arduino.
2. Reply the previous step to each of the channel pins. According to the code, you should see an increasing 1 Hz, 4 bits counter (rather, a BCD counter) in thet formed 4 led array. That would be an OK for the channel selection pins.
3. Remove the leds and connect back the opened lines.

Any fail in steps 1 or 2 may indicate that the pin are damaged but you can use another analog pin and other pins for the channels respectively. But if at step 3 it doesn't works, may be a damaged 4067 or a little hidden bad connection...

  [1]: https://www.arduino.cc/en/Reference/analogWrite
  [2]: https://www.sparkfun.com/datasheets/IC/CD74HC4067.pdf


message:
Help Led matix isn't lighting up correctly Is it a Hardware or software issue?

I am trying to reverse engineer the project from this video: https://youtu.be/zc1zbwheyE0?t=50s.

From the video a visible 10 wires are going from the LEDs to the Arduino mega, i am assuming that they are wired in a 5x5 matrix (5 rows, 5 columns) given that there are 25 keys on the Midi controller so there most be 25 LEDs.
I reconstructed the project the best a could from observing the video, but my issue is when i press 3 keys 5 LEDs light up unlike in the original video where 3 keys are pressed and 3 LEDs light up(as seen @ 0:50 of the video).
This is the issue i am having : https://i.stack.imgur.com/ppLJn.jpg.
I am thinking the issue is related to how i have my LEDs wired, but my LEDs are wired exactly the same as in the video. isn't it ? is there something i might have missed? How is the project in the video able to light up 3 LEDs without having an issue with extra LEDs lighting up in their matrix? how can i fix my circuit to replicate the video?

Here is some of my coed for turning on an LED when a key is pressed:

    <include MIDI.h>

    MIDI_CREATE_DEFAULT_INSTANCE();

    byte anodes[5] = {30, 32, 34, 36,38};

    byte cathodes[5] = {31, 33, 35, 37,39};

    byte data1 = 0;

    void setPinTo5V(byte pin) //set a pin given to this function to a 5V voltage source

    {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, HIGH);
    }

    void setPinToGND(byte pin) //set a pin given to this function to a GROUND (GND pin)
    {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, LOW);
    }

    void loop() {
        MIDI.read();
    }

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
    {
        data1 = MIDI.getData1();

        if (data1==48){//C3
            setPinTo5V(anodes[0]);//set pin 30 to 5V
            setPinToGND(cathodes[0]);//set pin 31 to GND

            delay(1); //do nothing for 1 ms
        } //this is done for all 25 keys

    }

 any help would be appreciated Thanks.

body:
Your code is incomplete, so it's impossible to be sure, but I suspect your problem is with the way you are lighting the LEDs in the matrix.

Think about it conceptually: your LEDs are on the junctions of rows (anodes) and columns (cathodes).  To light an LED you make the row high and the column low.

Let's call the rows R1, R2, R3, R4 and R5, and the columsn C1...C5.

Let's say the first LED you want to light is at the junction of R1 and C1.  You make R1 high and C1 low.

Now you want to light an LED on the junction of R3 and C3.  You make R3 high and C3 low.

What happens?  Four lights light up.  Why?  You have R1 and R3 high, and C1 and C3 low.  The circuit doesn't "know" that you want only two LEDs lit: it will light R1C1, R1C3, R3C1 and R3C3.

What is the solution?  Remember which LEDs you want lit.  Cycle through the matrix and deal with one row at a time: light all the LEDs you want lit in that row.  Then move to the next row and repeat.  Do this very fast.  Your LEDs will be flashing, but if you write your code properly they'll do it so fast you won't be able to see it.


body:
This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.

#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define LedR 3   //

#define LedC 4 //pin for each led

byte data1 = 0;

unsigned long previousMillisR[2]; //[x] = number of leds

unsigned long previousMillisC[2]; //[x] = number of leds

int Status [25];

void setup() {

 MIDI.begin(MIDI_CHANNEL_OMNI);

MIDI.setHandleNoteOn(MyHandleNoteOn);

MIDI.setHandleNoteOff(MyHandleNoteOff);

  pinMode(LedR, OUTPUT);

  pinMode(LedC, OUTPUT);

}

void loop() {

  MIDI.read();

//BlinkLedR(LedR,2000, 0);   //BlinkLed( which led, interval, one of the
stored prevMillis

//BlinkLedC(LedC, 10, 0);  //last parameters must be different for each
led

}

void BlinkLedR (int led, int interval, int array){

  //(long) can be omitted if you dont plan to blink led for very long time I think

   if (((long)millis() - previousMillisR[array]) >= interval){

    previousMillisR[array]= millis(); //stores the millis value in the

selected array

digitalWrite(led, !digitalRead(led)); //changes led state

  }

 }

 void BlinkLedC (int led, int interval, int array){

  //(long) can be omitted if you dont plan to blink led for very long
time I think

   if (((long)millis() - previousMillisC[array]) >= interval){

    previousMillisC[array]= millis(); //stores the millis value in the

selected array

    digitalWrite(led, !digitalRead(led)); //changes led state
  }

 }

 void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

 data1 = MIDI.getData1();

 if (data1==48){//C3

  Status[0]=1;

while(Status[0]==1) {

 BlinkLedR(LedR, 10, 0);   //BlinkLed( which led, interval, one of the

stored prevMillis

 BlinkLedC(LedC, 1, 0);  //last parameters must be different for each led

 if (Status==!1){

  break;

 }

}

 }

 }

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {

  data1 = MIDI.getData1();

if (data1==48){//C3

Status[0]=0;

 }

}


message:
Is there any good working MODBUS TCP master library available for Arduino?

I would like to connect with Fronius solar inverter through MODBUS TCP with Arduino to READ and WRITE register values only. I want to set the Arduino as master and the Inverter as slave. I want to use only two functions "Read Holding Registers" and "Write Single Holding Register" function code '3' and function code '6' respectively. Is there any good and working library available for these? And also an example.

body:
Check out the library [Modbus-TCP](https://github.com/goddland16/Modbus-TCP) on Github. It has the facility for all the function codes as asked. It has provision for Wiznet W5100 and ENC28J60 Ethernet IC. All tested with Arduino Mega. See the well documented [example code for the Wiznet module][1] in the library.

For detailed knowledge about the library, read the [index.html][2] inside the [doc folder][3] of the library.

Here is an example code explaining a few function codes for the Arduino Mega and a W5100 module.

    /*
      This is Modbus test code to demonstrate all the Modbus functions with
      with Ethernet IC WIZNET W5100

      ModbusTCP is free software: you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation, either version 3 of the License, or
      (at your option) any later version.

      ModbusTCP is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with ModbusTCP.  If not, see <http://www.gnu.org/licenses/>.

      Adopted from ModbusMaster for RTU over RS-485 by Doc Walker
      Modified by Narendra Dehury for TCP.
      copyright @ phoenixrobotix.com

    */
    #define WIZNET_W5100 1

    unsigned int param_value_int[7];
    #include <Ethernet.h>

    IPAddress ModbusDeviceIP(10, 10, 108, 211);  // Put IP Address of PLC here
    IPAddress moduleIPAddress(10, 10, 108, 23);  // Assign Anything other than the PLC IP Address

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1 };

    #include <ModbusTCP.h>

    ModbusTCP node(1);                            // Unit Identifier.

    void setup()
    {

      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);                      // To disable slave select for SD card; depricated.

      Serial.begin(9600);
      delay(1000);
      Ethernet.begin(mac, moduleIPAddress);
      node.setServerIPAddress(ModbusDeviceIP);
      delay(6000);                                // To provide sufficient time to initialize.

    }

    void loop()
    {
      uint8_t result;

      node.setTransactionID(random(100));           // Not necessary; but good to distinguish each frame individually.
      result = node.readHoldingRegisters(1, 12);    // Read Holding Registers

      Serial.println(result, HEX);
      if(result != 0)
      {
        Serial.println("TimeOut");

        delay(6000);
      }

      int len = node.getResponseBufferLength();
      Serial.println("Response Length: " + String(len));// See the length of data packet received.
      for (byte j = 0; j < len; j++)
      {
        Serial.print(node.getResponseBuffer(j));       // Inspect the data.
        Serial.print(" ");
      }
      Serial.println();
      node.clearResponseBuffer();
      delay(100);

      node.writeSingleRegister(5, 3);                  // Write single register
      Serial.println(result, HEX);
      delay(500);

      for (byte i = 0; i < 5; i++)
      {
        node.setTransmitBuffer(i, (i+100));
      }
      node.writeMultipleRegisters(2, 5);               // Write multiple register
      Serial.println(result, HEX);
      delay(500);

      node.writeSingleCoil(20, 1);                     // Write Single coil
      delay(500);

      node.setTransmitBuffer(0, 0b1010101001010101);

      node.writeMultipleCoils(20, 16);                 // Write multiple coils
      delay(500);
      result = node.readCoils(20, 18);
      len = node.getResponseBufferLength();
      Serial.println("Response Length: " + String(len));
      Serial.println(node.getResponseBuffer(0), BIN);

      node.clearResponseBuffer();
      delay(5000);
    }

  [1]: https://github.com/goddland16/Modbus-TCP/blob/master/examples/modbusTCPlib_w5100/modbusTCPlib_w5100.ino
  [2]: https://github.com/goddland16/Modbus-TCP/blob/master/doc/html/index.html
  [3]: https://github.com/goddland16/Modbus-TCP/tree/master/doc


message:
Programming other Atmel chips(excluding Atmega 328 and 168)

How can we program any other chips of Atmel using Arduino Nano as a Arduino ISP ? Excluding the Atmega 328 and 168.

body:
Since you say:
>Excluding the Atmega 328 and 168.

I'm going to assume that you already understand the general process for using your Nano as an ISP.

The Arduino IDE includes the **Arduino AVR Boards** hardware package which provides hardware definitions for specific configurations of:

- ATmega328P
- ATmega168
- ATmega2560
- ATmega1280
- ATmega32U4
- ATmega8

If your hardware matches the configuration of one of the Arduino AVR Boards then you only need to select that board from the **Tools > Board** menu.

It is also possible to program many other Atmel microcontrollers or alternative configurations of the microcontrollers included with the Arduino AVR Boards hardware package with your Nano but you will first need to install the 3rd party hardware package that contains the definitions for the part you want to program. You can find a fairly comprehensive list of these hardware packages here:

https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls

Once you have found the hardware package that contains the necessary definitions you will need to install it. For this you have two options:

### Boards Manager
The easiest installation option Boards Manager. Most Arduino hardware packages allow this type of installation (and certainly all of them on the above list):

- Copy the Boards Manager package index URL.
- File > Preferences > Additional Boards Manager URLs > paste URL > OK
- Tools > Board > Boards Manager
- Wait for downloads to complete.
- Scroll down until you see the entry for the hardware package you want to install. Click on it.
- Click "Install".
- Wait for installation to finish.
- Click "Close"

### Manual Installation
Another option is to manually install the hardware package. For a simple package this would involve:

- Download the hardware package
- Copy the contents of the downloaded file to {sketchbook folder}/hardware. You can find the location of your sketchbook folder at **File > Preferences > Sketchbook location**.
- Restart the Arduino IDE if it's running

After installation you will only need to select the correct board from the **Tools > Boards** menu. In some cases selecting a board may also add custom menu items to the Tools menu that can be used to adjust the configuration of the board (part, clock, BOD, etc.).

>using Arduino Nano as a Arduino ISP

Note that the correct term is **Arduino as ISP**. There is a programmer named ArduinoISP that is completely different from the Arduino as ISP. The confusion is increased by the sketch used on the Arduino as ISP being named ArduinoISP.


message:
State change in Arduino Using Adafruit display

if(menustate == 1310){menustate ++;Serial.println("Execution:");Serial.println(menustate);}
                 if(menustate == 1311){menustate ++;if (hr==0) menustate ++;else{aCount++;gpArray[aCount]=hr;}Serial.println("Execution GP:");Serial.println(menustate);}
                 if(menustate == 1312){menustate ++;if (minu==0) menustate ++;else{aCount++;gpArray[aCount]=minu;}Serial.println("Execution GP:");Serial.println(menustate);}
                 if(menustate == 1313){menustate ++;if (seco==0) menustate ++;else{aCount++;gpArray[aCount]=seco;}Serial.println("Execution GP:");Serial.println(menustate);}
                 if(menustate == 1314){menustate ++;if (dates==0) menustate ++;else{aCount++;gpArray[aCount]=dates;}Serial.println("Execution GP:");Serial.println(menustate);}
                 if(menustate == 1315){menustate ++;if (months==0) menustate ++;else{aCount++;gpArray[aCount]=years;}Serial.println("Execution GP:");Serial.println(menustate);}
                 if(menustate == 1316){menustate ++;if (years==0) menustate ++;else{aCount++;gpArray[aCount]=years;}}
                 if(menustate == 1320){menustate ++;}

I am trying to get different time inputs from users by using the menustate value , but here in this code the menustate starts from 1311 and without pressing anything the state goes directly to 1320 .and i cant get to the inbetween states

body:
You should use a switch statement ... than after the switch statement you get the in between states:

    // conditional loop
    {

        // prepare for switch (if something is needed)

        switch (menustate)
        {
            case 1310:
                menustate ++;
                Serial.println("Execution:");Serial.println(menustate);
                break;
            case 1311:
                menustate ++;
                if (hr==0)
                     menustate ++;
                else
                {
                    aCount++;
                    gpArray[aCount]=hr;
                }
                Serial.println("Execution GP:");Serial.println(menustate);
            break;

            case 1312:
                // ...

            default:
                // You can do here things with all other values
        }

        // Here you have the in between states available
    }

You should put this switch statement in some conditional loop (like until an end state is reached.


message:
Arduino board with built-in Bluetooth

I would like to find an Arduino with built-in Bluetooth.
I know about the HC-06, the shields and the other Bluetooth modules, but i would like to have built in Bluetooth for eliminating the risk for miscommunication on the serial port.

The official Arduino foundation did produce an board but it's retired now.

body:
There is this board called Bluno
Its an Arduino UNO Based board with built in Bluetooth 4.0

[Bluno - An Arduino Bluetooth 4.0 (BLE) Board][1]

[![Bluno - An Arduino Bluetooth 4.0 (BLE) Board][2]][2]

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

  [1]: https://www.dfrobot.com/product-1044.html
  [2]: https://i.stack.imgur.com/l2Bv8.jpg
  [3]: https://i.stack.imgur.com/gi67A.jpg