text:
7805 powered Atmega328 Stops working when input of 7805 exceeds 7volts
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).

Have you added capacitors ? Reset problems may be attributed to inadequate current supply. Refer : http://www.circuitdiagram.org/images/12-to-5v-converter-circuit.gif

Maybe thermal protection? Voltage drop on the regulator is 2 volts if you have 7V input and that means  2V * 0.75A = 1.5W  turned into the heat. That means heatsink might be needed to work properly.

i have uploaded the circuit diagram, please take a look, and i will try all the hints mentioned above..

Do you have a phobia of capacitors? I can see at least 8 that are conspicuous by their absence - maybe more. You seem to have an aversion to diodes as well.

yeah, its embarrassing , i didnt think that capacitors will be that much important. Anyways i am gonna try it again after attaching the capacitors and diodes.

If you are simulating (vs. real parts on a breadboard or PCB), how a BC547  works vs a BC337 probably depends on what part suffixes you specify: BC547A, B, or C vs BC337-16, -25, or -40.  BC547C have higher gain at 100 mA collector current than BC337-16 and -25, but lower than BC337-40.  With real parts, it depends on which you buy and use.

okk, got you , but my new schematic is consuming all total of 840ma (with two output & relays) when they are turned on. Now if i use all six of them it  will consume more than 1amps, any ways to reduce them??? may be increasing the resistances or something??

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.

thaks for your reply, i tried using 220E resistors, but its not working, 56E seems to work fine in the sketches. Also i connected 100E at the sketch, output LED, is glowing , but dimmed, what should i do?

@SHILADITYADEY, do you have an oscilloscope?  If so, check if regulator oscillation (as mentioned by Majenko) is an issue.  And/or, use a DVM to check output voltages on several IO pins, on load and off.  Also detach an isolator from its IO line, and drive the isolator with different voltages to test if the isolators+relays work by themselves.  Also detach 4 isolators+relays from the circuit and see if you have enough current to drive the remaining 2 (to check if problem is just too much load, or some wiring error, or a design problem).

Also, a 'glowing , but dimmed' LED either is at low current or is turning on/off rapidly.  Easy to check with a scope, not so easy with a DVM; possibly detectable by sweeping it across your field of vision.  Low current may be a result of high resistance (eg damaged IO lines) or low voltage.  Low voltage can be caused by shorts or low-resistance loads, or by power-supply oscillation.

gonna do it today and let you know

found out it was problem with the excessive current 817Cs are taking from controller. New modified circuit solved it. Thanku for the help.

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.

Thanks @Majenko for your help, I am gonna try it and give you feedback.. thanks again.

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.

@SHILADITYADEY Have you got your diodes the right way round?

yes i have, and i have changed the circuit. There is some issue with the modified circuit tough, please check it

@SHILADITYADEY Are you relying solely on simulations for this, or do you have an actual real physical circuit?

@SHILADITYADEY Re your new circuit: you should have a pull-down resistor on the base of Q1.

I have not implemented the new circuit physically yet, what should i do? Should I use pull down?

@SHILADITYADEY I'd get breadboarding. Simulations are all very well, but you may find that in real life with real components it behaves very differently.

So i am going to make it with pull down at base, sounds ok?

@SHILADITYADEY Without that pull down, when the opto turns off the base is left floating. 10K should be a reasonable value.

Pulldown is not doing any change in simulation, but BC337 solving it

That's because your simulation isn't real. It's lacking the noise the base would pick up from the environment while floating. You need the pulldown even if your simulation says it works. Personally I prefer an n-channel MOSFET instead of a BJT.

ok, but adding pulldown is not reducing the collector voltage, it still is at 1.8 volts

Try it in real life. I never trust simulations to get it right.

okk, I am gonna try it tonight and let you know

Hello @Majenko, I made the new schematic i had uploaded yesterday, and its working fine, right now i did it for only two outputs, gonna do it for all six of them today, also added the pulldown. Thanks for your help. Really appreciate it.


text:
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);
}
}

There can be only one loop() function, and you have two.

Two void loops are not allowed, why do you need one??

After I remove the 2nd loop,then also there is an error.

send me the code after removing the loop, and also be specific  about what you are trying to do.

“dht DHT;”: You mean DHT dht;. The syntax is type_name variable_name; and the type name is DHT (upper case).

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

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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.

It strikes me that you need to read some basic "Introduction to C programming" tutorials.

@Majenko Having basic instructions in this site could help too, even if it might not be the first go-to place to learn about arduino's. The answer provided below is clear, short and simple to understand, which is what beginners look towards.

This site is not the place for basic tutorials. There's already plenty of them around if you just google. Most of your questions can be answered by first learning the basics of the C syntax, which seems to be the information you are lacking to make sense of everything else.

"I could just look this up on google". Yes, you could.

I would recommend the Arduino on-line reference and tutorials. Please see https://www.arduino.cc/en/Guide/HomePage and explore the Learning menu.

These are reasonable questions, but Stack Exchange is not designed as a tutorial site. The intention is to ask a specific question (eg. "can I use a mousetrap to catch a rat?") and not a really general question (eg. "Please describe all the ways I can catch rats").

