text:
How can I loop for a set amount of time when a condition is met?
I'm trying to create an Arduino project with a light sensor and a buzzer. The idea is that when the sensor detects that the lights have gone off, the buzzer will sound for 5 seconds. At some point, the lights will come back on, but when they go back off, I need the buzzer to sound again.
At the moment the buzzer does sound the first time the lights are turned off but after the lights have come back on and then off again, it won't sound and I can't figure out why.
int lightSensor = 2;
int buzzer = 3;
long startTime,stopTime;
long myDesiredTime = 5000;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lightSensor, INPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

void runBuzzer()
{
  tone(buzzer, 1000); // Send 1KHz sound signal...
  delay(1000);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  delay(1000);
}

You have two major issues here:
void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

The first is that you never re-read sensorState. The second is that you are comparing stopTime before setting a value to it. Try re-arranging like this:
void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      stopTime=millis();
      if(stopTime - startTime <= myDesiredTime)
      {
        runBuzzer();
      }
    sensorState = digitalRead(lightSensor);  // read sensorState again
    }
  }
}

In your example, the buzzer does not sound when the light has been switch on and then back off again.

Good point. Well, we can simplify somewhat:
void loop() {

  if (digitalRead(lightSensor) == HIGH)
    {
    startTime = millis ();  // remember when we started
    while (digitalRead(lightSensor) == HIGH &&
           millis () - startTime <= myDesiredTime)
      {
      runBuzzer();
      }  // end of while switch still closed and time not up
    while (digitalRead(lightSensor) == HIGH) { } // wait for sensor go to LOW
    delay (200);  // debounce
    }    // end of switch being closed
}      // end of loop

In your example, the buzzer does not sound when the light has been switch on and then back off again.

See amended answer.

Thanks, I've tried it, but now it doesn't stop after 5 seconds and only goes off when the lights come back on. The theory should be like this: Light Detected= No Buzzer, No Light Detected= Buzzer for 5 seconds max then reset. So the next time that light is not detected, it will go off again for 5 seconds.

Hmm. So you want the buzzer to beep for a maximum of 5 minutes? I've added another 2 lines to my last example. Once 5 minutes is up it waits for the sensor to go LOW again.

Think of it like this. Any time you use a while loop your code has the rains until its done its job.
It's important to remember that the loop() function in Arduino should not be blocked. This line:
while (sensorState == 1)
will block forever. The condition is never changed from within the while loop. Theres a simple way you could fix this which would be to set sensorState and update it inside the while loop. But lets not do that. Because thats inefficient and you'll likely run into this problem again in more complex programs and that solution here won't still be a solution.
What you're trying to do is called concurrency. Your program should have obvious units of execution. Your two units are: "run a buzzer for 5 seconds" and "set off an event when a sensor reads true." where the first is depended on the second. So its conditional. That sounds like a job for if
When you code in { and } it is a block. It's not quite a context but is a distinct mode of execution.
So technically this:
void loop() {
    if( ... ) {
      ...
    }
    if ( ... ) {
      ...
    }
}

Is two modes of execution. Since loop() is executed repeatedly. With that in mind when you program you can then use a variable to control the what gets executed as needed. So:
void loop() {
    int sensorState = digitalRead(lightSensor);
    if( sensorState == 1 && buzzer_enabled == 0) { // set off an event when a sensor reads true.
        buzzer_enabled = 1;
        startTime = millis();
    }
    if ( buzzer_enabled == 1 ) { // run a buzzer for 5 seconds
        endTime = millis();
        if(stopTime - startTime <= myDesiredTime) {
            runBuzzer();
        } else {
            buzzer_enabled = 0;
        }
    }
}

We could stop here. But the use of delay is also blocking in the loop function and it is only for perception. So here's the whole thing without delays using a check against the modulus of diffTime.
int lightSensor = 2;
int buzzer = 3;

long startTime,stopTime;
long myDesiredTime = 5000;

bool buzzer_enabled = false;
bool buzzer_active = false;

int sensorState;
int prevSensorState = 0;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lightSensor, INPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
    sensorState = digitalRead(lightSensor);
    if( sensorState == 1 && prevSensorState == 0 ) { // set off an event when a sensor reads true.
        buzzer_enabled = true;
        startTime = millis();
    }
    prevSensorState = sensorState;
    if ( buzzer_enabled == true ) { // run a buzzer for 5 seconds
        stopTime = millis();
        long diffTime = stopTime - startTime;
        if( (diffTime % 2000) < 1000 ) {
            if(buzzer_active == false) {
                buzzer_active = true;
                //tone(buzzer, 1000);
            }
        } else {
            if(buzzer_active == true) {
                buzzer_active = false;
                //noTone(buzzer);
            }
        }
        if(diffTime > myDesiredTime) {
            buzzer_enabled = false;
        }
    }
}

No need for delay >:3 And all for free you got a new feature which is that if you set off the event again (the light goes off) the buzzer is extended another 5 seconds. If you don't want that all you have to do is add && buzzer_enabled == false to the first if.

I'm afraid I tried your example and the buzzer did not run at all.

You need to read the code. I didn't intend for you to just run it as is. I'm not sure what your function tone and noTone actually do so they are left commented where i think they should be.

Understand that your while (sensorState == 1) in your switch() is an infinite loop, with no way out (even if internally it gives the desired 5 seconds of sound).


text:
how can I upload a hex file to an arduino uno?
I have a Rostock Max 3d with an Arduino Uno as the controller. The OEM has a firmware version I would like to upload, but it is in the hex file format.
I have looked all over the Arduino IDE, but did not found a way to upload a hex file to the Arduino. I tried using AVRDUDE, but the Arduino only communicates with my PC when I set the "Programmer" to AVRISP. I have uploaded other codes for blink, and hello_world, but haven't been able to compile the firmware source. I was hoping I could just use the hexfile included in the firmware package.
My OS is Linux.

You can enable "Verbose output" under File -> Preferences for uploading the code.
The Arduino IDE also uses avrdude to upload its sketches - you may "steal" the command it uses from that verbose output.
After that, simply edit the command used by the IDE to point to your .hex file.

I've been using Xloader. http://www.hobbytronics.co.uk/arduino-xloader

I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.

This is essentially the same as @raddevus answer except it is in python code. I am using windows. Set the preferences in the arduino IDE to verbose and upload the sketch you want to upload using the python code. Find the line of code just before it executes the avrdude bit (where it says 'avrdude: Version...'). The code is designed to be flexible in that you can create a function that will feed in different hex files and com ports for different arduinos etc. If you have problems, make sure you get all the apostrophes, speech marks and spaces in the right place and change all the '' in filenames to '/'. I used the arduino blink example here to check it worked.
comport is the COM port that your arduino is on
Sketch is the .hex file path that you can find in normally hidden folder Appdata - you can copy this hex file and store it somewhere more convenient.
in1 is the first part of the line of code up until the P of the part where it says '-PCOM4'.
in2 is the bit that comes after the '-PCOM4' until the location of your file.
cmdIn creates one long string that is then passed to os.system to execute.
import os

comport = 'COM4' # enter your comport here
sketch = 'C:/Users/user_name/AppData/Local/Temp/arduino/sketches/290321875103144FE430B0C8E22741C9/Blink.ino.hex'
in1 = 'cmd /C ""C:/Users/user_name/AppData/Local/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude.exe" -C"C:/Users/user_name/AppData/Local/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf" -v  -patmega328p -carduino -P'
in2 = ' -b115200 -D "-Uflash:w:';
cmdIn = '%s%s%s%s:i' % ( in1, comport, in2, sketch);
os.system(cmdIn)

I recommend looking at the arduino IDE files located at "(install path)/hardware/arduino/avr/" (on windows anyway, I should assume the same on linux).
I am unsure if the following files have the .txt extension on them, but if not use just the file name.

Open and look in "boards.txt" and find the associated entries starting with "uno." keeping this file open.
Next open "platform.txt" looking for the entries "tools.avrdude" (the avrdude part comes from boards.txt "uno.upload.tool" entry) and copy into a new text editor the value of "tools.avrdude.upload.pattern" you can fill in the parameters later.
With the command you copied replace the following:
from platform.txt

"{cmd.path}" = "tools.avrdude.cmd.path"
"{config.path}" = "tools.avrdude.config.path"
"{upload.verbose}" = "tools.avrdude.upload.params.verbose"
"{upload.verify} = "tools.avrdude.upload.verify"

now from boards.txt

"{build.mcu}" = "uno.build.mcu"
"{upload.protocol} = "uno.upload.protocol
"{{serial.port}" = Your serial port (according to research something like /dev/ttyS0)
"{upload.speed}" = "uno.upload.speed"
"{build.path}" and "{build.project_name} = path to file you are trying to upload

So with the above set out for me to upload a program to an Arduino uno I would use something like the following in windows:
assuming install path was "C:\Arduino\"

"C:\Arduino\hardware\tools\avr\bin\avrdude.exe" "-CC:\Arduino\hardware\tools\avr\etc\avrdude.conf" -v -patmega328p -carduino "-PCOM1" -b115200 -D "-Uflash:w:C:\MyArduinoProject\build.hex:i"

for linux it could possibly be (I really am unsure):
assuming install path was "/opt/Arduino/"

"/opt/Arduino/hardware/tools/avr/bin/avrdude" "-C/opt/Arduino/hardware/tools/avr/etc/avrdude.conf" -v -patmega328p -carduino "-P/dev/ttyS0" -b115200 -D "-Uflash:w:/usr/MyArduinoProject/build.hex:i"

The above should work for you, I have previously written my own program to upload a hex file to the Arduino utilizing the above commands and avrdude.

I found the definitive answer to this.

Start Arduino IDE
To to File...Preferences...
Turn on Show verbose output during: [X] upload (image 1 below)
Upload a sketch to your Arduino Uno
I used the sample blink sketch and saw the following (image 2 below):

AVRDude: is used to upload
You want that first line shown in white --- when you expand it you'll see that it is the entire line of code that is used to upload the HEX file of your program to the Uno.
The entire command on my computer looks like the following:
C:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\<username>\dev\arduino\STK2UPDI\build\blink.ino.hex:i

I'm going to break this down into a few lines:
First, it's the full path to the avrdude exe.
Then it is passing the -C argument with the full path to the avrdude.conf file
c:\longpath\avrdude -C C:\avrdude.conf
Then a bunch of params to set up avrdude properly:
-v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:
And finally the full path to the HEX file you want to upload
c:\longpath\blink.ino.hex:i
All You Have To Do
All you have to do is take that extremely long line and replace the full-path to the hex file to be your target HEX file and then run the entire command and you'll see something like what is shown in image 3 below.
Image 1

Image 2

Image 3

neat, I'll check that out. what version are you using?

using Arduino IDE 1.8.15

I think you can use this software http://www.mediafire.com/file/tx2l85gsdkpf5d4/HEXtoArduino_V1.0.0.zip/file

source: Stack Exchange

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

sort: votes


text:
Diffrence between running once and infinite
const int ledPin = 12;