These are a lot of different questions. However, you can find most of the Arduino related answers in the official reference:
Arduino reference Guide
Some other answers:

how to declare variables:

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.

short, simple, understandable and easy to remember. Thank you. Quick question about something, what do you mean the limit of a "pen"?, what is a 'pen'? is there a reason why they have limits?

@Utsave: you are welcome ... and I meant pin, not pen (I updated the answer). The main reason is that it has to be mapped to a value usable for computers. In practice e.g. a voltage can be anything from 0.00000 to 5.0000 V for example. However, computers use bits/bytes and it is not useful to keep 10 significant digts. With 1024 (0-1023 values) the accuracy is good enough and 1024 is 10 bits (2 to the power 10).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
IR remote heater
I am having issues to reproduce the remote control of my heater , this is the dump of one button:
Encoding  : UNKNOWN
Code      : A32AB931 (32 bits)
Timing[23]:
     +1300, - 400     +1250, - 450     + 400, -1250     +1250, - 450
     +1250, - 450     + 400, -1250     + 400, -1300     + 400, -1250
     + 400, -1300     + 400, -1250     + 400, -1300     +1250
unsigned int  rawData[23] = {1300,400, 1250,450, 400,1250, 1250,450, 1250,450, 400,1250, 400,1300, 400,1250, 400,1300, 400,1250, 400,1300, 1250};  // UNKNOWN A32AB931

I wonder why I cant just send the raw of this data, maybe because it doesnt run at 38khz? How do I find out what is the frequency ?
It worked fine to dump data from my tv and dvr so it is not an error n my code.
Note:
Opening the remote I found a BEC5104S which doesn't really tells me what frequency runs, not even the Chinese datahsheet
This is the spectrum which confirms that is working at 38khz

what IR library are you using? they should provide such methods...

Looks like manchester encoding to me. Were you able to emulate the TV/DVR remote?

I am using IRremote, the most common one. It works for my TV and DVR. It doesnt work for my heater. I am not sure if my heater is using a different frequency.

Update the post with spectrum which confirms that is working at 38khz


text:
How can I add two different programs of bldc motor and servo motor in one so that they work in parallel?
This is for the servo motor:
#include <Servo.h> //Servo library

Servo servo_test;
//initialize a servo object for the connected servo
int angle = 0;

void setup() {
  servo_test.attach(9);
}

void loop() {
  for(angle = 0; angle < 180; angle += 1) {
    servo_test.write(angle);
    delay(15);
  }
  delay(1000);
  for(angle = 180; angle>=1; angle-=5) {
    servo_test.write(angle);
    delay(5);
  }
  delay(1000);
}

This is for the bldc motor with esc:
#include <Servo.h>

Servo esc_signal;

void setup() {
  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop() {
  esc_signal.write(55);
  delay(15);
}

First thing, read the Blink without delay Arduino tutorial, then remove all calls to delay() from your programs.

Actually, this kind of task is not inconsistent with use of blocking delays, but they need to be used with more coordination and care.

Depending on how the code is driven. The simplest would be to simply run loop1 and loop2 in the new loop.

But that would make the code execute serially not in parallel as the OP requested.  You can't do parallel on an Arduino.

Try out this code. It may be helpful.
#include <Servo.h> //Servo library

Servo servo_test;  //initialize a servo object for the connected servo
int angle = 0;

Servo esc_signal;

void setup()
{
  servo_test.attach(9);

  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop()
{
  servoFun();
  bldcFun();
}

void servoFun()
{
  for(angle = 0; angle < 180; angle += 1)
  {
      servo_test.write(angle);
      delay(15);
  }
  delay(1000);

  for(angle = 180; angle>=1; angle-=5)
  {
      servo_test.write(angle);
      delay(5);
  }
  delay(1000);
}

void bldcFun()
{
  esc_signal.write(55);
  delay(15);
}

No.  That won't do what is desired at all.


text:
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.

Also, when I put noteDurations in PROGMEM, it makes the note play forever.

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

Thank you. I did not know about this and your answer has solved my problem.


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

A_x: -0.12 A_y: 0.53 A_z: 0.83
A_x: -0.12 A_y: 0.53 A_z: 0.83
A_x: -0.12 A_y: 0.53 A_z: 0.83

Does not agree with what the smart phone receives: (See image 1)

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

float x = (float) 0.52;
float y = (float) 0.52;
float z = (float) 0.52;

I get the following results (see image 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?

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.

Thank you for the response. Using what you said as a starting point, I was able to piece together the solution.
Your statement about sprintf not having sprintf floating point support was also seen because the number recieved was really large compared to the value it should have been.
So my solution was to convert the floating point numbers to strings using dtostrf:
Ex:
dtostrf( x, 5, 2, tempx);
which I repeated for the other two variables.
Then in sprintf I changed the format to read:
sprintf(sendBuffer, "% 3s % 3s % 3s", tempx, tempy, tempz);
And it works perfectly!


text:
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);
  }
}

sensor_msg should be 5 bytes long not 4, but other than that it looks fine. What is your reception code? Maybe the bug lies there?