void setup(){
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void loop(){
    if (Serial.available()) {
        light(Serial.read() – '0');
    }
    delay(500);
}

void light(int n){
    for (int i = 0; i < n; i++) {
        digitalWrite(ledPin, HIGH);
        delay(100);
        digitalWrite(ledPin, LOW);
        delay(100);
    }
}

by Oscar Liang
awesome little piece of code which taught me how to setup connection by serial. yet one part I don't understand fully. Why does this line:

light(Serial.read() – '0');

make the code run once,
and this line an infinite times.

light(Serial.read());

has this something to do with binary? I don't get why subtracting the string 0 would run the code once.
Thanks in Advance!

Serial.read() -'0'
Such code is often used to convert a character to a digit (e.g. int).
Like if the character is '2', than '2' - '0' = ascii 50 - ascii 48 = 2
However, if you use
Serial.read()

the value will be 50 instead of 2.... maybe looping 50 times (or 48 to 58, for values 0 to 9) will give you the impression it runs infinite?

oh wow Thank you, so that is just a way to convert to a int. Never knew that!

Yes, it is a way to convert one digit (so a character from '0' to '9') to an integer. Nb if this answer is good, consider upvoting and accepting it as your answer.

cant upvote yet. I don't have enough rep, but you will get it in the end :)

Thanks for accepting. No problem (geen probleem). Enjoy programming!

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


text:
Error uploading to ATtiny
I followed Great Scott's video on YouTube for uploading to an ATtiny85. When I tried I got the following error messages:

Arduino: 1.6.7 (Windows Vista), Board: "ATtiny85 (internal 8 MHz clock)"
Board attiny-master:attiny:attiny85-20 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-20
Board attiny-master:attiny:attiny45-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY45-8
Board attiny-master:attiny:attiny85-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-8
Board attiny-master:attiny:attiny44 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY44

etc. etc. ...

exec: "-w": executable file not found in %PATH%
Error compiling.`
This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.

When I unplug  my ATtiny85 and restart Arduino, I have no problems uploading, though I get about 8 error messages saying something like:

Board attiny-master:attiny:attiny84 doesn't define a 'build.board' preference. Auto-set to: ATTINY_ATTINY84

Please edit question and add a link to whatever video you mean, and a link to the file you downloaded to set up boards.txt for those processors.

It's likely that a compiler's file name is missing from a command line the IDE is trying to execute.  To find out more about what the command looks like (which will let you figure out what name is missing), turn on verbose output during compilation.  That is, click File, Preferences in the IDE, then click the box in front of “compilation”.  After you find out what's missing, you can then turn off verbose output and fix platform.txt, which is the file the IDE looks at to find out what commands to execute when compiling sketches.
To get rid of the warnings about undefined build.board values, add lines like the following to the boards.txt file in the tiny/avr/ directory (or whereever you installed it).  (Your 1.6 IDE wants build.board definitions, which IIRC weren't needed by 1.5 and earlier IDEs.)
attiny85-20.build.board=ATTINY_ATTINY85-20

Each of the lines you add will contain the Auto-set value, prefaced by a string made up of a board-type and .build.board= concatenated together.  Add each line just before or after other .build.-containing lines.

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


text:
Programming an ATtiny85
Recently I ordered some ATtiny85's from Jameco, and I've been trying to upload code to them through an Arduino Uno, following the instructions from this video on YouTube. I've been getting a lot of unexpected errors and I am now wondering if the chips I bought are the problem. Here are the specs from the Jameco website:

Flash (Kbytes): 8 Kbytes
Pin Count: 8
Max. Operating Frequency: 20 MHz
Power Supply: 2.7 - 5.5V
Operational Range: Industrial (A) (-40°C to 85°C)
CPU: 8-bit AVR
Number of Touch Channels: 3
Hardware QTouch Acquisition: No
Max I/O Pins: 6
Ext Interrupts: 6
USB Speed: No
USB Interface: No

Does the "USB Speed: No; USB Interface: No" mean these aren't programmable by my set up? Or is there is anything else I should know about these chips? Do I need to get new ones that are different?

Please post the error messages. There are a lot of warnings when programming ATtiny with these old tools.

Before you panic (try not to panic) and buy new chips, test the existing ones. See my page about detecting chip signatures which has links to code on Github for a sketch you can run on your Uno, to test the ATtiny85.

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from this page about a hex uploader and wiring like this (you also need an SD card adapter):

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.

I would suggest you to take a look at this video which explains step by step how to program the ATtiny85. https://www.youtube.com/watch?v=i9WOwDrpRKs
From my early days trying to program the ATtiny, i have watched this video.

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


text:
Regarding the output voltage and current in arduino
This is basically an off-shoot from https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop. It's the same schematics and so on, however, I'm now wondering what the output voltage and current is.
I've a 9V battery and the MOSFET transistor from the arduino starterpack (doesn't say the specs) connected to the 5V pin on the board. I need the following output current/voltage for it to activate a solenoid:

6V: 160 mA
7V: 190 mA
8V: 220 mA
9V 240 mA
10V :270 mA
11V :300 mA
12V :320 mA

and I'm just not sure how to calculate it since I'm not sure about the output from the transistor and all the way to the solenoid.
The solenoid: http://www.electrokit.com/en/plastic-water-solenoid-valve-1-2-12v.51108

Your transistor is backwards: you should ground the emitter and connect the collector to the solenoid. Also, put a few hundred ohms between it's base and the Arduino output.

In fact he says it's a mosfet, so even the schematic symbol is wrong. Now.. Can you rephrase the question so that we can understand what is the question? I mean, what are those numbers? You said you have a 9V battery, so what is 6V? and 12V? And if your question is "will the transistor be able to let 240mA pass?" the answrer is "it depends". Usually it can, because that current is quite low, but you will have to read its specifications (aka datasheet) to be sure..

the transistor is connected as: (left) gate to pin 9, (middle) drain to the solenoid, (right) source to gnd. I thought the schematics would help even with errors in it but maybe it caused more confusion instead! The numbers are the current and voltage needed for the valve-solenoid to open/close., "relay" in the image.. ugh, another error

You don't need to "calculate" anything with a MOSFET.  You will be using it in the saturation zone. That means it is fully turned on and will allow through the current you need.
However, the gate of a MOSFET looks, to all intents and purposes, like a small capacitor. That means there will be a certain amount of inrush current to the gate when you turn it on. To limit that inrush current you need a small resistor (say 100-220Ω) on the gate.
When using a BJT, though, you need to ensure that you allow enough current through the base to allow enough current through the collector.  Divide the current you need through the collector by the Hfe (typically 100 for a small signal transistor) and that is the minimum current you need to allow through the base. Subtract a silicon junction voltage (0.6V) from the voltage of the IO pin (5V). Divide it by your base current calculated above, and that is the maximum resistor you can use on the base.
And also your transistor symbol in your schematic is backwards.

I think it works better now than before when I added a 220Ohm resistor.  Not sure if it's the solenoid that doesnt open enough when I connect it to a valve so perhaps it's the solenoid that is broken or bad quality

Ok, so the retailer told me that a 9V battery is too weak because of the inner resistance. I need something like http://www.electrokit.com/en/timer-1s60h-startstop.50293

9V PP3 batteries are not suitable for anything. I rue the day someone first posted a tutorial online using one with an Arduino. If you must use batteries, use AAA or AA batteries (6), or a 7.4V LiPo.

Oh, I actually used the arduino starterpack guide tutorial 09 - motorizzed pinwheel, although I removed some stuff and switched the DC motor out for a the solenoid, and they are using a 9V batteri. In any case, I'll try it out with another battery say http://www.amazon.co.uk/Duracell-MN21-A23-12V-Batteries/dp/B001PAZU0Y


text:
problem data I2C to sensor GY955/BNO055 (China)
I want to ask, I have a problem when running the Arduino sensor, I can't output data, but it's detecting that the sensor address has been paired.
Like I2C has a problem or locks it.
Last night it worked only because my twin sensors tried another with the same program after I compiled and uploaded, I see the serial monitor is only a detection sensor, but it doesn't display data, so the pitch evaporates and the roll data is 0.0,0.
There seems to be a problem with i2c: the data does not come out, it only detects the sensor address but the contents are all zero. Have you ever experienced this?
This initially worked, because the sensor was the same and I tried it with the same program after reading GY 955 / BNO055 on Euler_streaming it only showed zero per axis.
This is code in the bread board
/****************************************************************************

    Euler_Streaming.pde - part of sample SW for using BNO055 with Arduino

   (C) All rights reserved by ROBERT BOSCH GMBH

   Copyright (C) 2014 Bosch Sensortec GmbH

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

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

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

 **************************************************************************/
/*  Date: 2014/01/07
     Revision: 1.2

*/
#include "BNO055_support.h"     //Contains the bridge code between the API and Arduino
#include <Wire.h>

//The device address is set to BNO055_I2C_ADDR2 in this example. You can change this in the BNO055.h file in the code segment shown below.
// /* bno055 I2C Address */
// #define BNO055_I2C_ADDR1                0x28
// #define BNO055_I2C_ADDR2                0x29
// #define BNO055_I2C_ADDR                 BNO055_I2C_ADDR2

//Pin assignments as tested on the Arduino Due.
//Vdd,Vddio : 3.3V
//GND : GND
//SDA/SCL : SDA/SCL
//PSO/PS1 : GND/GND (I2C mode)

//This structure contains the details of the BNO055 device that is connected. (Updated after initialization)
struct bno055_t myBNO;
struct bno055_euler myEulerData; //Structure to hold the Euler data

unsigned long lastTime = 0;

void setup() //This code is executed once
{
  //Initialize I2C communication
  Wire.begin();

  //Initialization of the BNO055
  BNO_Init(&myBNO); //Assigning the structure to hold information about the device

  //Configuration to NDoF mode
  bno055_set_operation_mode(OPERATION_MODE_NDOF);

  delay(1);

  //Initialize the Serial Port to view information on the Serial Monitor
  Serial.begin(115200);
}

void loop() //This code is looped forever
{
  if ((millis() - lastTime) >= 100) //To stream at 10Hz without using additional timers
  {
    lastTime = millis();

    bno055_read_euler_hrp(&myEulerData);            //Update Euler data into the structure

    Serial.print("Time Stamp: ");               //To read out the Time Stamp
    Serial.println(lastTime);

    Serial.print("Heading(Yaw): ");             //To read out the Heading (Yaw)
    Serial.println(float(myEulerData.h) / 16.00);       //Convert to degrees

    Serial.print("Roll: ");                 //To read out the Roll
    Serial.println(float(myEulerData.r) / 16.00);       //Convert to degrees

    Serial.print("Pitch: ");                //To read out the Pitch
    Serial.println(float(myEulerData.p) / 16.00);       //Convert to degrees

    Serial.println();                   //Extra line to differentiate between packets
  }
}

Can someone find a schematic of the gy955?

How do you know, that the sensor was found at the address? What library are you using (link)? Is the address defined in the BNO055_support.h?

Hari_Murti, did you connect the vcc of the module to the 3.3v pin or the 5v pin of the arduino mega 2560?

I had the same problem with the Adafruit library. When a Chinese module is used the id needs to be specified in the constructor like this:
Adafruit_BNO055 bno = Adafruit_BNO055(55,0x29);


text:
Why my LCD does not work with this if statement?
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int greenLedPin = 12;
int blueLedPin = 11;
int redLedPin = 8;
int yellowLEdPin = 9;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  pinMode(greenLedPin, OUTPUT);
  pinMode(blueLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  pinMode(yellowLEdPin, OUTPUT);
  Serial.begin(9600);
  while (! Serial);

}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(analogRead(lightSensorPin));
  analogValue = analogRead(lightSensorPin);
  if (analogValue < 50) {

digitalWrite(redLedPin, HIGH);

  }
  else if (analogValue >= 50 && analogValue <= 99) {
    digitalWrite(yellowLEdPin, HIGH);
  }
  else if (analogValue >= 100 && analogValue <= 300) {

    digitalWrite(blueLedPin, HIGH);
    lcd.print("its bright");
 }
  else {
      digitalWrite(greenLedPin, HIGH);
      lcd.print("its bright");
      }

  delay(3000);
  digitalWrite(greenLedPin, LOW);
  digitalWrite(blueLedPin, LOW);
  digitalWrite(redLedPin, LOW);
  digitalWrite(yellowLEdPin, LOW);
  lcd.clear();

}

I'm very new to this so sorry if its a dumb mistake and I know my LCD is working right, since I have tested it so all the pins are good.

On the Uno, pin 0 and 1 are used for Serial. You can't use pin 1 for Serial in addition to the LCD. What happens if you change the wiring to use a different pin and update the code accordingly?

thanks so much this seems to have worked for me

You're welcome. I'm very glad to hear that! I have written a formal answer so that this question can be considered answered by the Stack Exchange system. If you consider it the correct answer, you can "accept" it.

On the Uno, pin 0 and 1 are used for Serial. You can't use pin 1 for Serial in addition to the LCD. In general, it's best to avoid using pins 0 and 1.
You need to change the LCD wiring to use a different pin and update the code accordingly. For example, if you moved the LCD's RS pin connection from pin 1 on your Arduino to pin 13, you would update this line from:
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

to:
LiquidCrystal lcd(13, 2, 4, 5, 6, 7);

After that, your LCD should work correctly.


text:
Did not find fingerprint sensor :( Arduino Mega 2560 Adafruit Fingerprint Sensor
I'm getting the following error when I try to enroll fingerprints using the Arduino Mega 2560 microcontroller along with a Fingerprint Scanner:

Did not find fingerprint sensor :(

The exact devices I'm using are as shown in the links below:
https://www.gearbest.com/development-boards/pp_70487.html?lkid=11637831
https://www.gearbest.com/boards-shields/pp_009769796663.html?wid=1433363
My circuit connection is:

(Green) TX    =>  Pin 0 [PWM]
(White) RX    =>  Pin 1 [PWM]

//It doesn't respond when connected to 5V, it only heats up

(Red) VCC     =>  3.3v
(Black) GND   =>  GND

The connection is illustrated below:

The code is shown below:
#include <Adafruit_Fingerprint.h>

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
 #define mySerial Serial1

// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// comment these two lines if using hardware serial
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(10, 11);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }
  }
}

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()                     // run over and over again
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
  id = readnumber();
  if (id == 0) {// ID #0 not allowed, try again!
     return;
  }
  Serial.print("Enrolling ID #");
  Serial.println(id);

  while (!  getFingerprintEnroll() );
}

uint8_t getFingerprintEnroll() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

I used the Adafruit Fingerprint library found here:
https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library
I also soldered the wires from the sensor onto Male Pin Headers for greater connection stability.
All I get is the fingerprint sensor blinking continuously which makes me think it's not faulty but when I try to run the enroll code I get the error message highlighted above.
I also tried connecting using the Software Serial approach like below but that wasn't the solution either:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

What could be the problem? Is my connection and code okay? Anyone have an idea on how to fix this?
The heat occurs on the encircled area below:

Before anything, watch this video https://www.youtube.com/watch?v=nxjLx5RdaSQ&t=183s . I  would say it's damaged goods if it heats up when connected to 5v. That sensor board is supposed to be able to run off that voltage, per the specs listed and educ8ts great video. It's also from gearbest, and gearbest does not have the best track record. Can you pinpoint where the heat is coming from? You may be able to swap a damaged component (if you're lucky).

It just so happens I had watched it :-) Thanks. I have edited my question to show where the overheating is occurring. Do you know which part is causing this from the snapshot? Or am I overreacting, maybe these heat levels are normal?!

Could it be the male jumper wires that connect the breadboard to the micro-controller? Because those dance around a bit as you handle the device. There should be a way to secure those, no?

Mega has 4 hardware Serials. why do you use the first which is used by USB or why SoftwareSerial? and why a breadboard in the middle?

@Juraj Now that I've established my sensor is in working order and have used it with both SFG Demo and Arduino IDE, I'll try out the hardware serials some more. I had tried them unsuccessfully before if you check out my question above where I used PINs 0 and 1 which work with SFG Demo but not Arduino IDE. I suspect the issue might be with the Adafruit Library since when you attempt to upload the edited code to work with the Hardware Serials, the upload is unsuccessful, unless I'm using the wrong PINs altogether. Suggestions? Either way I'll post my findings here in a couple of days.

Serial on pins 0, 1 is used by USB. use Serial1 on pin 18 and 19

Thanks! I'll try this out first. I've confirmed that's the case here: https://www.arduino.cc/reference/en/language/functions/communication/serial/ There's a lot to these tiny computers.

@Juraj Tested and working. I've updated my answer accordingly. Thanks for your input! Regarding my use of the breadboard, I soldered my fingerprint scanner wiring onto 4 joined male pin-headers so that's why I need the breadboard for now albeit as a temporary solution as I prototype my design.

Thanks for your responses @HavocRC and @Juraj
I've successfully come to the following working parameters that I have tested and have given positive results:

When using Arduino Mega 2560 with the SFG Demo, we use:
(Green) TX    =>  Pin 1
(White) RX    =>  Pin 0
(Red) VCC     =>  5V
(Black) GND   =>  GND
When using Arduino Mega 2560 with the Adafruit Library, we use:
Using Hardware Serial Port (Serial1) [Recommended]
(Green) TX    =>  Pin 19
(White) RX    =>  Pin 18
(Red) VCC     =>  5V
(Black) GND   =>  GND
//Note that you'll comment out the Software Serial initialization
//as directed by the code in the Adafruit Library
#define mySerial Serial1

When using Arduino Mega 2560 with the Adafruit Library, we use:
Using Software Serial
(Green) TX    =>  Pin 10
(White) RX    =>  Pin 11
(Red) VCC     =>  5V
(Black) GND   =>  GND
//The order of the PINs in the code is
SoftwareSerial mySerial(10, 11);

In the process of testing I also used an older version of Arduino IDE, version 1.0.5 which may have helped to get the sensor working (just a hunch). It turns out the sensor only works with 5V although it heats up a bit (not to fiery levels at a go but I wouldn't leave it turned on if I was away from my laptop for a while).
By the way, for the SFG Demo to work, upload the 'blank' example first, close Arduino and then run SFG Demo. If it works then your fingerprint scanner is in working order.
For the hardware Serial options you can also use alternative PINs as follows:

Serial2 on pins 17 (RX) and 16 (TX)
Serial3 on pins 15 (RX) and 14(TX)

Links
http://www.adafruit.com/datasheets/SFGDemoV2.0.rar
https://www.arduino.cc/en/main/OldSoftwareReleases
https://www.arduino.cc/reference/en/language/functions/communication/serial/


text:
Failsafe Arduino
I want to read an RFID tag using an Arduino, which controls some relais. This is easy.
For me the more complex part is to build it fault-tolerant. So I thought I could use the watchdog. The tricky part is, my relais module should keep a certain state (change of state is rare), no matter what happens to the Arduino.
My first thought was to put some condensators to the relais. Calculate the RC component so it can last the watchdog timeout plus booting up.
Now there is the problem, that the relais module is keeping its state while booting. I guess I can't use a pull up/down resistor, since the state of the relais can be low or high at random.
My second thought was using a latch relay. But this has the disadvantage, that it probably can hide problems. For example if the arduino died, and the latch relay holds a certain state, it masks the problem. In that case it's not possible to notice a faulty Arduino.

Those are the reasons I tend to think condensators are better?
Are those ideas feasible? Are there easier ways to accomplish this?
Are there more problems to think about?

(I was already reading about millis at gammon's page. Apparently it's not a problem after all.)

Please explain why and where you would need a pull up/down resistor.

you are contradicting yourself in your statements ......... relais module should keep a certain state (change of state is rare), no matter what happens to the arduino ........ and if the arduino died, and the latch relay holds a certain state, it masks the problem

It is impossible to solve. You need to be able to detect all problems for everything. When the wire of the rfid coil breaks or shorcuts, how can you detect that? A smoke detector can detect smoke and a low battery voltage. That's all. To make it reliable, a good quality smoke detector is required and it should be tested every month (some manuals say: every week). You need therefor the best quality hardware and software to start with.

@jsotola: this is due to unclear requirements. I wasn't sure about them. After thinking a bit more: I think I want to keep the state only for a certain amount of time. Enough time for the arduino to recover. Or else go into default state, where nothing happens, and I can see a problem. If the state is kept infinite, then I don't see the problem easily.

@jot: I think the only requirement I have: If the rfid reader tells me he read a certain tag, it should be true. if he fails, nothing is working, and I can detect the problem. I think with a timed latch I can go to a default state, where I shut down the relais module. So I hope I should be fine.

Consider constraining your design with clear requirements.  As it is highly unlikely any design can protect its self for all situations.

my relais module should keep a certain state (change of state is rare), no matter what happens to the arduino

Consider latching relays where there is a set coil and a reset coil.  Such as  this one.  Such a device does not need to be continuously powered.  Only pulsed to set and a pulsed to reset.

So I thought I could use the watchdog.

Watchdog timers are fine if your program can get stuck waiting for an event that may never happen.  Like waiting to read the data from and RFID chip.  If you think this might happen, then add the watchdog timer to your design.

Now there is the problem, that the relais module is keeping its state while booting.

Most embedded processors with bi-directional GPIO pins force those pins to be inputs when booting up.  This appears as high impedance to the outside world.  Consider using pull ups or pull downs on these pins to prevent them from floating to a state which may change the relays during booting of the processor.

Yes you're totaly right. My requirements are not clear. Even I am not sure about them. Good point. I was thinking about a timed latch. If I go into default state, nothing happens and I can detect a problem. If there is a state other than default, I want to be sure it's the proper one.


text:
How do I turn on/off led with the same IR button?
I'm trying to make the led switch on/off by the same case(): code.
But its not working could anyone help me?

Have you tried checking the current state and acting accordingly?

It would be good if you add your sketch if you have one.
In principle, you have to create a boolean variable which keeps the current state of the LED. When you get an IR command, inside the IR button handler invert the state of the boolean. Than change the LED accordingly.
Something like:
Const/Global variable:
#define LED_PIN 8

int ledState;

In setup:
 ledState = FALSE;
 digitalWrite(LED_PIN, ledState);

In side loop:
case IR_BUTTON_CHANGE_LED:
   ledState = ledState == LOW ? HIGH : LOW; // Invert state
   digitalWrite(LED_PIN, ledState); // Set LED according to state
   break;


text:
Sizing relays for audio circuit?
Non-technical person here, so please be gentle. I moved into a place that has ceiling speakers in each room (I tried, but they don't come apart, aren't marked other than manufacturer, and that is a company that went out of business 15+ years ago). So, let's assume they are 8 ohm speakers.
I have a media amplifier, and have successfully played music over all the speakers so I know that they work.
My wife would like the ability to select which speakers are on or off, so I'm thinking a quick Arduino project and relay board with 8-12 relays... but I'm not sure how to estimate the load, so I don't know how to appropriately size the relays.
Any suggestions on the best way to do this, or should I just get mains-rated relays and over-engineer the heck out of this?

Unless you're working with kilo-watt level audio equipment it'll be hard to under engineer it with relays.

Bear in mind you may need transistors to drive the relays. Don't forget the snubber diodes over the relay coils. You can buy "speaker switch boxes" which might be a simple solution.

Pretty much any "Arduino" relay board on eBay will be more than adequate and contains all the drive circuitry you need.

Relay's will do the trick. You might try FET's or transistors, which might become under-engineering at some point.

You wouldn't even need an Arduino, to be honest. Just put in some switches that power on/off the relays.
Unless you would like to make some kind of web-interface or timing schedule or anything that's not 1-on-1 connected with a switch :)

See a similar project I did: http://iceboundflame.com/projects/multi-room-audio-control-with-rpi and related question about speaker current: http://electronics.stackexchange.com/questions/155779/home-audio-how-much-current-flows-through-my-speaker-amplifiers-output

If you can estimate speaker power, it probably is reasonable to use the ordinary power formula P = I²R for estimating the current the relay needs to handle.  Typically, high-power speakers of a given kind are bigger than low-power speakers of the same kind.  But as you can see from pictures of
5W,
10W, and
40W speakers, some 10W speakers are smaller than some 5W speakers, and some are bigger than 40W speakers, so power estimation based on speaker size can be difficult.
If you have access to the sound source (tuner or player or whatever, connected to an amplifier) you may find output power listed on the amplifier.
In any case, due to the I² term in the power formula, the range of current to plan for is relatively small.  For example, if 5W is going to an 8Ω speaker, 5/8 = I², and I =  0.79 A.  If it's 40W, then I = 2.24 A.  This range is likely to be handled ok by relays sold for ordinary use with Arduino systems.
Note 1: A relay's current rating ordinarily is derated significantly when the relay is used to switch DC or high-voltage AC.  Audio is low-voltage AC and relay derating probably isn't needed.  Note 2: The current a relay can safely switch in a live circuit may be much less than the unswitched current that closed contacts can carry.  This might not be a problem with low-voltage audio.  Note 3: Some commercial high-wattage audio distribution systems operate at higher voltages (see, eg, wikipedia's high-voltage audio distribution systems article, re 70.7 V etc systems); if you have one of those – as amplifier labeling might reveal – the example calculations shown above would need adapting.


text:
Arduino code for continuous rotation for 3 servos with Bluetooth
This code is working, any ideas?
Please check the code - Bluetooth is connecting but the servo motors are not varying with respect to the app sliders.
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo2 = realservo;
      servo2 = map(servo2, 1000, 1360, 0, 360);
      myservo2.write(servo2);
      Serial.println("servo 2 On");
      delay(10);
    }

    if (realservo >= 1000 && realservo < 1360) {
      int servo3 = realservo;
      servo3 = map(servo3, 1000, 1360, 0, 360);
      myservo3.write(servo3);
      Serial.println("servo 3 On");
      delay(10);
    }
  }
}

pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.

pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.
If you do want to use softwareserial try this code https://gist.github.com/emil01/afedff4c3ba4625ebc75 Here i am using pins 2 & 3.
If you do not want to use software serial you can try this code https://gist.github.com/emil01/9a89800e383ec7f95b3f
In your code
  if (bluetooth.available() >= 2 )
  {
   unsigned int servopos = bluetooth.read();
   unsigned int servopos1 = bluetooth.read();

You are performing 2 consecutive read functions, this is not ideal as there can be data loss. A more ideal solution would be send a string with known string terminators and then parsing this string to get your required data.
For e.g. you could send

S1:90\nS2:180\n

from this string you can clearly figure out the start and end of the string and accordingly manipulate the data for your need

then where do I connect my HC 05 tx rx? @evolutionizer

It says broken pipe error

the Tx pin of the bluetooth would go to pin 2 and Rx to pin 3

@AnitaB broken pipe error in your android log?

I changed the bluetooth tx rx pins to 14 and 15 and that did the work!!! BUT it moves clockwise and anticlockwise I also need to make it stop could you help me with it plz @evolutionizer

As pointed by @evolutionizer , you can't do SoftSerial + Serial (native) from pin 0 and pin 1. So the setup should be like this:
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo1, myservo2, myservo3;

int bluetoothTx = 2;
int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  myservo1.attach(9);
  myservo2.attach(10);
  myservo3.attach(11);

  //Setup USB serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

As for the movement for the servo, more information about data sent from Android is needed.
If the app is sending continuous value instead of sending only if the value is changed, you can do this trick:
unsigned int lastpost;
void loop()
{
  //Read from bluetooth and write to usb serial
  if (bluetooth.available() >= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 * 256) + servopos;
    Serial.println(realservo);

    if (realservo >= 1000 && realservo < 1360 && realservo!=lastpost) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1360, 0, 360);
      myservo1.write(servo1);
      Serial.println("servo 1 ON");
      delay(10); //delay to wait servo rotate to desired position
      lastpost = realservo;
    }
...
  }
...
}


text:
What type of hardware could make a ball tilt or roll?
I wanted to know what type of component or module I could use to make a hollow ball move.  I have these hollow plastic balls (think empty easter eggs) that I was going to put a nano in and a sound detector and was just hoping to just get it to move.  I prefer a sort of a tilt left and right effect, but if it just rolls randomly that would work as well.
I was thinking just a simple vibration, but it doesn't really shift the ball at all, so I'm at a loss without building something quite complex with magnets or something.  Perhaps a motor stuck to the side?

A motor with an asymmetric weight will do it. Or, you could be more sophisticated: look at the Sphero BB-8 teardown.

That sounds like a good idea.  I assume you mean attaching the motor to the side, and the asymmetric weight will cause it to rock back and forth.  I will try that, though the motor I ordered off Aliexpress will probably take a month to get here.  :P

The motor (and weight) could be inside the ball. If you slowly increase the speed of the motor. The ball should begin to roll, since the center off mass would be displaced (I believe). You could indeed just fully power the motor, making your ball shake and rock (and be totally out of control).

The ball moves are made by a simple physics principle called Conservation of Angular Momentum. The angular momentum is a property that has any object that rotates and is proportional to its mass and velocity.
To make a ball move you should play with this momentum, using its simplest application, the mechanical gyroscope.
The mechanical gyro is made of a heavy disc rotating at high speed, modulating its velocity you can change the momentum and create a force that will move your sphere.

Maybe some sort of bristlebot?  Try a hexbug nano and see if it behaves acceptably.  The key behind them is a vibrating motor on top of a biased bristle that turns the vibration into a biased motion.

These sound interesting. Do you have any recommended/preferred sites/pages that you could link to in your answer?

Want to make a ball move? Maybe look at how sphero does it by looking at a tear down video. You have to use motors. The motor end has to be connected to a wheel which turns the outer shell. The centre which is not at all connected to the shell should be heavier than the shell.

Read up on Muscle Wire! I'm sure this will be the easiest most elegant solution.
Basically apply a small voltage to a section of this wire in response to sound detection and it will deform, changing the centre of gravity of the ball at rest, making it move. Use two pieces and you will manage to get it to move or tilt in two directions!


text:
Analog sensing needs external power supply
I am using an Arduino Uno board for sensing analog input.
I have connected the board only through a USB cable to my laptop, but the board does not sense analog input,
Is it necessary to use an external power supply ?

What sketch are you using? What do you mean it "doesn't sense"? What sensor are you using? You don't have to use an external power supply for the ADC to work.

I am using "Analog Input" sketch from Examples, where A0 is used as analog in. I have connected 10k pot, to +5, and gnd, center pin to A0 input, 'does not sense' mean there is no effect on LED connected at pin 13 when pot is set to different positions, Later the board seems to have burnt when pot was set to minimum level (zero volt input to A0)

Setting the pot to minimum would not burn out the board, if the connections are as you say they are. An external power supply should not be needed, USB should supply enough power. When you say the board has burnt out, does power LED still work? Does the Arduino still respond to the IDE, if you try to upload "Blink" for example? If Blink still works then the board is probably not burnt out.

I think "burnt" = you blew the polyfuse. This means that you made the wrong connections to the potentiometer, connecting the cursor to either 5V or ground. If the led is always on then you probably connected ground to the cursor (and so the delay between turn on and off is around 1ms), while if the led blinksat about 0.5 Hz you connected +5v to the cursor (and so the period is always 2*1024ms). Double check the  potentiometer pinout with a multimeter, then triple-check it and, if you are really sure it is right, check it again...


text:
Tower Pro MG996R 180° high torque servo controlling using Arduino
We are trying to control a robotic arm using the Tower Pro MG 996R 180° high torque servo.
Firstly we tried to power the servo from Arduino's default 5V, but it didn't work, then we power it from an external source, the servo ran, but only in one direction. Then it stopped rotating. We used the sweep code from the Arduino examples to test the motor.
Here's the code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Can anyone please specify what are we doing wrong, and what is the right way to do it.

Show how you have the servo connected to the Arduino.  Did you remember to connect the ground from the servo to the Arduino ground?

The Arduino's 5V is hardly enough for driving servos. I found that even a simple 9g micro servo draws well over 1A spikes, which causes the board to reset itself.

Power the servo from an external battery pack (e.g. 3xAA or 4xAA batteries will do);
Ensure that the GND of the battery pack is connected to the GND of the servo as well as to the GND of the Arduino;
So you'll have two wires between the Arduino and the motor: GND and the driving signal.

It has to work, servos are pretty standard stuff. However there are many complaints against this particular type at this link Towerpro MG996R 10kg Servo 10kg / 0.20sec / 55g.

These have a label with "towardpro"? Probably counterfeit, should return to shop immediately.

@Gee Bee we did exactly that, except instead of using battery pack, we used an external 5v dc power source. grounds are connected as you described, but its still rotates in one direction and stops rotating at a certain angle. however I can feel the motor running, but the shaft is not rotating... any suggestion ??
at_Paul... its "towerpro**" so I guess its not counterfeit....

Can you try to drive a simple standard model servo? That will rule out any problems of software and connections.
I found that even micro servos draw 1.5A spikes at start, so you need a very good 5V power source. A PC power supply would do, but an USB  charger is not. Although it sounds silly, give a try to the AA batteries. They provide much better transient responses than an off the shelf power supply. I had a project where servo anomalies drove me crazy - all caused by power supply glitches.

Thanks a lot bro... you are a life saver :D :D ... this time we powered the servo directly from computers USB, instead of external power supply.. and it WORKED :D really appreciate your help... and lesson learned... power can be brutally preposterous.

Good that it worked. Note that computer USB is a way too weak to power a brutal servo, sometimes I managed to trigger the short circuit protection of the PC just because of the sudden power draw of a servo can be huge. You may improve the situation a bit by connecting a 1000uF/10V electrolyt capacitor to the power pins of the servo connector, but I advise to use a dedicated power supply or a good battery with small internal resistance.

Si no me equivoco tiene 64 pasos. El servo no deberia ir de grado en grado sino por c/u de los 64 pasos. 180 grado / 6r es 3 grados x cada cambio de paso step to step. ?
Atte.
If I'm not mistaken in 64 steps. The servo should not go from grade to grade but by c / u of the 64 steps. 180 degree / 6r is 3 degrees x each step change step to step. ? Atte.


text:
Flashing dotStar LED
I have a DotStar LED strip that I want to make it blink (e.g., 1 second on, 5 second off in an endless loop).
I tried doing so via the script below but it does not work. Can someone please explain me how to do so?
Script:
#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 10

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{
  strip.show();
  strip.setBrightness(155);
  for (int i=0; i <= 10; i=i+1) {
    strip.setPixelColor(i, 255, 255, 255);
  }
  delay(1000);

  strip.setBrightness(0);
  delay(5000);
}

There's absolutely nothing in that sketch that shows an attempt at achieving what you want. Are you sure you posted the right code?

This is the starting code and I hoped that the delay will cause at least a blink but it did not work.

You will only get a blink if you turn the LEDs on, then delay, then turn them off, then delay again. At the moment you are just turning them on and never off.

The authors of the library are not fans of the setBrightness() method and advise handling it yourself.
The following code should do what you want.
#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60 // This should be the total number of LEDs in your strip

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{

  // loop through each pixel in the control array setting it to the colour mix you want.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 25, 25, 25); // Even 25 on my strip gives reasonably bright flash
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

// Then do it again for the 2nd brightness in your scheme

  // loop through each pixel in the control array setting it to off.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 0, 0, 0);
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

}

Both here and in the OP: If you have 10 pixels, and you go from 0 to 10, you have tried to address 11 pixels. The middle condition check on the for loop ought to be a plain “<“.

The basic idea of the program you're trying to write is:
loop() {
  strip.show(); // Turn LED strip on.
  delay(1000);  // One second, argument is milliseconds.
  strip.setBrightness(0); //Turn LED strip off.
  delay(5000);
  strip.setBrightness(155); //Turn LED strip on.
}

I haven't used the Adafruit DotStar library, so there may be details that I'm missing (like do you need to do a strip.show() after setting the brightness). But maybe this is enough to get you thinking about how to construct the program.
The real joy in hacking with something like this is the experimenting and the learning. Take the time to try to understand how you project works and to predict what will change as you modify the code and how you can tell if it is working the way you expect – that will get you a long way towards being a strong programmer.
When you're troubleshooting something new and/or unfamiliar, one thing that really helps is to break down the problem into simple steps. For example with this project a good first step would be to get the DotStart strip to turn on. Then see if you can get it to turn off. Build it up piece by piece.

Thanks, I updated the script in the question based on your suggestions but it still does not work, any idea why?

Can you describe what it does do, and what you're expecting it to do? "Does not work" is very hard to troubleshoot – especially remotely when you can't see the behavior.

OK, Only LED number 10 in the strip is on and no flashing.


text:
Timer/Counter programming Arduino
I'm trying to blink an LED on an ATMega328P (same MCU as Arduino I think..) using the internal timer but I'm stuck since it doesn't seem to light the LED at all....
#include <avr/io.h>
//#include <avr/delay.h>

void delay(void);

void delay_long(void);

int main(void) {

  DDRB = 0xFF;                   // port B is configured as output   DDRB : 0b11111111
  DDRB &= ~(1<<PB1);             // pin 1 of port B is configured as input  DDRB : 0b11111101
  PORTB = 0x00;                  // pins of port B are low (output) and with no pull-up resistor (input)
  PORTB |= (1<<PB0)|(1<<PB1);    // pin 0 is high (output) and pin 1 is pulled high (input)    PORTB : 0b00000011

  while(1) {
    PORTB &= ~(1<<PB0);
    delay();
    PORTB |= 1<<PB0;
    delay();
    PORTB = ~(1<<PB0);
    delay_long();
    PORTB = 1<<PB0;
    delay_long();
  }

  return 1;

}

void delay(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

void delay_long(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

if I remove the body of the event loop it lights up... so I think I must be missing something in the delay functions...

This looks like an AVR question. You are not using the Arduino core functions (that actually abstract what you are trying to do). In any case you are missing some of the timer configuration.

It seems that the offending line is:
while ( (TIFR0 & TOV0) == 0 )

TOV0 by itself equals 0, so the above loop will never end.
You should use:
 while ( (TIFR0 & (1<<TOV0)) == 0 )

instead.


text:
How can I reduce current drawn by micro SD card module?
I am using a servo along with a sensor and micro SD card module and speaker in arduino uno in order to play a wav file at certain conditions . But when i run the whole system the sd card module is consuming high current and the servo stops working as the current in that is in order of some micro amps. So please help me to solve the problem.

SD cards do use a lot of current. You just need to supply more to your circuit.

I think the problem is somewhere else. Most likely the SD library you are using is blocking all interrupts while it's reading the SD card. When there are no interrupts the servos don't get any signal for a moment, and will stop working.

another good practice might be to add a Transistor to your Systems so that you can physically disconnect parts of your System from the power rail while not in use. this will obviously decrease power consumption...

Don't try to drive all of that from the Arduino regulator. The answer is to get a higher current power supply. You might even need to add filter capacitors on the 5V rails "right in front" of your different systems to protect them from voltage drops when other systems suddenly draw large amounts of current from the 5V rail.


text:
Bool function for color variables
I am new of using Arduino.
I have seen code for color variables that has uses bool function. Is there anyone who can say me how this function connect to the colors of RGB LED matrix? This code has written for Arduino Due and the RGB LED matrix is 32*32.
// Non-constant variables
// Color variables
bool R [32][32] = {1};
bool G [32][32] = {1};
bool B [32][32] = {1};

bool is a data type, not function. you have 3 two dimensionals arrays of booleans. boolean is a datatype for true/false but the size of bool is 8-bit

Without the rest of the code one can only guess why the original author did what they did.  But this appears on the surface as a terrible wast of data space.

// Non-constant variables  .... from this comment line you can tell that the author of the software may not have been thinking clearly


text:
Problem with a code
I have one problem with my code and I'm a beginner and I can't solve it. Can you help me? Thank you so much.
I have this problem:
error: expected unqualified-id before '{' token

And this is my code:
int trigPin = 12;
int echoPin = 11;
long timeperiod, cm;
const int analogOutPin = 9;
int brightness;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){

  if (timeperiod > 50)
  analogWrite(analogOutPin,0);
}
{

  if (timeperiod 10 < 50){
  for(brightness = 0; brightness < 256; brightness++){
    analogWrite(led,brightness);
    delay(10);}
}}
  if (timeperiod < 10)
  analogWrite(analogOutPin,0);

{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(20);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(0);
  digitalWrite(trigPin, LOW);

  timeperiod = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(timeperiod);
  Serial.print("dist=");
  Serial.print(cm);
  Serial.println();

  delay(10);
}
long microsecondsToInches(long microseconds)
{
  return microseconds / 74 /2;
}
  long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29/ 2;
}

Sort out your indenting and you will find that the brackets you have don't make any sense.

The only problem I can see in your code is that your code modules are starting and ending anywhere. See from where till where you want to run a particular line of code. If you writing this code on arduino IDE you will be able to see which the ending of a particular bracket when you keep the cursor on one.

Your problems start here:
void loop(){

  if (timeperiod > 50)
  analogWrite(analogOutPin,0);
}
{

You are missing an opening brace for your if statement, and then have an extra opening brace afterwords. Also, any code inside braces should be indented from the code before it:
void loop(){

  if (timeperiod > 50) {
    analogWrite(analogOutPin,0);
  }

  if (timeperiod 10 < 50){
    for(brightness = 0; brightness < 256; brightness++) {
      analogWrite(led,brightness);
      delay(10);
    }
  }
  //And the rest of your loop function also needs cleanup...

The rest of your loop function needs cleanup as well. You've got bad indentation and mismatched braces all over the place. As @Majenko says in their comment, if you clean up your code formatting then your syntax problems will be obvious.

For example, the first 5 lines:
void loop(){

  if (timeperiod > 50)
  analogWrite(analogOutPin,0);
}
{

Always align your braces, you can do it like this:
 xxx {
    yyy
 }

or
 xxx
 {
    yyy
 }

where xxx and yyy can be one or more statements.
If you align the first 5 lines correctly, you see you should add a {:
if (timeperiod > 50)
{ // <- added
    analogWrite(analogOutPin,0);
}

Also, if you have an if, for or while statement, ALWAYS add brackets, even if it is only one line. Thus:
if (timeperiod > 50)
    analogWrite(analogOutPin,0);

should be written as
if (timeperiod > 50)
{
    analogWrite(analogOutPin,0);
}

This is not a mandatory rule, but if you later misindent something, or add a new line in the body, it is easily forgotten to add the brackets, so you better can do it beforehand.
So (also), it is wise to

align brackets (like explained above)
always use brackets in if/while/loop statements.
always use the same amount of spaces (or a tab) to indent a new level (e.g. after an if, while, loop, or the body of a function).
use new lines between functions; this makes it much easier to read
split up big functions with many brackets, in (sub) functions/methods (not in your case, yet)

Thank you for the answer. I did all of this and it says that I have the same mistake!

@jupepi Edit your question and post your new, aligned and clean code.

I don't see your code changes yet.


text:
Using two leds with one push button
How can I make the code of this project where I will press one time a button,  to turn on the first led (and turn off second led) and when other one press to turn on second led (and turn off the first led).

Your question is barely answerable and shows no effort of trying it yourself. You could try starting out with Arduino Tutorials instead of a project directly.

This is a poor quality lazy question. You need to exert some effort.

From the question it appears that person's first language is not english, it looks like it was possible processed through some translator.

You can do this by keeping the 'state' saved in a variable.
Depending on it's state, the button will have a different effect.
After this effect, the state is updated, so that next iteration it will behave according to the other state.
state = led1
if(buttonpressed){
   if(state == led2){
     led1On();
     led2Off();
     state = led1;
   }else{
     led1Off();
     led2On();
     state = led2;
   }
}

Also check the Arduino example about debouncing buttons.

You do the OP a disservice by giving them functioning code. This allows "copy/paste programming" without learning.

This code isn't completely functional and only to illustrate how using state works. I somewhat agree that I could have used a different example as the case for which this person was asking.


text:
Too little current to trigger a relay?
I try to use this relay with a Arduino Mega. I connected with jumper cables

5V pin to DC+,
GND to DC- and
Digital Pin 13 (because its a lucky number) to IN.

The power LED from the relay is lighting green.
I run this code, which should trigger the relay every 3s for 3s:
int pinOut = 13;

void setup() {
  pinMode(10, OUTPUT);
}

void loop() {
  digitalWrite(pinOut, LOW);
  delay(3000);

  digitalWrite(pinOut, HIGH);
  delay(3000);
}

When initializing the sketch, the red light (from the relay) is flashing and the relay is clicking. But afterwards nothing happens.
With my multimeter I check the currents:

5V to GND = ~5V
Pin13 to GND, when not connected to relay = ~4.7V
Pin13 to GND, when connected to relay = ~1.2V

The relay needs 5V and 5mA triggering current. I don't think the Arduino is not suited, since they promote the relay Arduino.
Any ideas? Do I need some kind of resistor? Or is the USB port from the laptop not sufficient? I used two different Arduino Mega's with two different relays. By the way i don't have a big background in electric.

but what do you want with not so lucky 10?

You are using pin 13, but you set pin 10 as an OUTPUT.
pinMode(10, OUTPUT);
Try changing that to
pinMode(pinOut, OUTPUT);
PS by not setting pin 13 to OUTPUT, digitalWrite(pinOut, HIGH); enables the internal pull-up, instead of "connecting" it to 5V. The internal resistors are around 35kOhm. So pulling a bit of current through them will result in a lower voltage at the pin.

OMG it is working now. I was trying for hours and in the end it was just a wrong number. Thanks a lot.

We've all been there. (-;

There but for the grace of god go I. The hardest bugs to fix are ones where you see what you expect to see, not what's there. Good catch. (Voted)


text:
How to dim background LEDs on TFT display with ILI9341
I have bought a 2.5" TFT shield online, which is equipped with the ILI9341 controller. I need to dim the intensity of the background LEDs to match ambient light.
This particular shield does not provide a pin to control the intensity of the LEDs with PWM via a separate input, so I need to dim the background LEDs of this display via software.
The zip file with the libraries can be downloaded here.
Does one of you know how can issue a command to the TFT display to dim the background LEDs?
Thanks in advance!
UPDATE 1:
I wrote a new function to set the display's brightness by controlling the background LEDs, but something is missing as I can seem to be writing correctly to the display. So I'm trying to get the display to answer to a known command first, like 0x28 (Display Off).
The new function is defined in Adafruit_TFTLCD.cpp:
// Set display brightness (background LED's)
void Adafruit_TFTLCD::setDisplayBrightness(uint8_t x) {
  // Try with 0x28 (Display Off) to see if display reacts
  writeRegister8(0x28, 0);
  return;
}

The function prototype is defined in Adafruit_TFTLCD.h
// New functions
void setDisplayBrightness(uint8_t x);

Then I call the function in my main loop. To make sure, I first write some rectangles on screen, wait 5 seconds, then fill the screen with blue, call the new function and enter an endless loop so no other commands can interfere:
  tft.fillScreen(BLUE);
  tft.setDisplayBrightness(10); // Which really is command 0x28 to test

Any clues what I might be missing?
Thanks!
UPDATE 2:
I got so far as to have the ILI9341 react to some commands, but not all the time, and not to all commands. I suspect there is something in the way you issue the commands that I'm missing( timing?, sequence?, other?)
Here is what I have found out so far:
I can get the display to react to the Display Off command (0x28), but only when I issue it in the begin(..) function. So, the original code in Adafruit_TFTLCD.cpp is like this:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);

If I change it to the following the display reacts by remaining white:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
writeRegister8(ILI9341_DISPLAYOFF, 0); // Display off is declared as 0x28
delay(500);

So, I have a reaction to command 28h.
Then I tried function 0x51 like this in the begin(...) function:
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);
writeRegister8(0x51, 0x80); // Test command 0x51 - background intensity
delay(500);

To no effect :-(
I even added command 0xBE (background PWM frequency) to see if it had any effect, but nothing :-(
void Adafruit_TFTLCD::begin(uint16_t id) {
  ...
  writeRegister8(ILI9341_DISPLAYON, 0);
  writeRegister8(0xbe, 0x80);
  delay(500);
  writeRegister8(0x51, 0x0);
  delay(500);

Also if I issue the 0x28 command:
writeRegister8(ILI9341_DISPLAYOFF, 0)

elsewhere in Adafruit_TFTLCD (e.g. in FillScreen, Fill Rect etc, it doesn't work either).
Any ideas? They would be highly appreciated!

What shield? We need to know that to know if it is even possible. The ILI9341 doesn't provide back-light control like chips such as the SSD1963 does, so you can't do it with the driver. If it is hard wired to +5V you are out of luck.

Other than command 0x51?

Ok, that's a new one on me. I was going on my experience of other ILI chips and this is the first I have seen with an LED driver in it. TBH I haven't used a 9341 display, only a 9340. It's a display I have been meaning to get hold of to implement in DisplayCore but just not got round to it.  Ok, so ignore that comment about no control - there may be control if it is used, and the library may be able to do it or be changed to do it. However, we still need to know what shield it is so we know how it's wired up.

That was an interesting challenge. There seems to be a set of commands for backlight control according to the product specification; brightness level, pwm frequency, brightness transition, etc. It will require writing some new driver functions.

Gents, This is indeed an interesting challenge :-). I bought the board here: http://www.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html    And I asked for the schematic which is here:  https://www.copy.com/s/t%3AwTDo10LVmZFHSxZc%3Bp%3A%252F2.4%2520schematic%25209325.pdf%3Boid%3A74    There are detailed photos on their site and you can see how the shield looks. Unfortunately, the seller doesn't have more information.

@Ignacio: would you have a snippet of code showing how to issue command 0x51? I would like to give it a try.

Nope, just follow the datasheet.

I tried command 51h (Write Display Brightness) by writing 0x51, xx (for xx I tried different values) to no avail. I also combined it with command 53h (Write CTRL Display) with 0x53, 0x28  and 0x53,00 also without results. Looks like I need the correct sequence of commands + parameters

Did the 0x28 command work as expected?

I could get the display to react to 0x28, but only at display initialization, not elsewhere. Please see my update #2

That is insane that they would hard wire it. Why write a datasheet if it's not going to be correct?
I evidently have the same display!
Maybe we can put the display to sleep. That is another command "10h" and leave sleep is "11h."

I agree it's insane to kill this functionality :-(  Putting the display to sleep doesn't work because I still need the display to be alive at night (but dimmed down).

I got in contact with the manufacturer of the shield, they informed that the background LEDs are hardwired and not controllable via the ILI9341. So, it is not possible to dim the background light in this shield
:-(
I will look for another TFT shield and make sure it's dimmable before buying.

That's strange. there is no BL pin? Have you got the schematics or at least a picture of the module?

No, there's no BL pin available on this board. I asked the manufacturer and they responded that this pin is hardwired and I don't feel like cutting/soldering PCB tracks.

Too bad :/ Such a stupid decision by the manufacturer.

Yep. In the end I abandoned the project because of other reasons. I found out that other boards communicate serially and provide a way to dim the backlight with a command. It means researching TFT shields before buying :-)

Most of thees cheap Chinese LCD modules have the LED backlight hardwired to Vcc and GND and cannot be controlled.
However, after inspecting the module I have and some similar ones online I found that most have the Back-light LEDs pins available through the LCD panel flex cable. If yours is similar to the one in the picture then you will notice that the main flex cable is for the LCD itself, and there are usually two other flex cables connected to it. The one on the left is for touch panel (if equipped), and the one of the right is for the back light LEDs (sometimes it is connected on the backside of the flex).

In this panel and on mine (a little different from this) they are labeled as K1, K2, K3 and K4 which are mostly the Cathode side of the LED (negative side) and they are exposed as separate pins in the main flex cable, while the Anode is soldered to the main flex cable Vcc plane and cannot be easily accessed without desoldering the LED flex cable.

So in ordered to control the backlight you have to cut the trace on the PCB (not the flex cable) and connect it to a transistor which you control through the Arduino.

Double check the polarity in your LCD panel, it could be different from mine.

I have successfully dimmed the backlight on a ili9341 by simply modulating the pin the LED pin is connected to.
Note, I am using a teensy 3.2 your mileage may vary.
ledPin=32;

void loop() {
analogWrite(ledPin, 60);

After looking at the schematic (mine is different) but on pin 16 is labeled as BL. If that is indeed the power for the LED backlights then a voltage applied to it should vary the brightness.  Caution:You need to know how much current the LEDs are pulling. If over the limit for a PWM pin you will have to run it through a transistor to boost the current.

It looks like it should be controllable with command 0x51.
I would modify the library and add a new method to the Adafruit_ILI9341_8bit_AS class - something like:
void Adafruit_ILI9341_8bit_AS::setBacklight(uint8_t brightness) {
    writeRegister8(0x51, brightness);
}

Then you can change the brightness by calling that method on your TFT object in your sketch.  (Don't forget to add the prototype to the class definition in the header file of course).

Hi Majenko, I followed your advise but I still can get this to work. Please see my update in the original question


text:
Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?
I have an Arduino.
I'm not sure if RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?
For example, do I treat RX1 and TX0 as RX and TX in the Arduino IDE when coding?
This is the chip I have. On the chip it says "ProMini R160JAC6v" and when I program it, it programs under 5V 16MHz with ATmega 328. Notice RST RX1 and TX0 are on the top left corner.

It's not RX1 and TX0 but RXI and TXO
That is receive input and transmit output,
Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.

No, it is not mnemonical. It is about PIN numbers: 0 for RX and 1 for TX, as seen in the table here: https://www.arduino.cc/reference/en/language/functions/communication/serial/. However, you invented a good one.

Yes you treat them the same, they are the same pins.
It looks like (in the photo) you're connecting a bluetooth module.
Be careful when uploading your sketch.  If you connect something to TX/RX (pins 0 & 1) it may be necessary to disconnect it for arduino-uploading to work.
You may find it a more convenient solution to declare a SoftwareSerial on different ports and use that for the bluetooth communications.


text:
Multi-file arduino esp8266 sketch sharing a reference to server
Transferred from stackoverflow on the advice of @Gee_Bee:

I can get Writing a Library for Arduino to work as well as
  Breaking a sketch into multiple files and Classes within Classes
  - Initialiser Lists. I can even get extern references to variables to work but referencing the an instance of ESP8266WebServer in
  different files is still beyond me.

As my sketches get bigger, the code looks awful as one file and the number of global variables is too high.
For the webconfig part of my sketch the device attempts to get online and if it fails it scans for available Wi-Fi networks, goes into Access Point Mode, starts a server, sends the list of SSID's and listens for a response of an SSID/password pair. The server is only for the configuration.
Ideally I'd like the cleaned up main.ino file to look like
    #include "config.h"
    void setup(){
        Serial.begin(115200);
        Serial.println();
        Serial.println("--------------------------");
      Serial.println("ESP8266 multifile");
      Serial.println("--------------------------");
      getOnline();
    }
    void loop(){
        if(IN_CONFIG_MODE){
           server.handleClient();
        }
    }

with a config.h something like..
    #ifndef config_h
    #define config_h
        #include <ESP8266WiFi.h>
        #include <ESP8266WebServer.h>
        ESP8266WebServer server;
        void getOnline();
    #endif

and then a config.cpp where it does all stuff described above yet gives the main.ino program access to the server instance so it can listen in the main loop.
#include "config.h"
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

char *espssid = "espAPsb";
char *ssid = "street_no_vale2";
char *pwd = "jjjjjjjjx";
char ssids[300];

extern server(80);

void handleRoot(){
    server.send(200, "text/html", "
root of espAPsb AP server
");
    //send json of available ssids
}

void scan(){
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");
}

void setupAP(){
    WiFi.softAP(espssid);
    server.on("/", handleRoot);
    server.begin();
  Serial.println();
  Serial.print("connected as AP ");
  Serial.println(espssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP());
}

void getOnline(){
    WiFi.begin(ssid, pwd);
  int tries =0;
  int success=1;
  while (WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
    tries++;
    if (tries==15){
      success=0;
      Serial.println("WiFi not connected");
      scan();
      setupAP();
      break;
    }
  }
  if (success){
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }
}


text:
How do I calibrate an ESC after connecting it to an Arduino?
I'm trying to connect an Arduino to an Electronic Speed Control and failing horribly. I'll explain what I've done so far, and then I'll explain the problem.
Before we get there, here's the list of parts I'm using:

Arduino Uno (genuine)
6V to 8.4V rated 18300 RPM 350 g-cm brushed motor.
Traxxas XL-5 brushed motor ESC. 1600 Hz is the highest PWM signal it accepts, if I'm not wrong.
Venom 4200mAh NiMH 8.4V battery pack (will replace soon with a 7.2V).

So I first connected the ESC to the motor. The connection is this bullet lead connection (the connection seems intact), and then the ESC to the Arduino. I connected the white wire to pin 9 and the black wire to ground. If I'm not wrong, this is the standard servo motor setup. I then plugged the Arduino into my computer, which has an intact USB port. Lastly, I connected the battery pack to the ESC.
Now I've tried to upload some basic code to try and calibrate my ESC, but it just plain our refuses to work. Under no circumstances will the motor run.
The code I'm using just sends the signal sent by the signal monitor.
I'm a complete noob to Arduino, so I don't know what could be wrong. The program I have in mind needs to be able to run while not connected to the computer, activate when a push-button switch is activated, run the motor for a certain distance (which involves an encoder, right?), and then stop.
Any pointers or things I could be doing wrong?
int value = 0;
Servo myservo;
void setup() {
    firstESC.attach(9);    // attached to pin 9
    Serial.begin(9600);
}
void loop() {
    myservo.writeMicroseconds(value);
    if(Serial.available())
        value = Serial.parseInt();    // Parse an Integer from Serial
}

and the one here:
#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 700
#define MOTOR_PIN 9
Servo motor;
void setup() {
    Serial.begin(9600);
    Serial.println("Program begin...");
    Serial.println("This program will calibrate the ESC.");

    motor.attach(MOTOR_PIN);

    Serial.println("Now writing maximum output.");
    Serial.println("Turn on power source, then wait 2 seconds and press any key.");

    motor.writeMicroseconds(MAX_SIGNAL);

    // Wait for input
    while (!Serial.available());
    Serial.read();

    // Send min output
    Serial.println("Sending minimum output");
    motor.writeMicroseconds(MIN_SIGNAL);
}
void loop() {
}

^shamelessly copied from the internet

What is the code?

just added the code c:

@a_human_mistake Please use the Code button in the editor to format code as code. Your current method did not look nice. :)

oh man, I tried and it wouldn't allow me to put newlines in the code. turned out really weird when I used the mini-Markdown formatting. Thanks for editing to make it look decent!

@a_human_mistake could you describe what the led is doing on your ESC?

http://chat.stackexchange.com/rooms/36489/discussion-between-a-human-mistake-and-rsm

The is a standard with RC connectors, that is Black always goes to ground white/orange goes to the signal and red/brown goes to 5V.
I don't know if you have made a typo, but you need to connect the white to D9 and the black to GND. Here is a instructables post, it describes using a brushed ESC step two reiterates the colour code standard.
You would also need a rotary encoder or shaft encoder to tell the distance moved, there are lots of ways to achieve this from simple(coded disk and IR arrangement) to custom made PCB add-ons.

Oops, I did make a typo. Thanks for pointing it out. I don't technically need to measure the distance I move, only make it move a certain distance. I considered using a quadrature encoder, but I have enough problems with everything else that the plan was basically benched.

@a_human_mistake do you have a RC receiver and transmitter you could use to test the ESC. Also I will move this to a comment rather or delete it.

I can check and see -- is it possible that it's a problem with the ESC?

@a_human_mistake there may be the annoying possibility that the ESC might have had too much current pulled through.

So if I were to buy a new ESC, what would I look for in order to avoid that happening? Can I avoid that problem in any way?

@a_human_mistake you can avoid an ESC burnout by making sure , as a rule of thumb, that the current rating for continues use is at least 10A higher than the motor's rated current, and then the burst/surge current would also be high to handle start up draw. Do you have the specs of your current motor's current draw?

"peak current draw 50+ amps" is all it says on the website. I feel like that's a lot... https://traxxas.com/products/parts/escs/3018Rxl5waterprooflvd <- ESC, http://www.amazon.com/RS540-Sport-Tuned-Motor-All/dp/B00061HB0K <- motor

Calibration can be done by sending the low throttle and high throttle values through the Serial monitor.Here's an instructable i have made using NODEMCU.Check this out.May be it helps.


text:
Pseudo-code of a program
I have written a code but I am facing a problem in pseudo-code that I am not able to change this code, so can anyone help me in translating the Arduino IDE program code to pseudo-code?
#define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include<DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "py0oKurvtk_Rv2GGkKtghpKqlxLQug8F";
char ssid[] = "Hostal1";
char pass[] = "shakajutt7867";
DHT dht(D4, DHT11);
SimpleTimer timer;
int Relay = D5;
int PIR = D3;
void sendSensor()
{
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  int value = digitalRead(PIR);
  if (value == 1)
  {
  digitalWrite(Relay, HIGH);
  Serial.print("Detected");
  Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Detected");
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  else if (value== 0)
  {
    digitalWrite(Relay, LOW);
    Serial.print("Not Detected");
    Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Not Det");
  lcd.setCursor(0,1);
  lcd.print("T:");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  Blynk.virtualWrite(V7, value);
  Blynk.virtualWrite(V5, humi);
  Blynk.virtualWrite(V6, temp);
  delay(1500);
}
void setup()
{
  pinMode(Relay, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(Relay,LOW);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  lcd.begin(16,2);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  timer.setInterval(1000L, sendSensor);
}
void loop()
{

  Blynk.run();
  timer.run();
}

What exactly is your problem in writing this as pseudo code? Do you understand, what the code does (since this is essential to write it as pseudo code)?

what do you mean by pseudo-code?

You can format it by selecting the code and pressing ctrl-k

Although I know how the program line by line but how to write #INCLUDE libraries and there are many lines that I can't explain /?

Michel Keijzers ........... I couldn't get your point? How? Although ctrl+k doesn't work.

So it is more about understanding the program? If yes, then I can write an answer. What do you mean with "how to write #include libraries"? Pseudo code doesn't need any includes, since it is not compilable anyway. You just write, what the code should do on a level of higher abstraction.

"Pseudo-code" isn't a programming language. It is just a term that we use when we write code that looks like code but can't be compiled, because it's half-English, half-code. You write pseudo code when you want to communicate to another human how code is supposed to work without getting bogged down in the details.