Actually, one thing i just noticed. The third argument of itoa should be 10 not 4. That argument is the base you want to represent the value in.

thanks, I've changed it. also tried HEX but 1 stays 1 obviously :D I will find an extra Pro Mini to test the sending of the data from a Pro Mini, will update my question afterwards

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

Ok from a Pro Mini it all works. So the code is ok and the receiver is ok. About the pins; I use PB0 to send data, so PB4 must be PB4 right? It's not possible to name it A2 but it 'should be' that pin. I will make a blinking LED on PB3 to be sure :) maybe I can have it blink analogeRead/100 or something..

Tusen tack! It was the pin number after all... PB0 for physical pin 5 and 2 for physical pin 3. Awesome! Please convert something to an answer so I can give you credits :) Now I have to stop my LED routine because it is trying to blink the value 1023 :)

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 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 and GPIO.hh.
Cheers!
Here is something that does basically the same as the sender. Cosa supports attiny and Arduino boards "out-of-the-box".


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

Better than that: Zero wires.
The Arduino has EEPROM built in.

I forgot to mention i am using Arduino Due

The Arduino due has flash memory based EEPROM emulation built in.

I searched for it... Do you mean this: https://github.com/sebnil/DueFlashStorage

Ok, maybe the due doesn't have it as default (lazy buggers, all the other larger boards do), but yes that looks like it should plug the gaping hole Arduino left in the due.


text:
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 ?

Nothing, button contacts "BOUNCE" on off for a while when activated. YOU need to either add a de-bounce circuit, or configure your code to ignore then signal for 50mS or whatever. Though I am assuming that code is even right...

You pressed it once, but you must have held it for 10 seconds. You got a "Hi" for every iteration through the loop. If you only want one message per press, then you need to remember the previous state of the switch in a variable, and then compare that to the current state.

Use one of the "bounce" libraries for Arduino or write something similar, see: https://github.com/thomasfredericks/Bounce2/wiki

it is is really "bouncing" issue, why does it last 10 seconds ?
edit: To be clear, I press the button for less than a second.

As Yasu said in his answer, your input is floating when the button is not pressed

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?

I'd like to see your schematic but from what you describe there's a pull-down connection missing

seems like you are right, my schematic was not correct, but I still needed some debouncing code to make it work smoother. thanks

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.

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

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

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;
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Ways to turn a knob with a stepper motor and an ATMEGA32u4
Hey all I am wondering what would be the best items to purchase for me to be able to turn this know (continuous) below:

As I mentioned above, I would need the stepper motor to have a continuous rotation in order for it to work with either of these dry food dispensers above.
There is a decent tutorial HERE but really doesn't give much information about how they went about building it and the mentioned Yocto-LatchedRelay seems over priced for something that can be done with just a stepper motor and some logic behind it.
I plan on using a ATMEGA32u4 with this project. I will have a total of 6 of these to control.
So any suggestions on what would be best for this type of project would be great and I look forward in hearing them! :o)
I'm just needing to know what kind of servo torque I would need in order to turn that without issues of it getting stuck mid-ways.
update
i spoke to the original creator of that web site project that i linked to and this is what they had to say about the parts that were used:

We used a  small geared Maxon motor (great but expensive hi-tech
  stuff).
motor RE-max 13 Ø13 mm, Precious Metal Brushes CLL, 1.2 Watt, with
  cables  Part-No.: 203888
gear Planetary Gearhead GP 13 A Ø13 mm, 0.02 - 0.35 Nm, Metal version
  Part-No.: 110316
Torque was on the low side: it was enough for regular cornflakes but
  clearly insufficient for muesli  :-)
The problem is not only about finding a motor with enough torque, it's
   also about finding a motor small enough to fit in the dispenser.
Here are the files. The pulleys were 3D printed, but the bracket was
  laser cut in 3mm acrylic glass.

Are there any servos that have a hole in the middle so that i can slide it over the turning rod and screw down to tighten on it in order to spin it as if you were spinning it yourself with the handle?
Something like this:

adding vibe to the hopper will lower the required torque and increase flow speed. without gearing, about any non-slim nema24 should be able to power it, even a typical nema17 should work on the fruit loops with a vibration, if my muscle memory serves us halfway correct. calculations aside, this is the sort of thing that needs experimentation.

Are there any servos that have a hole in the middle.. if there is, it would be rare and purpose made. instead, think of a coupler.

Looks to be a screw driven by a motor through a set of greats. It doesnt matter if the motor is a regular (dc) motor or a stepper.

Updated my OP with some other info if that helps.

Unfortunately it is not possible to tell you with any reasonable degree of confidence what torque is needed. It is a function of your design, materials, and luck. And it is likely that you will not be able to avoid jam at any torque level. Best to develop some jam detection techniques and unjamming strategies.

"Are there any servos that have a hole in the middle so that i can slide it over the turning rod and screw down to tighten on it in order to spin it as if you were spinning it yourself with the handle?"
That was the question, this indeed does not seem to provide an answer to that question.


text:
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?

You have no MAC address (HWaddr).  This usually means you have a driver problem.  That might be why you aren't getting an address.

This might point you in the right direction; https://communities.intel.com/thread/45455

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


text:
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?

RTM.  If you go to https://www.arduino.cc/en/Reference/HomePage and then fin Serial.Begin() https://www.arduino.cc/en/Serial/Begin you will find out what it means.  Also you see the meaning of all the function calls.

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.

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

It's worth noting that on boards with a "direct" USB connection (such as the Leonardo, Micro, Teensy, Lenny, Fubarino, etc) the baud rate is actually meaningless.


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

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

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?

There are no separate data input and output pins. So no, you can't.

The "B" is USB stands for Bus. It would be worth a read to understand how a bus is different to, for example, a serial port (where this sort of thing could work).

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.

Thanks! it's a great answer. Am I able to only transmit data without receiving? I am able to connect to both D+ and D-, but I can only output data from my board, it doesn't receive data. For example, I'll just hardcode transmit the right data at the times I know when I should transmit, so i don't need to listen to the computer?

It is up to you what data is sent over the connection and in what direction. If you don't send data between the computer and the device then there is nothing for the device to read.

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


text:
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?

Try looking at https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c
Inside that is:
/** 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
};

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


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

Double check your SPI protocol. Is the order correct? A state machine might help understand the sequencing. Also avoid Serial print in ISRs.

Some tips: 1) use ctrl-t to autoformat, 2) use { and } consequently regarding new lines, 3) use more clear variable names (also for loop iterators), 4) Write also comments in code in English, 5) motif = motif + 1 , more c is motir++;

@MichelKeijzers : Thank you for the tips, but "motif =motif +1"works in my program; i'll add a screenshot of the simulation.The display on the slave monitor is correct. I made a short circuit between the first and the second pins and i i've got " -MOTIF LU= 11000000 ".

@MikaelPatel: wrote my code based on this link [gammon.com.au/forum/?id=10892&reply=2#reply2] (Part: How to get a response from a slave) . I tested its code and it worked very well. I did not change anything except the process at the slave level: instead of adding or subtracting I read the state of the slave's pins and report it to the master.

@Saha222 Yes it is the same, but it's more 'C'  style to write motif++ instead of motif = motif + 1 ... or motif += 1; ...I'm glad you sorted out the problem.

@MichelKeijzers, Ah, ok I understood .. but it did not work yet, the display at the master level always remains incorrect.

@Saha222 That's why I made it a comment an not an answer, it doesn't solve your problem (sorry). I hope someone else has the answer.

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


text:
Accessing 3rd party driver
This is a newbie question but I'm not having much luck googling.
I'm wanting to write code that accesses an InvenSense MPU-6050 motion sensor package. I've obtained the Embedded Motion Driver 5.1.1 package. It contains example code plus a driver in the form of a directory tree of .c and .h files. The file structure of the driver is
\---msp430
    |   msp430USB.cmd
    |   msp430_clock.c
    |   msp430_clock.h
    |   msp430_i2c.c
    |   msp430_i2c.h
    |   msp430_interrupt.c
    |   msp430_interrupt.h
    |
    +---F5xx_F6xx_Core_Lib
    |       HAL_FLASH.c
    |       HAL_FLASH.h
    |       HAL_MACROS.h
    |       HAL_PMAP.c
    |       HAL_PMAP.h
    |       HAL_PMM.c
    |       HAL_PMM.h
    |       HAL_TLV.c
    |       HAL_TLV.h
    |       HAL_UCS.c
    |       HAL_UCS.h
    |
    +---USB_API
    |   +---USB_CDC_API
    |   |       UsbCdc.c
    |   |       UsbCdc.h
    |   |
    |   +---USB_Common
    |   |       defMSP430USB.h
    |   |       device.h
    |   |       dma.c
    |   |       types.h
    |   |       usb.c
    |   |       usb.h
    |   |       UsbIsr.h
    |   |
    |   +---USB_HID_API
    |   |       UsbHid.c
    |   |       UsbHid.h
    |   |       UsbHidReq.c
    |   |       UsbHidReq.h
    |   |
    |   +---USB_MSC_API
    |   |       UsbMsc.h
    |   |       UsbMscReq.c
    |   |       UsbMscReq.h
    |   |       UsbMscScsi.c
    |   |       UsbMscScsi.h
    |   |       UsbMscStateMachine.c
    |   |       UsbMscStateMachine.h
    |   |
    |   \---USB_PHDC_API
    |           UsbPHDC.c
    |           UsbPHDC.h
    |
    \---USB_eMPL
            descriptors.c
            descriptors.h
            eMPL_CDC.inf
            usbConstructs.c
            usbConstructs.h
            usbEventHandling.c
            UsbIsr.c

It's intended to be used with a development environment called "Code Composer Studio." I'm trying to use it with the stock Arduino development environment (1.8.1). I create a new sketch and copy the example code into it. It includes various files from the driver tree;
#include "USB_eMPL/descriptors.h"

#include "USB_API/USB_Common/device.h"
#include "USB_API/USB_Common/types.h"
#include "USB_API/USB_Common/usb.h"

#include "F5xx_F6xx_Core_Lib/HAL_UCS.h"
#include "F5xx_F6xx_Core_Lib/HAL_PMM.h"
#include "F5xx_F6xx_Core_Lib/HAL_FLASH.h"

#include "USB_API/USB_CDC_API/UsbCdc.h"

#include "usbConstructs.h"

I've read about how to import libraries. However this isn't a library- copying it into the "libraries" folder of the project and restarting the IDE doesn't make anything new appear in Sketch->Include Library and nor does it allow the program to compile.
Copying the driver files and subdirectories into the same folder as the sketch gets me past the first hurdle of those include files not being found, but then similar lines in files in the driver subdirectories also cause errors because the paths are wrong. The files are obviously intended to be in a central dev environment "include" directory so the search always starts from the same point in the filesystem.
I've therefore tried copying the driver files into C:\Program Files (x86)\Arduino\libraries as the folder "msp430." This added an "msp430" item to the "Include Library" menu, but compilation still fails with unresolved includes. Using trial and error, it seems that I can only get files to be recognised if they're in their own folder in 'libraries.' So by pulling all the nested subfolders out and changing the paths in the top level again gets me past the first hurdle of the include files in the top level of code, but all the includes in the driver files then fail because they're looking for files in nested directories. I could go through and remove all the path information from every #include, but then everything's in the same "namespace" and with such generic names as "types.h" I can see that screwing up very quickly. So I can't believe that's how included files are generally managed on here.
So having said what hasn't worked, does anyone know what I can do that will work?

If you just google "Arduino MPU6050" you will get billions of hits, including a large number of Arduino-specific libraries, code samples, examples, tutorials, schematics, etc. Everything you need to get it working.

Yeah I've got examples that just read the sensor outputs, but there's a "motion processor" in there that lets you do things like FFT filtering of the raw data before it comes out of the device, calculate quaternion data for you and a few other things. That's what this driver gives access to.

You mean the DMP? Then you want this: http://www.geekmomprojects.com/mpu-6050-dmp-data-from-i2cdevlib/


text:
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 ?

This is either unclear, or too broad.  Of course many things are possible, if someone builds the electrical interface and writes the program.  To have an answerable question you would have to ask about something specific: which target, and if you mean you want to load some random hex/binary/elf file, or if you mean you want to build an Arduino sketch using a port of the Arduino core to that target, and then load it using a classic ATmega Arduino as the programmer.

Build an sketch using port of Arduino core to that target and then use Arduino nano as an ISP.

What 3rd party Atmel products do you have in mind in particular? If you don't provide a list, then your question is already too broad. By the way, what is a "third-party Atmel" product, if it's Atmel, then it's not 3rd party, if it's 3rd party then it's not Atmel...

Please go the new link !

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 and the guideline for a custom core. Then select an custom core to study. Here you will find the files you need to provide to support a new AVR based MCU.
Cheers!

There is some potential for confusion here. The ArduinoISP programmer is a dedicated programmer sold by Arduino, which is used by selecting Tools > Programmer > ArduinoISP. "Arduino as ISP" is the name of the programmer made by uploading the File > Examples > 11.ArduinoISP sketch to an Arduino and is selected via Tools > Programmer > Arduino as ISP. The two programmers are not interchangeable but it's easy to mistake one for the other because of the confusing sketch name.

Let me correct that to avoid any confusion.

Yup You kind off using Arduino ISP to program any other Atmel chip .Can you explain it point to point ? Mikael

No problems, I can google that for you; https://www.arduino.cc/en/Tutorial/ArduinoISP

But if I want to program any other Microcontroller other than Atmega328 or Atmega168 Then ?

This is what happens when you ask a non-specific question and accept a response that doesn't answer what you wanted to know.  Ask better questions and you might get better answers.

Please go to this : http://arduino.stackexchange.com/questions/36238/programming-other-atmel-chipsexcluding-atmega-328-and-168 Sorry for the inconvenience faced ! Sorry !


text:
How to send HTTP requests 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:
/*
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?

Chances are you can't unless 'Ciao' allows you to.  Have a look a PAT, port forwarding or proxy servers.  Depending on you topology one of those may be able to help.

change the firmware to WiFi Link https://github.com/jandrassy/UnoWiFiDevEdSerial1#uno-wifi-with-wifi-link-firmware

update 2022. put AT firmware 1.7.5 into the esp8266 and use my WiFiEspAT library

You can find a port definition for 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 to itself from the CPU/Linino server to the MCU/Arduino client.
https://www.arduino.cc/en/Reference/CiaoRestServer

OP has Uno WiFi, not Yun. The library UnoWiFiDevEd has a ciao-like object but the WiFi is served by esp8266

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Do software SPI read from a register using shiftin()
How to read from a register using software SPI, presumably shiftin()?
It works using the builtin SPI library + hardware SPI.
I seem to be able to write but not read using manual shiftin()/shiftout(). I need to do this because I need a version of this to work on a device that doesn't have hardware SPI. I always read out 0x00000000 using shiftin() as below, but the SPI hardware/library works as expected.
(yes, I've double checked the pin numbers). LIS_MISO_PIN = 12.
  // this works (write):
  SPI.transfer(WriteAddr);
  SPI.transfer(Data);

  // this works (write):
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, WriteAddr);
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, Data);

  // this works (read):
  SPI.transfer(Reg | 0x80);
  *input = SPI.transfer(0x00);

  // does NOT work, as well as various permutations:
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, Reg | 0x80);
  *input = shiftIn(LIS_MISO_PIN, LIS_SCK_PIN, MSBFIRST);

SPI reading is done one byte at a time, how would shiftIn handle that?

Is your LIS_MISO_PIN set as INPUT? Does your device use SPI mode 0?

How about using SoftSPI? ShiftIn/Out does not work. https://github.com/MajenkoLibraries/SoftSPI

How do you declare and initialize "input" ? This smells of uninitialized pointer...

Could you please add a link to the software SPI that you have used.


text:
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) 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. 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?

If AA batteries happen to be fine, do I need another piece in my design, such as this one?
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.

you need to be able to supply 2 amps. AA batteries can supply that for short periods. if find you needed more amps, you can add more cells in parallel instead of series to increase available amps. you might want to consider a buck/boost converter than can turn any (reasonable) voltage into another voltage.

If you are using NiMH batteries watch out for the self discharge, they can lose almost 50% of their charge in a week. It increases with temperature and in the summer cars get hot, you could easily find that your batteries don't last a week in the car even with nothing connected to them.

@Andrew Never thought of that, thanks. Which batteries could be better for in-car use, is there a resource that you can point out to me?

@SertalpBilal Li-Ion have very good self discharge characteristics but long periods of high temperatures can ruin their maximum capacity and they are a lot more complex to charge / make safe. Your best bet for a simple solution may be the low self discharge NiMH cells you can get (also sold as "pre-charged" rechargables). They cost a lot more than standard rechargeables but would avoid the issue.

@Andrew Do you mean something like this one?

@SertalpBilal yes.

@Andrew Thanks! As a follow up question, would that be just fine if I connect everything as shown in the drawing using low self-discharge batteries? Arduino has a linear regulator, so it will take care of step down, am I right?

The voltage regulator on the Nano has a dropout of 1.25V which means you need 6.25V on the input. That works out as 1.25V per cell if you have 5, it depends on loading and temperature but for low power applications most batteries hit that at about 50% charge. Probably best to go with 6 cells. On the plus side that should make finding a battery holder easier, 6 cells is more standard. Other than that I can't see any obvious issues.

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

simulate this circuit – Schematic created using CircuitLab

Thanks for the detailed response. A few questions:
Is there any advantage of using 6/8 AA batteries with a step down converter compared to using a LiPo (3.7V) with a step up converter? I worry that the device will get heavier/bulkier with that many batteries.
Another question is, can I recharge batteries by plugging my Arduino into the USB in this case? It seems diodes will prevent the current into charging direction.

Not so sure if this is the one I'm looking for, but do you think something like this would work?


text:
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???

Yes, use VirtualWire or RadioHead. You might need to "evolve" your protocol to handle message fragmentation and loss. RadioHead has support for that.
Cheers!

OK, I'm gonna try it.


text:
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.

simulate this circuit – Schematic created using CircuitLab

Code: http://pastebin.com/77hqTuWA

You put 12V on an input pin? You likely fried something. ATMega are 5V max devices.

USB powered with LED instead of Voltmeter is working fine. R1 is 47k BTW

With 47k as the pullup to 12 V you probably have not fried your AVR. It's only 100 uA into the protection diodes in the processor. But you do need to change that ....it's definitely not a good thing to do. You can either turn on the internal pullup or add one to the 5 V rail (say 1K or higher).  For the output pin I'd posit you have some load you are driving and it's too heavy for the port. Restrict your output current to 20 mA or less (either source or sink). The processor stands up well to too a high a sink current, but you can blow the internal rails in the chip if you source too much.

why not just use INPUT_PULLUP on D2 and remove the 12v pullup parts completely?

@Neka "R1 is 47k BTW" - If it's 47kΩ, then put it in your diagram as 47kΩ, not 100Ω! How do you expect people to give useful answers with such misinformation?

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.

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.

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


text:
Arduino does not respond to button press suddenly
I have used this program to control relays based on commands from a serial input or control the relays with a button. Single click for a particular pin toggle and double click is like a master switch.
The code works well normally but sometimes the button just does not respond. the button works without flaw if I remove serial communication and EEPROM part of the code.
Here is the Arduino code
#include <EEPROM.h>
#include <Arduino.h>
#include <avr/wdt.h>

int pins[]={14,16,17,18,19};    //TODO: Set Switch Configuration
int no_of_switches=5;

String names, req, s;

void setup() {

  //Setting up for switches

  // initialize the pushbutton pin as an input:
  for(int i=0;i<6;i++)
  pinMode(i+3, INPUT);

  //Common pin pull up resistor
  pinMode(2,OUTPUT);
  digitalWrite(2,HIGH);

  //Setting up for relays
  Serial.begin(115200);

  for(int i=0;i<6;i++)
  {
    pinMode(i+14, OUTPUT);
    digitalWrite(14, 0);
  }

  Serial.setTimeout(4);

  names="";
  int i=0;
  char data;
  EEPROM.get(i, data);

  while(data!='^')
  {
    names+=data;
    i++;
    EEPROM.get(i, data);
  }
  names+='^';

   wdt_enable(WDTO_4S);
}

void loop() {
  wdt_reset();
  for(int i=0;i<=no_of_switches;i++){
    int b = checkButton(i);
    if (b == 1) clickEvent(i);
    if (b == 2) doubleClickEvent(i);
    if (b == 3) holdEvent(i);
    if (b == 4) longHoldEvent(i);
 }

  if (Serial.available()) {
    req = Serial.readString();
    s = "";

  if (req.indexOf("gpio") != -1)
  {
    String val = req.substring(req.lastIndexOf("gpio")+4);
    int index = val.toInt()-1;

    digitalWrite(pins[index], !digitalRead(pins[index]));

    s += pins[index];
    s += " is ";
    s += (digitalRead(pins[index]) == HIGH) ? "ON  " : "OFF  ";
  }
  else if (req.indexOf("status") != -1){
    String response_code="";
    for(int i=0;i<no_of_switches;i++){
      response_code=response_code+(digitalRead(pins[i])==HIGH?1:0);
      }
    s += response_code;
  }
  else if (req.indexOf("setstate") != -1){
    String val = req.substring(req.lastIndexOf("setstate")+8);
    for(int i=0;i<no_of_switches;i++){
      if(val.charAt(i)=='1')
      digitalWrite(pins[i],HIGH);
      else
      digitalWrite(pins[i],LOW);
      }
    s += "saved";
  }
  else if (req.indexOf("setname") != -1)
  {
    String val = req.substring(req.lastIndexOf("setname")+7);
    for(int i=0;i<val.length();i++)
    EEPROM.put(i, val.charAt(i));
    names=val;
    s="saved";

  }
  else if (req.indexOf("names") != -1)
    {
      s=names;
    }
  else
  {
    s="invalid request";
  }
  Serial.println(s);
}
}
//=================================================
// Events to trigger

void clickEvent(int pos) {
  digitalWrite(pins[pos],!digitalRead(pins[pos]));

}
void doubleClickEvent(int pos) {
  boolean bol=!digitalRead(pins[pos]);
   for(int i=14;i<=19;i++){
    digitalWrite(i,bol);
    }
}
void holdEvent(int pin) {
}
void longHoldEvent(int pin) {
}

//=================================================
//  MULTI-CLICK:  One Button, Multiple Events

// Button timing variables
int debounce = 20;          // ms debounce period to prevent flickering when pressing or releasing the button
int DCgap = 250;            // max ms between clicks for a double click event
int holdTime = 1000;        // ms hold period: how long to wait for press+hold event
int longHoldTime = 3000;    // ms long hold period: how long to wait for press+hold event

// Button variables
boolean buttonVal[] = {HIGH,HIGH,HIGH,HIGH,HIGH,HIGH};   // value read from button
boolean buttonLast[] = {HIGH,HIGH,HIGH,HIGH,HIGH,HIGH};  // buffered value of the button's previous state
boolean DCwaiting[] = {false,false,false,false,false,false};  // whether we're waiting for a double click (down)
boolean DConUp[] = {false,false,false,false,false,false};     // whether to register a double click on next release, or whether to wait and click
boolean singleOK[] = {true,true,true,true,true,true};    // whether it's OK to do a single click
long downTime[] = {-1,-1,-1,-1,-1,-1};         // time the button was pressed down
long upTime[] = {-1,-1,-1,-1,-1,-1};           // time the button was released
boolean ignoreUp[] = {false,false,false,false,false,false};   // whether to ignore the button release because the click+hold was triggered
boolean waitForUp[] = {false,false,false,false,false,false};        // when held, whether to wait for the up event
boolean holdEventPast[] = {false,false,false,false,false,false};    // whether or not the hold event happened already
boolean longHoldEventPast[] = {false,false,false,false,false,false};// whether or not the long hold event happened already

int checkButton(int buttonPin) {
   int event = 0;
   buttonVal[buttonPin] = digitalRead(buttonPin+3);
   // Button pressed down
   if (buttonVal[buttonPin] == LOW && buttonLast[buttonPin] == HIGH && (millis() - upTime[buttonPin]) > debounce)
   {
       downTime[buttonPin] = millis();
       ignoreUp[buttonPin] = false;
       waitForUp[buttonPin] = false;
       singleOK[buttonPin] = true;
       holdEventPast[buttonPin] = false;
       longHoldEventPast[buttonPin] = false;
       if ((millis()-upTime[buttonPin]) < DCgap && DConUp[buttonPin] == false && DCwaiting[buttonPin] == true)  DConUp[buttonPin] = true;
       else  DConUp[buttonPin] = false;
       DCwaiting[buttonPin] = false;
   }
   // Button released
   else if (buttonVal[buttonPin] == HIGH && buttonLast[buttonPin] == LOW && (millis() - downTime[buttonPin]) > debounce)
   {
       if (not ignoreUp[buttonPin])
       {
           upTime[buttonPin] = millis();
           if (DConUp[buttonPin] == false) DCwaiting[buttonPin] = true;
           else
           {
               event = 2;
               DConUp[buttonPin] = false;
               DCwaiting[buttonPin] = false;
               singleOK[buttonPin] = false;
           }
       }
   }
   // Test for normal click event: DCgap expired
   if ( buttonVal[buttonPin] == HIGH && (millis()-upTime[buttonPin]) >= DCgap && DCwaiting[buttonPin] == true && DConUp[buttonPin] == false && singleOK[buttonPin] == true && event != 2)
   {
       event = 1;
       DCwaiting[buttonPin] = false;
   }
   // Test for hold
   if (buttonVal[buttonPin] == LOW && (millis() - downTime[buttonPin]) >= holdTime) {
       // Trigger "normal" hold
       if (not holdEventPast[buttonPin])
       {
           event = 3;
           waitForUp[buttonPin] = true;
           ignoreUp[buttonPin] = true;
           DConUp[buttonPin] = false;
           DCwaiting[buttonPin] = false;
           //downTime[buttonPin] = millis();
           holdEventPast[buttonPin] = true;
       }
       // Trigger "long" hold
       if ((millis() - downTime[buttonPin]) >= longHoldTime)
       {
           if (not longHoldEventPast[buttonPin])
           {
               event = 4;
               longHoldEventPast[buttonPin] = true;
           }
       }
   }
   buttonLast[buttonPin] = buttonVal[buttonPin];
   return event;
}

Do you have external pull-up resistors as you are using INPUT mode for the inputs?

If it stops working after a random time, I would say it looks like a memory exhaustion problem. You could periodically print the available RAM to make sure: code to do so is widely available. If that is indeed the problem, using statically allocated character arrays instead of String objects should help.

Could it be that the processor is busy dealing with the serial or EEPROM code when you press the button and you release it before the processor has returned?

Yes, I do have pull-up resistors for the button. Normally the button works consistently. But all of a sudden it stops working


text:
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..

It looks like it found an invalid library in your Arduino installation. From the screenshot, though, it is not clear which. You could try de-installing the Arduino software and re-installing it.

Why did you post a screenshot with mostly irrelevant stuff and an incomplete error message? Why not copy paste the error here? There is an obvious button labeled "Copy error messages".

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)


text:
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.

A float has roughly 7-digit resolution. Printing it with 10 decimal places is ludicrous.

Please add the library (source) for "client.add()". Impossible to guess what you are using. Also you should start a new issue if the original question has been answered even though the issue has evolved. How could others find information if the question changes?

does using double instead of float help?

@dandavis: It might help on an ARM-based Arduino, like the Due. On AVR (most Arduinos), double is the same as float.

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) are only 32-bit, and that gives 6 to 9 significant decimal digits precision.
Cheers!

i get your point completely

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

Floats are always exact numbers, and 10.0 will always be 10, never 9.9999999999. You get rounding errors only when trying to represent as a float a number that cannot be exactly representable as a float.

@EdgarBonet not according https://technet.microsoft.com/en-us/library/ms187912(v=sql.105).aspx ... I mean a float as type (probably you mean a 'mathematical float' ?

Every float represents a number, in the mathematical sense of the word “number”, i.e. defined with infinite precision. Most numbers are not representable as floats, and can thus only be approximated by floats. Every single integer in the range ±16777216 (and this include the number 10) is an exact float.

@EdgarBonet Yes you are completely right about the integers ... I will update the answer. Thanks.


text:
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;

When you turn on the led, record the time.
After that, turn off the led if

The led is on and
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.

fairly straight forward, isn't it?

It would seem that this is what I should accomplish, but I have some trouble understanding how to do this.

You have trouble implementing it or understanding it? Potential solutions for the first and no solution for the latter.

I have trouble understanding how to implement this in a way so that the program recognizes that the connection has been reestablished and then turn off the LED after 2s

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;

Look at one of the timer libraries such as SimpleTimer. 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.

I initially used the timer.h library, but since I have a timer elsewhere in the code that uses the millis() function (Couldn't find an appropriate function for this in the library), the behavior of the digital pins became quite odd (They started to oscillate at a very low voltage, causing the LED's to blink, when they should be turned off)


text:
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.

Is there a reason why you don't want to use the serial bootloader?

What do you mean by 'serial' bootloader? Actually the problem is that I have ATMega328 instead of 328P for an UNO board. I have tried burning the bootloader fot both 328 and 328P on my 328 but I cant get either of them to program via USB somehow. USB connection is fine as loopback test is running fine.

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


text:
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.

You forgot to add the link referred by "this".

What board and serial port have you selected?

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


text:
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.

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.

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.


text:
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?

if it wasn't using those 100 lines anyway, you won't save anything...

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

Arduino is C++ not C.

yep, true, thanks for pointing that out, i'll correct that (yet, you can code c libraries if you need)... and the generated assembly is even worse!