text:
Include Git tag (or SVN revision) in Arduino sketch?
Is there any way to get the current Git tag/commit identifier into an Arduino sketch binary?
For normal desktop program development, you can pull some tricks with the Makefile (as pointed out in this StackExchange answer). However, there is no Makefile for an Arduino sketch. Right?
I could make a batch file that I run before every compile, but there is the very real possibility I will forget to run it, and incorrect version information is worse than no version information.
At the moment, I am using the preprocessor macros __DATE__ and __TIME__ to try and identify what version is running on the board. This works, but tracking backwards from a compile date/time to a source control commit is more guesswork than anything.

You could ditch the Arduino IDE and go for a Makefile-based development.

tracking backwards from a compile date/time to a source control commit is more guesswork than anything - why? Commits have the date in them.

@EdgarBonet I think that is what I am looking for! I will give that a try. If you post that as an answer, I can accept it.

Inspired by Cellie's answer, I investigated further and found a similar
method that can be implemented using the regular interface of the
Arduino IDE.
It appears that GitHub user Wackerbarth, while facing the very same
problem, opened an issue on the Arduino bug tracker:

It would be very useful to be able to add a recipe to the platform
  specification that is executed at the start of the build process.
  (pre-build)
In particular, my use case is to generate version strings which will
  be incorporated in the Rom image based on information extracted from a
  SCM repository.

He went on to submit a pull request for adding “hooks” to the
build process, which made it to release 1.6.2. See the documentation on
these Pre and post build hooks.
Here is how you can use this feature for including git commit
information into your program (tested on Arduino 1.8.5 / Ubuntu 16.04):

Save the following file under the name make-git-version, somewhere
in your PATH, and make it executable:

#!/bin/bash

# Go to the source directory.
[ -n "$1" ] && cd "$1" || exit 1

# Build a version string with git.
version=$(git describe --tags --always --dirty 2> /dev/null)

# If this is not a git repository, fallback to the compilation date.
[ -n "$version" ] || version=$(date -I)

# Save this in git-version.h.
echo "#define GIT_VERSION \"$version\"" > $2/sketch/git-version.h

Locate the file named platform.txt in the Arduino installation
directory (currently in arduino-1.8.5/hardware/arduino/avr for the
AVR boards). In the same directory, create a file named
platform.local.txt with the following content:

recipe.hooks.sketch.prebuild.1.pattern=make-git-version "{build.source.path}" "{build.path}"

In your sketch, include "git-version.h" and use it like so:

#include "git-version.h"

void setup() {
  Serial.begin(9600);
  Serial.println("This is version " GIT_VERSION);
}

Create an empty file in your sketch directory named git-version.h.

Note that the git-version.h in the current directory is only needed
for the first compilation. The real git-version.h will be in the
temporary build directory.

I struggled with Arduino (ESP32) versioning also.
To make it somewhat more practical and less error prone I made some scripts to assist this process.
Using these scripts is as easy as adding them to your sketch folder and adding
#include "gitTagVersion.h"
...
Serial.println( sketchVersion );

to your Arduino sketch.
That is all that is needed.
The output in the example above will be something like v1.0.0-3-gab3fb04.
That breaks down to tag v1.0.0, we had 3 commits since that tag, at commit ab3fb04.
HOW TO INSTALL AND USE?
There are 2 scripts involved, the first script is a replacement for the Arduino  Verify button.
Save it as verify.sh:
echo "const char * sketchVersion = \"$(git describe --tags --always --dirty)\";" > gitTagVersion.h
~/arduino-1.8.5/arduino --verify test.ino
rm gitTagVersion.h

And the second script replaces the Upload button.
Save it as upload.sh:
echo "const char * sketchVersion = \"$(git describe --tags --always --dirty)\";" > gitTagVersion.h
~/arduino-1.8.5/arduino --upload test.ino --pref custom_DebugLevel=esp32_none
rm gitTagVersion.h

Some things to note about these scripts:

The scripts REPLACE the buttons.
You won’t be able to use the buttons anymore, as these buttons don’t
generate the necessary version info from git.
Using them will result in this error:

fatal error: gitTagVersion.h:    No such file or directory

The scripts are hardcoded to use Arduino 1.8.5 and have to be updated
if you update your Arduino IDE.
These script only work in Linux with a vanilla Arduino install.
If you use Windows, or are on a Mac the scripts will not work.
To change the debug output (using the LOGx_ESP macros) on ESP32
builds, change the custom_DebugLevel in the Upload script to
esp32_xxxx, where xxxx is none, info, error, debug or verbose.

I posted this also on my blog and esp32.com

I would drop the -n in echo -n '";': it is customary in Unixland that text files (specially source code) end with a line feed. Also, you could replace the first three lines of each of those scripts by echo "const char * sketchVersion = \"$(git describe --tags --always --dirty)\";" > gitTagVersion.h

I met the same problem and based on the previous answers I wrote this script for Arduino IDE. I'm using it successfully on different OSs for many months to now. In the repository, you can find the instructions to install it.

If you're using Platformio, add this in platformio.ini file
build_flags =
    !echo '-D GIT_VERSION=\\"'$(git rev-parse HEAD)'\\"'

And use it like this:
Serial.printf("Firmware version: %s\n", GIT_VERSION);

Check out relevant docs:
http://docs.platformio.org/en/latest/projectconf/section_env_build.html#dynamic-build-flags

Inspired by Edgar's Bash script, I wrote a Windows Batch script do almost the same in adition to copying HEX file from the temp build directory to the project directory and insert commit hash, date, branch name and tag to it's name. I wrote a short article on how to use GIT to manage firmware versions.
:: How to use:
:: Add this file to you Arduino project directory and add the following line to platform.txt from Arduino core files
:: recipe.hooks.sketch.prebuild.1.pattern = {build.source.path}\fw_ver.bat GIT {build.path} {build.source.path}
:: recipe.hooks.objcopy.postobjcopy.2.pattern = {build.source.path}\fw_ver.bat SAVE {build.path} {build.source.path}

@echo off

:: arg1 -> "GIT" print version, commit number, brnach name and commit date , "SAVE" copy the .hex file from temp build directory to project directory
set arg1=%1
:: arg2 -> path to temp build directory
set arg2=%2
:: arg3 -> path to project source files
set arg3=%3

cd %arg3%

FOR /F "tokens=* USEBACKQ" %%F IN (`git describe --match^=NeVeRmAtCh --always --abbrev^=7`) DO (
SET commit=%%F
)

FOR /F "tokens=* USEBACKQ" %%F IN (`git show -s --format^=%%cd --date^=format:%%y_%%m_%%d %commit%`) DO (
SET date=%%F
)

FOR /F "tokens=* USEBACKQ" %%F IN (`git rev-parse --abbrev-ref HEAD`) DO (
SET branch=%%F
)

FOR /F "tokens=* USEBACKQ" %%F IN (`git describe --abbrev^=0`) DO (
SET ver=%%F
)
::Export to version.h
ECHO #define FW_VER "%ver%" > version.h
ECHO #define COMMIT_NUMBER "%commit%" >> version.h
ECHO #define COMMIT_DATE "%date%" >> version.h
ECHO #define COMMIT_BRANCH "%branch%" >> version.h

IF "%arg1%"=="GIT" (
@echo on
@echo version:%ver% Commit:%commit% Branch:%branch% Date:%date%
@echo off
)
IF "%arg1%"=="SAVE" (
@echo on
@echo Save fw_%ver%_%branch%_%date%_%commit%.hex to %arg3%
COPY "%arg2%\fw.ino.hex" "fw_%ver%_%branch%_%date%_%commit%.hex"
)

I'm not sure what the commit ID would prove. I use git for source control for my Arduino sketches, but a particular upload might be halfway between the previous commit and the next one. That is, the code on the board might not match any particular commit.
The date/time would at least identify approximately where in the commit stream the code is.
A possibility would be to run a cron job that periodically (say, every minute) updates a .h file with the current commit ID from the branch, and include that in the sketch.

It is true that you can be compiling with a dirty working copy, but at least you know for sure what commit you started with for that firmware. With just a date, you can't know for sure which branch was compiled, especially if multiple branches were updated at about the same time. And finally, using date/time leads to problems with time zones, lending even more ambiguity to exactly what was compiled.

If you say so. A "dirty working copy" could be anything. I'm not sure what the original commit ID proves. using date/time leads to problems with time zones - how many time zones are you in? I'm in one, personally.

I still work with friends from college, and we now live in different states. The time zone thing has bit me in the past, I'm not trying to be a jerk or anything. Knowing the original commit ID lets me know what branch the sketch came from, at least. I do agree that a dirty working copy can indicate anything, but generally it is close to the base commit.

People have made makefiles to compiler their Arduino stuff. I can't think of any really simple way of doing it, short of my suggestion of a cron job to update a .h file regularly.

If you want to do Makefile-like tricks, one possibility is to use a
Makefile-based workflow instead of the Arduino IDE. There are a few
generic Arduino Makefiles floating around the Web. One quite popular is
Sudar Muthu's Arduino
Makefile. With it, you just
write a small per-project Makefile that sets a few variables and then
includes the generic Makefile. There is one limitation with this
approach though: the Arduino IDE normally modifies your .ino file before
submitting it to the compiler, in two ways:

It #includes <Arduino.h>
It writes prototypes near the beginning of the program for every
function you define.

Sudar Muthu's Makefile does include Arduino.h (it does not touch your
code, using instead the -include gcc option), but it does not write
the function prototypes for you. It is thus not 100% compatible with the
Arduino IDE.
Another possibility would be to completely write yourself a Makefile
that calls Arduino
Builder. This should be
100% compatible with the IDE.


text:
Understanding schematics: resistors attached to Attiny85 pins V-USB
I'm currently trying to create my own Attiny85 usb thumb(to mimic an joystick). I understand that I have to limit the voltage on the attiny's pins that are connected to the D+/- pins from the usb. In various schematics there are some pull-up resistors used with some zener diodes(that will drop the voltage that exceeds 3.3 V).(taken from insidegadgets)
Question:
#1
I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid an regulator?(as other schematics incorporate in them)
#2
Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.
#3
An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.007=171 ohms.That resistor attached to the attiny would produce a 1.2 drop).
#4
There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

While 1.2/0.7 ~ 1.71, 7 mA is not 0.7 amps but 0.007, giving 171Ω rather than 1.71.  Also, please edit your question and provide an attribution for the schematic.  I'm wondering why the zeners are on the USB side of the 68Ω resistors instead of on the '85 side.

@JamesWaldby-jwpat7 The zeners are on the USB side so the current from the GPIO pin is limited before being sunk through a zener. You don't want to overload the current from the GPIO pins, do you?

@Majenko, ok, I see that now

I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid the regulator?

If you have a 5v supply, as in a USB connection, and you want to run off 5v, then you do not need any regulator.

Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

Because only that pin needs pulling up to indicate the presence of a device on the USB bus.

An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.7=1.71 ohms).

You can only use a resistor to drop a fixed voltage of you have a fixed current. The current you quote is the chip's supply current, not the GPIO current, which you cannot know or predict. Also, if you did use a resistor it would operate both ways and the 3.3V coming in would also be reduced so the MCU will not be able to read the data.
Even if you did know the current you would find it was very small so a huge resistor would be needed, which would induce intolerable amounts of noise. It would also violate the USB specifications.

There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

They are to protect the ATTiny's IO pins. Without those the zener diodes will sink way too much current from the IO pins and damage them. They also act partially as termination resistors for the USB bus (which should be 20Ω).

Comments are not for extended discussion; this conversation has been moved to chat.

source: Stack Exchange

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

sort: votes


text:
Arduino Voice recognition
Is it possible to use only arduino to do voice recognition? or maybe with esp32 no internet.
I found speech recognition chip but that's not what i want
I got esp32 esp8266 and arduino board.
I would like to know if somebody could do it

No. It's as simple as that. No. Voice Recognition is a very very complex task. To do it fast and well in a "general" way takes a neural network, or a very powerful PC (note: all common ones now use online resources to do all the work).
A voice recognition chip generally is pre-programmed to respond to specific words.

Correction: You don't actually need a cloud-based service. It might take a little while, but Mozilla's Deepspeech (https://github.com/mozilla/DeepSpeech/) is capable of doing it on-device. IIRC Raspberry Pi's are capable enough to do it, but only just.

And how does that relate to doing it on an Arduino?

True. Just wanted to point out that it's technically possible to do locally, given the right equipment :P

Maybe if we were on the Pi SE site your comment might be taken a little more seriously. But we're not. Anything can be done if you have the right equipment.

The answer to can it be done is inherently yes at some point, making this answer wrong... it's as simple as that.

@user2305193 No, it's not. I challenge you to do it. Do voice recognition with just an Arduino, and maybe an ESP32 with no internet connection. Go on. Show us how. No extra hardware. No VR3 module. No Kendryte K210. No connection to a PC. Nothing. Just an Arduino. 9 times out of 10 when someone says "An Arduino" they mean "An UNO". I'll be nice. You can use a Mega2560.

A simple speech (word) recognition can be done. I made one in 1998. Chip was atmega16. Now there are ready to use sound detectors and you just use digital out. https://s.click.aliexpress.com/e/cn6IwDhI
From that digital signal you get frequencies, durations and delays. First output results to serial and then get key features, ranges of voice command or a word. Put those boundaries to table and there you have it. It works like a charm with few words but then you have to make indexed database or something to keep it reasonable fast. I had only 8 commands and recognition was about 85% There were only 2 times when it "hear" some other word as a listed word. Language was finnish. I assume that it might lower those false positive occurrencies. As you see this is nothing compared to real systems but can be easily used in non critical solutions. ESP32 can do so much more that I think this might be interesting..
You may also want to look -> https://github.com/MhageGH/esp32_CloudSpeech

Marmenmu, Form my understanding. Only you can speak to the microphone right? It use your frequency or tone. or only you that can make the robot understand.

Also what do i need to know to make frequencies recognition with atmega16

This method cannot handle high noise levels. First use the trimmer that it only activates when command is spoken at close distance of microphone. Then make "capture program" that only passes word parameters to pc. Speak desired word several times and you get key values of frequencies, delays and order of those. You have to just watch one pin and find minimum value how long the frequency alias tone must be same. Write those packets to array and then compare predefined commands that tells order and min and max lengths of frequencies and delays. https://forum.arduino.cc/index.php?topic=105289.0

Yes it is possible - see here for ESP32 example:
https://github.com/espressif/esp-adf/tree/master/examples/speech_recognition/asr

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


text:
Standalone Arduino
I have an Arduino Uno and I am using arduino 1.0.5 IDE. I followed he procedures for bootloading an atmega328P-PU on a breadboard using an Arduino Uno from the link:
https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
I uploaded the ArduinoISP sketch first, made the connections(using the External Oscillator) and then wired it up. Then, I selected the programmer as Arduino as ISP, selected the board as Arduino duemilanove w/ Atmega328P . Then I selected the correct serial port and clicked Burn Bootloader. I got the following errors:
avrdude.exe: stk500_program_enable(): protocol error, expect=0x14,
resp=0x50avrdude.exe: initialization failed, rc=-1 Double check
connections and try again, or use -F to override this
check.avrdude.exe: stk500_disable(): protocol error, expect=0x14,
resp=0x51

How to solve this issue? Also, can I upload the bootloader directly by using it on the Uno in place of the original chip. If so, how?

On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch) source (PS <rant>I'm getting very annoyed by the inaccuracies on the arduino website. New users continue to have to figure out why things don't work, while the problem has been known for years.</rant>)

See How to make an Arduino-compatible minimal board.

Also, can I upload the bootloader directly by using it on the Uno in place of the original chip.

No, a blank chip cannot install its own bootloader. You use a second chip. My page above describes how to do that. An alternative is a stand-alone ICSP programmer, which can be purchased for around $20. The tutorial page you linked uses your Uno as a stand-alone programmer.
I think my method of using a Uno as a programmer is easier, frankly.

Hey, I followed your procedure for making Arduino Compatible minimal breadboard. I had to use an external oscillator. But when I run the code my output is not what it should be. I get the following output
"MD5 sum of bootloader = 0x6A 0xE5 0x9E 0x64 0x85 0x03 0x77 0xEE 0x54 0x70 0xC8 0x54 0x76 0x15 0x51 0xEA
No bootloader (all 0xFF)"
What should i do now?

Please edit your question, and post the exact output (copy and paste) from the bootloader uploading program. Turn it into "code format" by selecting all of the output and hitting Ctrl+K.

I had the same problem; I never figured it out. I eventually threw down some cash for am ICSP (I got the FreeTronics USBASP), and have never looked back. In fact, with an ICSP, you don't even need a bootloader. It's also real easy to solder a 6-pin header onto your custom soldered board; then you will realize you don't need an Arduino at all, just an Atmel chip.

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


text:
Arduino wire can't send char
Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver.
I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like Wire.write("blablabla"); it pass. But when in char is NRF data code crashing when go to "Wire.write".
/*
*/
#include <Wire.h>
#include <SPI.h>
#include "RF24.h"

char datar = '';

//Konfiguracja
const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
//-- Konfiguracja

void setup() {
  Serial.begin(9600);
  Serial.println("LOL");
  Wire.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1, pipes[0]);
  radio.openWritingPipe(pipes[1]);
  radio.setChannel(78);
  radio.setAutoAck(true);
  radio.startListening();
}

void loop() {

  int len;
  if(radio.available())
  {
  len = radio.getDynamicPayloadSize();
  radio.read(&datar, len);
  delay(5);
  Serial.println(datar);
  Wire.beginTransmission(7);
  Wire.write(&datar);
  Wire.endTran345smission();
  radio.printDetails();
  }
  delay(5);

}

What  are the input of the write function? Are you sure you need to pass a pointer or  a variable

Your problem is here:
char datar = '';

...

 len = radio.getDynamicPayloadSize();
 radio.read(&datar, len);

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into datar more than one byte. This overwrites other parts of memory and the program crashes. You need to make datar larger, eg.
char datar [50];

The exact size would depend on your maximum payload size.

Absolute maximum size NRF24L01+ supports should be 32 bytes. (And it wouldn't hurt if one also updated their RF24 libraries through the IDE)

I think the answer is a combination of Nick and Mathieu's answers.
Like Nick said you haven't assigned any memory to datar, so this is probably causing a crash because of buffer overrun.
Now to the call to read.  Mathieu said you are passing a pointer into the function when you probably didn't mean to.  But if you put Nicks change in then you do need to pass in a pointer to the character array.  You can do this by radio.read(datar, len); because the character array is a character pointer.
You do not want to pass a pointer to a character pointer &datar because that would mean the function was able to move the memory that you have allocated.
Also, you need to prevent buffer overflows in the "new improved" code by checking that the value of len is less than or equal to the value you allocated when you declared the data buffer (i.e. 50).  Because you are using a number in two places you should declare it as a constant at the top of the file.
const int MaxBufferSize = 50;
char datar[MaxBufferSize];
...
len = radio.getDynamicPayloadSize();
if (len > MaxBufferSize)
  len = MaxBufferSize;
radio.read(datar, len);

Hope that helps.

The  code crash because you pass an memory address to the write function if you look to the arduino doc you pass a variable to the function therefore just writing datar as argument will end your problem

Not really, unless the payload size is only one byte.


text:
Cannot retrieve data from homemade ECG
For the past couple of weeks, I have not been able to find a solution to my problem.  My problem is that I cannot retrieve the data from my homemade ECG that I created from Arduino.  I am a total amateur at this, but I'm pretty sure it's a circuitry issue.  Here is what my circuit looks like now.  (Note: the thing that says 'Dual O' on the far left is the instrumentation amplifier, not an operational amplifier like the one near the middle)
Here is the code I'm using:
const int  signal = 5;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

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

previousBeatTime = millis();
}

void loop() {
delay(500);
input = digitalRead(signal);

if ((input != lastinput) && (input == HIGH)) {
    // If the pin state has just changed from low to high (edge detector)
    currentBeatTime = millis();

    period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
    previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
}

lastinput = input; // Save the current pin state for comparison at the next loop iteration

// Detect if there is no beat after more than 2 seconds
if ( (millis() - previousBeatTime) > 2000 )
{
    Serial.println("dead");
}
else
{
    if (period <= 0)
    {
        frequency = 0;
    }
    else
    {
        frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
    }

    Serial.print(frequency);
    Serial.println(" : alive! ");
}
}

I would appreciate if someone could get back to me as soon as possible.  Thank you!
EDIT:
Here's a schematic.  I used Fritzing, and since I am a total beginner at this, it looks like a complete mess.  Anyways, here it is:

Thank you for your help.

I looked at this, but am not prepared to try and decode your layout diagram. You may have more luck with a circuit diagram.

Hey, sorry about that, here is my schematic.

"cannot retrieve the data from my homemade ECG" - what do you mean by that? Can your host (PC for this matter) can identify and properly connect to the JY? If so, and it connects but you do not get anything on the PC side, try putting some Serial.print("dummy") in your setup() method to see if the serial terminal is configured properly.

Has any part of it ever worked? What have you done to it since?
My approach to debugging this would be to
 - Temorarily replace the Bluetooth with wired serial communication;
 - Comment out, or stub out(*), anything you aren't utterly and completely confident in.
 - Get some minimum amount of hardware and software working.
 - Add back one piece of hardware or one section of code at a time, fixing whatever you have to to get it working again.
 - Repeat, until everything is back together and playing nicely.
(*) Stubbing is the technique of replacing a function or a section of code with something trivial (and therefore hard to get it wrong!) that lets the rest of the code mostly work.
Suppose you had written a digitalRead() function. (I know it's a library function and we have total confidence in it, but for a moment, just suppose....) You might replace the contents of your digitalRead() with a single statement:
int digitalRead(uint8_t pin){
   // untested code commented out here
   // ...
   return(4);  // any value that means something to the calling code
}

Now you can work on the code that calls your digitalRead() without having a working digitalRead(). The caller will only ever get the same value every time it calls, but that may be enough get some part of it working until you can come back and fix your digitalRead() function.

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


text:
Is my leonardo broken? Is there a way to make it work?
backgrounds
I bought arduino leonardo and connect it to Ubuntu 15.04.
With arduino IDE 1.0.5(from Ubuntu official repo) running in sudo, the arduino was recognized as /dev/ttyACM0.
So I tried to upload sample sketch Blink to the port ttyACM0 with settings of Leonardo, but every time I tried to upload IDE said that serial port is wrong. and then actually leonardo was recognized as ttyACM1. If I set ttyACM1 and retry, leonardo moved to ttyACM2; and so on.
So I searched some websites and installed oracle-java7-installer package and Arduino IDE 1.6.5 from official site.
After doing so and several tries, my leonardo finally stopped to be recognized. no ttyACMx appears from that time.
I guessed it's the problem on software environment, so I connected the arduino to Windows7 pc, but device manager also didn't recognize the arduino.
How my leonardo is now
Connecting to PC, "ON" LED have turned on and "L" LED blinks each 1 seconds. I guess it's thanks to default bootloader.
So looks not completely broken or bricked, but still can't access from any PC in normal way.
What I want to be taught
Is my leonardo broken?
Is there a way to make it work?

reply(20151018)
@Chris Stratton
Thank you for suggesting! It's good news for me that it doesn't seem to broken.
I ran lsof | grep ttyACM and found nothing.
And about brltty, Ubuntu has installation of it by default, and sudo service brltty status says its enabled.
So I try sudo service brltty stop and connect my Leonardo, but it still not be recognized. X(

First, never run programs like the Arduiono IDE as root!  It's insecure, and it can make a mess by creating files which a normal user account can't clean up.  Add yourself to the dialout group instead.

The "migrating" USB serial device problem is a behavior of typical Linux configuration (probably udev) - if a device is disconnected (possibly including by simple reset of the target processor) from the USB bus while anything has the device file open, when reconnected it will not be given that same name, but the next one in the sequence of naming rules.  This can be quite annoying when doing embedded development, and I've been thinking about trying to change that behavior for select devices.  In the meantime, you can use lsof | grep ttyACM to see if something still has the old one open.

And make sure to disable brltty if you have that installed - it can improperly grab serial devices, and it could be something like that which is preventing re-use of the serial device names.  It's unlikely your Leonardo is bad - it has to be fairly alive to be given a serial device name.  At an extreme you could try reloading its firmware in DFU mode, but that's probably unecessary.  Can you use a friend's Mac or Windows box to test it?


text:
Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery?
I have an Arduino Uno. It has a 3.3v pin that I would like to use to power another module that requires 3.3v, and nothing more. If I power my Arduino Uno with a 9 volt battery, will this pin output 3.3v, or will it give more than that?

It will output 3.3V. What module do you want to power ? A sensor uses very little current, that won't be a problem.

I am using an IMU sensor and an NRF radio. They both run on 3.3v.

A (fake) nRF24L01+ ? I think they require not a large amount of current (only 10mA or 20mA or so), but I'm not sure. I will probably work.

The 3.3v is regulated and will always output 3.3v if the device is powered on.


text:
Two Leonardos on one USB hub - not working properly
I have two Arduino Leonardos here. They do different things, but basically they both emulate a keyboard. Here is an example:
const byte SWITCH = 12;

void setup ()
  {
  Keyboard.begin();
  pinMode (SWITCH, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  if (digitalRead (SWITCH) == LOW)
    {
    Keyboard.println ("foo");
    delay (2000);
    }
  }

Now I program a second Leonardo with the same code but send "bar" rather than "foo".
Now if I plug these into my PC (running Ubuntu 14.04) using different USB ports, everything works. When the switch is closed I see "foo" and "bar" being typed into whatever application is open.
However ...
If I plug them both into a D-Link 4-port USB hub (model DUB-1340) only the first one works. The other is ignored.
Doing lsusb shows this (along with other irrelevant devices):
$ lsusb
Bus 003 Device 040: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)
Bus 003 Device 039: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

This happens in both cases (if they are both in the USB hub or not).

My question
Is this proper behaviour that two Leonardos on a USB hub fail to both work? (Perhaps you aren't supposed to plug two identical USB devices in at once).
Or, is this a bug in either:

The Leonardo USB interface?
My USB hub?

Update
Further testing revealed that the setup worked OK when plugged into my Mac running OS/X.
Then I went back to Ubuntu and it worked as well! However a mouse that I had plugged into the USB hub now stopped working!
Further investigation reveals that the fourth port on my USB hub is faulty in some way. If I swap the mouse and the Leonardo the Leonardo works but not the mouse.
Following Majenko's suggestion:

You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks.

First one:
T:  Bus=03 Lev=02 Prnt=50 Port=00 Cnt=01 Dev#= 66 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

Second one:
T:  Bus=03 Lev=02 Prnt=50 Port=03 Cnt=04 Dev#= 72 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 0 Cfg#= 0 Atr= MxPwr=
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceNumber: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bAlternateSetting: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bNumEndpoints: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceSubClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceProtocol: No such file or directory
/usr/bin/usb-devices: line 79: printf: (none): invalid number
I:  If#= 0 Alt= 0 #EPs= 0 Cls=() Sub= Prot= Driver=

Tentative conclusion
Perhaps I somehow damaged that USB port by drawing too much current during testing at some earlier point.
Although ... now the mouse is working in the port where it was not working before, and the Leonardo has stopped working in the 3rd port, when it was previously not working in the 4th port.
Those error messages above must be relevant, but I don't know enough about it to say in what way.

What OS are you using? You could try changing the PID on one of them.

I am using Ubuntu 14.04. See updated question.

Are you using the external power for the hub or drawing power from the bus?

I was using external power on Ubuntu, but drawing from the bus on the Mac, as it was fiddly to move the power wire.

There is no reason I can think of that would stop it working as it should.
lsusb is showing both the devices, so they are being detected by the kernel.
You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks. You should get two blocks like this:
T:  Bus=01 Lev=03 Prnt=07 Port=00 Cnt=01 Dev#= 11 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=0036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=USB IO Board
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

The important bit is the I: lines - they show the individual USB interfaces and what kernel driver has been associated with them.   For the keyboard, of course, it's the last entry, which is assigned to the usbhid driver.
Another good diagnostic is dmesg -w
Run that with both Leonardos disconnected.  Plug one in and it should show it registering as a USB device.  A few moments later you should get a pair of lines like:
[ 2106.937086] input: Arduino LLC USB IO Board     as /devices/pci0000:00/0000:00:1a.7/usb1/1-1/1-1.4/1-1.4.1/1-1.4.1:1.2/0003:2341:0036.0006/input/input21
[ 2106.990523] hid-generic 0003:2341:0036.0006: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC USB IO Board    ] on usb-0000:00:1a.7-1.4.1/input2

That is the board being associated with an input device (in this case input 2).
Repeat it with the second Leonardo and see if the same appears, but this time with a higher input number (it would be 3 on mine if I had a second Leonardo).
The fact that the two Leonardos work together normally means that they should be working fine in any arrangement, so if the OS is seeing it all fine but the data isn't getting through, then my money is on the hub.  It looks quite a new hub, so it may have a few bugs in it that are yet to be ironed out.
USB devices are identified to the drivers using the VID and PID, but to the kernel the USB device is just a chain of bus/port numbers.  For instance my Leonardo above is identified as:
1-1.4.1

That's USB bus 1, downstream port 1 (root hub - normally only has 1 port), which connects to a hub (the one built into the computer to drive multiple ports) which then has downstream port 4 connecting to a hub (on my desk) which then has downstream port 1 connecting to the device.  Nothing else can be connected to that same combination of downstream ports - it's physically impossible, so it's uniquely identified.

I've tried what you suggested, see amended question.


text:
Why is the IR transmitter tied to one pin
I'm using IRremote.h  (https://github.com/Arduino-IRremote/Arduino-IRremote).  The receiver allows you to change the pin it is connected to but the transmitter does not.  Is there any reason why this is hardcoded in IRremoteInt.h.  If it just a PWM pin, can't any PWM pin be used?
#if defined(CORE_OC2B_PIN)
#define TIMER_PWM_PIN        CORE_OC2B_PIN  /* Teensy */
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN        9  /* Arduino Mega */
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define TIMER_PWM_PIN        14 /* Sanguino */
#else
#define TIMER_PWM_PIN        3  /* Arduino Duemilanove, Diecimila, LilyPad, etc */
#endif

There is not much documentation on this.

have you tried using another pin?

Where are those pin definitions? Just have found some pin numbers in IRTimer.hpp. Though by default you can use any pin for sending since the timing is done via software. The pin definitions come only to play when you want to use a hardware timer in PWM mode. Then you can provide the corresponding defines to tell the library which Timer to use. Thats important,  since it will directly access the corresponding registers of that Timer

So in short, I need to modify the header and source if I wish to use any pin for sending.  No idea why the author designed the receiver to take any pin but not the sender.  I'll just change it to accept any pin and send the mods to the author.

@cup I would guess the author did it that way because thats the way most Arduino libraries are.  "There is not much documentation on this" adds weight to that assumption.  IMO a lot of libraries are generated because the author needs the functionality and then they are published because the authors are just nice people and are willing to share.  In this case the author probably never thought about using a different pin, the wire was connected to port 9 why would 'he' need it on port 8.

@cup ... There is also the chance that there is a hardware restriction that was in force at the time that meant it could only be on port 9, it was the only port that supported PWM? Maybe now the limitation is no longer there.
But anyway you have the right idea, if you can improve a library do so and feed it back into the repo.

I'll do the changes, test it and then feed it back to the author.  Can someone close this?

Got to the bottom of it.  As mentioned in the comments, this is tied to the timers.  The list is given in Secrets of Arduino PWM.  The code can be changed to use a different timer but it will still be tied to a specific pin.


text:
Relay switch problem: Arduino Nano with a 312 PIR sensor
I am working with a 312 PIR sensor with an Arduino Uno Nano.
When sensing motion Port 13 goes High for Time_A (10 minutes). If I then press a push button on the Arduino board it takes Port D2 LOW, then Port A will be on for Time 2 (A quick 30 second test cycle for testing and/or troubleshooting the code and equipment and a second LED (Port 12 goes high).
So, the sensor turns on the light relay for 10 minutes and the push button makes the light and the LED stay on for only 30 seconds so I can quickly test the system.
I have all the above working perfectly, but I have having difficulty adding another section of code that will turn all of the above off after either the 10 minutes, or the 30 second cycle. Now the lights stay on until I reset and start the cycle over for one of the times determined by the button, or the sensor.
Below is the code :
//Serial.println("TOP OF PROGRAM");
float pressLength_milliSeconds = 0; // value will be recorded in seconds. Define minimum time, in milli-seconds
int optionOne_milliSeconds = 100;
int optionTwo_milliSeconds = 2000;  // the pin your button is attached to
int buttonPin = 2; // pin your LEDs are attached to
int ledPin_Option_1 = 13;
int ledPin_Option_2 = 12;

void setup() {   // initialize pushbutton input pullup. Keep in mind, pin2 has ground voltage applied, we
  Serial.println("Top of SKETCH");
  pinMode(buttonPin, INPUT_PULLUP); // set the LEDS pins as outputs
  pinMode(ledPin_Option_1, OUTPUT);
  pinMode(ledPin_Option_2, OUTPUT); // start serial communications - for debutting   purposes or
  Serial.begin(9600);
} // close set up

void loop() { // record roughly the of tenths of seconds the button is being pressed
  while (digitalRead(buttonPin) == LOW ) {
    delay(5); // if you want more resolution, lower this number
    pressLength_milliSeconds = pressLength_milliSeconds + 100;   //display how long button is has been held
    Serial.print("ms =  ");
    Serial.println("pressLength_milliSeconds");
  } // close while     //Option 2 - Execute the second option if the button is held for the correct amount of time
  if (pressLength_milliSeconds >= optionTwo_milliSeconds) {
    digitalWrite(ledPin_Option_2, HIGH);
  }  // option 1 - Execute the first option if the  button is held long enough
  else if (pressLength_milliSeconds >= optionOne_milliSeconds) {
    digitalWrite(ledPin_Option_1, HIGH);
  } // close if options. every loop - reset  pressLength_Seconds counter
  //if (optionTwo_milliSeconds >= 10000)
  //  delay(10000);
  //digitalWrite(ledPin_Option_1, LOW);
  //digitalWrite(ledPin_Option_2, LOW);
  pressLength_milliSeconds = 0;
}

use button to control the timer, not LED ... use timer to control the LED ... you could separate the control even more by using timer to control a flag, then use the flag to control the LED

So there's two conditions that are supposed to make the light turn on? Within 10 minutes after a sensor signal on pin XX or within 30 seconds after a button press on pin 2?  I'd record the micros() when the button was pressed, and the micros() when the sensor was pressed and do the logic for the LED.


text:
Question about a code
This code is used to toggle an arduino on and off , the problem is that i can't comprehend it at all. can someone explain to me how does it work ?
New = digitalRead(button);
  if ( New!=old)
  {
    if ( New == HIGH ){
      if (LEDstatus == LOW)
    {  digitalWrite(LED,HIGH);
    LEDstatus = HIGH;
    }
    else
    {
      digitalWrite(LED,LOW);
      LEDstatus=LOW;
    }
    }
    old=New;
  }

It doesn't toggle an Arduino on and off. It toggles an Arduino's output pin on and off on button presses.

First, fix the indentation:
New = digitalRead(button);
if ( New!=old) {                        // If the button state has changed
    if ( New == HIGH ) {                // If the button is now in the pressed state
        if (LEDstatus == LOW) {         // If the LED was off
            digitalWrite(LED,HIGH);     // Turn the LED on
            LEDstatus = HIGH;           // Remember the LED state for next time
        } else {                        // The LED was on, so turn it off
            digitalWrite(LED,LOW);
            LEDstatus=LOW;              // Remember the LED state for next time
        }
    }
    old=New;
}

That makes the code a whole lot easier to understand.
It only does something when the button is pressed (switches to HIGH state). It doesn't do anything when you release the button.
Each button press changes the state of the LED.
if it was off, it turns it on. If it was on, it turns it off.


text:
Question about ElapsedMillis() library and state machines
I'm making a sort of state machine with 3 states, and I'm actually doing some tests by configuring at the start of my code state=3. I've wired on each pin 2 leds, for a total of 12 leds. I'm using elapsedMillis library (https://github.com/pfeerick/elapsedMillis)  to make things a bit more easy and I'm stuck at 3rd state. At the 3rd state I would like that each couple of leds will stay on for 90ms, than goes of for 1ms. elapsedMillis library allows one to do something like that:
elapsedMillis timeElapsed; //declare global if you don't want it reset every time loop runs
#include "elapsedMillis.h"

const int pin0 = 12;
const int pin1 = 11;
const int pin2 = 10;
const int pin3 = 9;
const int pin4 = 8;
const int pin5 = 7;

unsigned long t1 = 500;
unsigned long waiting = 1000;
unsigned long t2 = 100;
unsigned long t3 = 50;
unsigned long t4 = 1;
unsigned long t5 = 90;
unsigned long startTime = 0;

int ledArray[] = {pin0, pin1, pin2, pin3, pin4, pin5};
int j, k, a, c = 0;
int state = 3;

elapsedMillis elapsedTime;
elapsedMillis timer1;
elapsedMillis timer2;
elapsedMillis timer3;
elapsedMillis timer4;
elapsedMillis timer5;

void setup() {
  pinMode(pin0, OUTPUT);
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  pinMode(pin4, OUTPUT);
  pinMode(pin5, OUTPUT);
  Serial.begin(9600);

}

void loop() {

  switch (state) {

    case 0:
      // led accesi in modo scalare allo stato 0
      while (k <= 5)
      {

        if (timer1 >= t1)
        {
          if (j <= 5)
          {
            digitalWrite(ledArray[j], HIGH);
            j++;
            timer1 = 0;

          }
          k++;
          elapsedTime = 0;
        }

      }
      // attendo 1s poi vado allo stato 1

      if (elapsedTime >= waiting) {
        state = 1;
        elapsedTime = 0;
      }

      break;

    case 1:

      // led spenti rapidamente in modo scalare

      while (k >= 0) {
        if (timer2 >= t2)
        {
          if (j >= 0)
          {
            digitalWrite(ledArray[j], LOW);
            j--;
            timer2 = 0;
          }
          k--;
          elapsedTime = 0;
        }
      }
      // attendo 0.1s
      if (elapsedTime >= t2) {
        state = 2;

      }
      break;

    case 2:

      // led fade per 3 volte
      if (c <= 3)
      {
        while (a <= 255)
        {
          if (timer3 >= t3) {
            analogWrite(ledArray[3], a);
            timer3 = 0;
            a += 10;

          }

        }
        while (a >= 0)
        {
          if (timer3 >= t3) {
            analogWrite(ledArray[3], a);
            timer3 = 0;
            a -= 10;
          }
        }
        c++;
      }
      else {
        state = 3;
      }

      break;

    case 3:

      if (timer4 >= t5) {
        if (j <= 5) {
          digitalWrite(ledArray[j], HIGH);
          j++;
          timer4 = 0;
          if (timer5 >= t4) {
              digitalWrite(ledArray[j], LOW);
              timer5 = 0;
            }
          }
        }
      break;
  }
}

case 3:

  for (int ii = 0; ii <= 5; ii++)
  {
    digitalWrite(ledArray[ii], ( (ii == j) && (timer4 < 90)));
  }

  if (timer4 > 91) {
    j += backwardScan ? -1 : 1 ;
    if (j > 5) {
      backwardScan = 1;
      j = 5;
    }
    if (j < 0) {
      backwardScan = 0;
      j = 0;
    }
    timer4 = 0;
  }
  break;

For the state3 I would like an effect like the "KITT" knight rider car in 80s TV show. Each couple of 2 leds should move back and forth... in shortly: first 2 leds stays on 90ms and 1ms off, then second 2 leds on 90ms and 1ms off.. etc...
It seems like the leds in the array goes on all together.

And what exactly is the actual problem? Please give a detailed description. Also: How are you seeing if it works? 1ms is too short of a pause to see with the human eye

For the state3 I would like an effect like the "KITT" knight rider car in 80s TV show. Each couple of 2 leds should move back and forth... in shortly: first 2 leds stays on 90ms and 1ms off, then second 2 leds on 90ms and 1ms off.. etc...

And what is the problem with your code? What exactly does it do different than expected? Please don't let us guess

seems like the leds in the array goes on all together

Guessing about case 3-- State variable j is which pair of leds to light, and.....Not sure... No state for back and forth, timing state is the diff between timer4 and timer5?  I'd guess you need another state variable to remember whether you are moving "back" or "forth".  In general with state machine logic, you should be able to identify exactly which state you are in, set the outputs accordingly, and then transition or not to the next state.  For instance, your code should be able to recognize how to set the KITT leds for the "middle pair, scanning forth-wards, on, 33ms to go" state.

Yes in state 3, variable j is to keep track of which pair of leds are you in, but my actual problem is how to have a led on for 90ms and 1ms off by using the timer4 and timer5 if needed. I have t4 that is variable for 90ms led ON and t5 that is led off for 1ms

... You could handle the on & Xms to go state with the state of a timer, with for(int ii=0,ii<=5,ii++){digitalWrite(edArray[ii],( (ii==j) && (timer4 <90) }} and then whenever if(timer4>91), update  backwards, jandtimer4` to the appropriate next state.

mmmh sorry I can't read this well...

You need to maintain more state information to have 'case 3' work like a KITT-style back and forth LED scanner. I think you can do it with three state variables, j for which pair of LEDs is active, backwardsScan to say which way to go, and timer4 to remember where in the 91ms cycle we are with the active pair of LEDs.
Try something like this:
...
int backwardsScan = 0;
...

case 3: // KITT-like scanning back and forth 90us/1us
  // j remembers which LED pair is active
  // backwardsScan remembers which direction to scan
  // timer4 handles the 90ms/1ms on-off cycle.
  //
  // reset output leds appropriately for (j,timer4):
  for(int ii=0;ii<=5;ii++){
    digitalWrite(ledArray[ii],( (ii==j) && (timer4 <90)));
  }
  // update KITT state based on (j,backwardsScan,timer4)
  if(timer4 > 91){
     j += backwardsScan? -1 : 1 ;
     if (j > 5){
        backwardsScan = 1;
        j = 5;
        }
     if (j < 0) {
        backwardsScan = 0;
        j = 0;
        }
     timer4 = 0;
     }

  break;

The main trick with state machines is being able to fully determine the complete state from what you are keeping track of--It should be memoryless, in that the state variable(s) fully specify the state, and you don't need to remember the prior state.  If you find you need to know more than one thing, you might need a vector or set of state variables.  One could map the whole led-backwardsScan-timer4 state vector into a single state variable (timer4, modulo 182ms for example,) but that would be unnecessarily complicated. Recognizing all the variables required to fully specify the state is important.

I noticed you write: "backwardsScan?" and the digitalWrite is not clear for me...

The  ( backwardsScan ? -1 : 1 ) is the ternary operator https://en.wikipedia.org/wiki/%3F:  If  backwardsScan is true, it delivers the first value, -1  or if false, it delivers the second value +1.

I had to change this: for(int ii=0,ii<=5,ii++) with ";" not ,

The logic in the digitalWrite only writes HIGH to the active LED in the sub 90ms timer4  time, and LOW to all the other LEDs and to the active LED after 90ms.

I have lot of errors, trying now to fix the code...


text:
How do I change the Console colour of Arduino IDE?
Leading on from the question Can I change font Color and/or Type for IDE 1.5.6r2?, in 1.6.0, or 1.6.11 it does not seem to be possible to change console.color or console.error.color. To be precise, you can change the settings in the preferences.txt2 file, but they appear to be ignored when the IDE is restarted. Have these become hard coded?  I see from the preference.txt example file that
# Some colors have been hardcoded into the source in app/ in order to ensure
# consistency with the images distributed and stored with the application.
# They have been commented out below so that users who install an old
# version of the software will not get incorrect colors left-over from this
# config file.

However, the settings to which I refer are not commented out, and so would led me to believe that they can be changed. Orange text on black is just horrific to read.
For example:
console.error.color=#FFF000
console.color=#FFCCCC

but I still get white/orange(red?) text for the output and error messages respectively.
I am making the edits while the Arduino IDE is not running.

1 In 1.6.3 the ignored console.color etc. lines appear to have been removed from the preferences.txt file.
2 C:\Users\username\AppData\Roaming\Arduino15\preferences.txt

It turns out that the theme.txt configuration file is not located alongside the preferences.txt file, but alongside/under the Arduino application's .jar files. Thus, for the current version (1.6.3):

on OS X, .../Arduino-1.6.3.app/Contents/Java/lib/theme/theme.txt
on Win7, C:\Program Files\Arduino\lib\theme\theme.txt
on Linux, .../arduino-1.6.3/lib/theme/theme.txt
on Windows 10, when installed as an App, C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\lib\theme\theme.txt, however it does not seem possible to edit it - it can be opened in notepad++ but a save fails.

See an associated Github issue, IDE Background and print color options needed, for a little more discussion.

Thanks for that. BTW, the Windows path is C:\Program Files\Arduino\lib\theme\theme.txt.  It does beg the question why are the console.error and console.color lines in the preferences.txt file if they are ignored. The Arduino IDE truly is a shockingly terrible piece of software. However, having said that, I notice that in version 1.6.3 the lines appear to have been removed.

If you've put those lines in preferences.txt (as I did), then they'll still be there after the IDE has read and re-dumped the properties, even though the IDE ignores them. Myself, I don't much like the IDE editor, so I use an external editor (setting the appropriate preference), and just use the IDE to compile and upload – for that, for me, it works well enough. Anyone out there who can add the path to the theme file under Linux?

I've added the Windows and Linux paths to your answer. Hope you don't mind.

@Greenonline Looks great!

Download the Dark Theme of Jeff Thompson from Github: jeffThompson/DarkArduinoTheme

Screenshot:


text:
Metal detector using Arduino
Is anyone out there building serious metal detectors with the Arduino? By "serious" I mean metal detectors with phase sensitivity to discriminate between ferrous and non-ferrous metals, etc.  Seems like the Uno is a good platform for a smart metal detector project.
Update:
Arduino allows me to control phase discrimination which allows ferrous metals to be rejected.
I already know it can be done with an analog phase shift circuit.
Also Arduino can perform target ID function with readout to 16x2 LCD display.

Should be possible with only analog logic. I don't see where you'd need an arduino. Just google some schematics for metal detectors.

A set of posts on Instructables uses an Arduino Nano to generate a Phase Induction pulse, with a capacitor instead of a dump resistor to set up a decaying oscillation, which is then limited with diodes and detected by the analog comparator with interrupts.  The comparator interrupts then count the frequency of the decaying ringing oscillation producing some ferrous/non-ferrous discrimination, and the duration of the ringing, producing some signal strength and size information.

Nano doing Pulse induction with LC-trap oscillation: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector-LC-Trap/
Nano meta detection software with high-frequency ADC sampling: https://www.instructables.com/id/How-to-Program-an-Arduino-Based-Metal-Detector/
Nano doing Pulse Induction, shifting the recovery pulse to match the arduino's analog comparator: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector/

The tricks in the Pulse Induction LC-trap system of using the analog comparator would be applicable to detecting phase shifts and detecting crossings in sync with a timer-based output.


text:
Traffic lights: gpios against 5V or ground
I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.
What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?
Moreover: how many ohms should the resistor have?
My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V.
So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?
Well, a lot of thoughts for 3 simple lights...
Thanks for any help.

different colors have different forward voltages, thus different resistor needs given the same source voltage.

I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

BAD BAD BAD!!!

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Nothing, other than the reversed logic. AVR GPIOs (and most GPIOs in modern MCUs) are balanced - i.e., they have the same current limit for both sink and source.

Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Yes. That is how you should wire LEDs - and you have already identified why.
For each LED calculate the resistance as R=(5-Vf)/0.02. You need to find the correct Vf for each LED from the datasheet to get the best results - but if you can't then a rule of thumb is: Red, Green and Yellow are about 2V, Blue and White are about 3V.


text:
4 digit 7-segment display
What happends if I turn on all LEDs at the same time in an 4 digit 7 segment display? that would be 32 LEDs turned on at once, wouldn't that exceed the 200ma MAX for the arduino output?

Which 7-segment display? Different displays need different currents. The answer is in the datasheet for the display. Which Arduino? Different Arduinos can supply different amounts of current.

Arduino uno. the 7 segment display is YY3641AH which I can't find a datasheet for.

And since there is no GND connected to the display, are all 8 segments of a digit connected trough one I/O pin as ground? Doesen't that exceed the pin's 20mA recommended level?

The key point is that if you do that, you're doing it wrong.
Typically a multi digit display is time multiplexed, such that you use a common set of segment lines to activate the pattern on each digit in turn, therefore at any one time only at most 7 (or 8 counting the decimal point) segments should actually be on.
Then in terms of the common connection which selects a given digit, this will indeed typically have to source or sink more current than an MCU I/O pin is typically rated to handle, so it's best if the common connection is driven by an external transistor or FET.
Other options of course include mutli-digit LED display drivers, or lower power display technologies like LCDs.
That said, if a software bug briefly means everything is on, chances are the chip will survive.  But hopefully this only happens to "engineering units" - you do want to make sure that production units don't suffer this at some point in the programming process or something like that (though that's not all that likely, as typically all I/Os become inputs with at most a weak pullup).

These typically use 12 GPIO pins (4 for the digits, 8 for the segments/dot).
Each GPIO pin controls one digit and/or segment at a time.
The normal 'maximum' LED current is 20 mA. For the digits, 8 segments * 20 mA = 160 mA which is below 200 mA.
However, maybe there are LED displayed which use more current. In that case, you have yourself to make sure not all segments are lit at the same time (by fastly alternating the LEDs, or using less current).

but aren't all 7 (8 with dot) segments connected to one I/O pin which is used as ground? Doesen't that exceed the 20mA recommended for one pin?

True ... I'm updating my answer

Thats what I'm worried about. Exceeding the individual 20mA amount for each of the 4 I/O pins used as ground, and exceeding the 200mA max for all pins

when I light up 4 leds they seem to pull 40mA. What about all the 32 then?

Each digit has their own ground, so max 8 LEDs for the digit/ground GPIOs.

but 1 led still uses 10mA, times 8  thats too much

10 mA * 8 = 80 mA, which is less than 200 mA (?)

but all that goes trough one I/O pin which is used as GND for the digit. Thats double the max rating for the pin.

The max pin current is 200 mA right? And one LED is max 20 mA ... 20 mA * 8 LEDs = 160 mA. Each digit has its own ground GPIO.

well, for me each LED uses 10mA, so if I set one digit to show a "8." thats 8x10mA= 80mA that go trough one GND I/O pin.

You are right ... the max for a GPIO pin is 50 mA which is too high. As dannyf explains there is also some internal resistance.
You also can use multiplexing to not lit all LEDs at once.

They will turn on, likely with slightly uneven brightness - the LEDs internal resistance and the pins limited current drive will act like the current limiter.
The actual current will depend on the supply voltage, led used and the mcus drive capabilities.
For a red 4 digit 7 seg on an atmeha8, I got less than 10ma at 2,5v and 20ma at 3.3v, with the LEDs multiplexed.
Edit: some quick math.
Say that the current through each led segment is I. And the gpio resistance is R.
Each common digit has 8 I current through it, and each segment has 4 I. Some math later,
I = (Vcc - Vf) / (12 R) where Vcc is the supply voltage and Vf is the LEDs forward voltage (1.9v for a typical red led). The gpio resistance varies from 50+ ohm to 30+ ohm, higher at lower voltage.
Plus in 3.3v and 2.7v you get total current of 30 to 75ma for all digits.
I'm going to measure mine later.
edit: about 25ma (total current = mcu + led) at 2.5v and 50ma at 3.3v. the mcu consumes 2-3ma approximately.
the brightness is fairly even amongst the leds if you don't look too closely.


text:
Is it possible to obtain %0.05 duty cycle at 1hz in arduino?(a 500us square pulse at 1 sec period)
I have a system which requires me to obtain different duty cycles at different frequencies. But using the analogWrite() does not allow me to obtain a value lower than 1/255 duty cycle. I need to obtain lower duty cycle values for 1Hz

Is it OK if, at 1 Hz, you are restricted to pulse widths which are multiples of 16 µs? E.g. you would have 496 µs instead of 500. If so, you can configure Timer 1 to generate the PWM signal on pins 9 or 10. A signal generated this way would have more consistent timing than a similar signal generated by software (e.g. using micros()).

@EdgarBonet - could you explain where are you getting the 16us from?  Several prescalar and count value possibilities will yield 500us, but I'm not immediately thinking of any that yield your numbers.

Prescaler = 256 → resolution = 16 us and maximum period = 1.048576 s.

Ok, the maximum interval is a point - but that doesn't have to come from the same timer.

Expanding from my comment. This is an attempt to generate that signal with Timer 1. No time to test it now... Edit: tested, works as advertised.
/*
 * Configure Timer 1 to generate a slow, low duty cycle PWM signal.
 * Output pin = digital 9 = PB1 = OC1A.
 */

const float PWM_PERIOD  = 1.0;     // 1 s
const float PULSE_WIDTH = 500e-6;  // 500 us

/*
 * With a 16 MHz clock and this prescaler, the resolution is 16 us and
 * the maximum period is 1.048576 s.
 */
const uint16_t TIMER_PRESCALER = 256;
const float F_TIMER = F_CPU / TIMER_PRESCALER;

void setup()
{
    // Configure Timer 1.
    DDRB  |= _BV(PB1);    // set PB1 = OC1A as output
    ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
    OCR1A  = round(PULSE_WIDTH * F_TIMER) - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}

void loop() {}

Thank you for this, It works great but I would like to get the same thing for 2 different pins and I have no idea about registers. Can you tell me how can I make this code applicable for pin 10 and pin 8?

@allta: You can't. Hardware-based PWM only works on pins OCnA and OCnB, where n = 0, 1, or 2 is the index of the timer you use. The small duty cycle you want can only be achieved with a 16-bit timer, and you have only one such timer on the Uno: Timer 1. Thus you can only use pins 9 (OC1A) and 10 (OC1B). C.f. the Arduino Uno pinout. See also the tutorial Timers and counters by Nick Gammon.

Thank you again
It's ok we can use the pin10 we won't use the pin 9 and 10 simultaneously. Will changing OC1A with OC1B would work for pin 10? How can I modify this code for pin 10?

@allta: Yes. OCR1B controls pin 10 in the same way as OCR1A controls pin 9.

void setup()
{
// Configure Timer 1.
DDRB  |= _BV(PB2);    // set PB1 = OC1A as output
ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
OCR1B  = round(PULSE_WIDTH * F_TIMER) - 1;
TCCR1A = _BV(COM1B1)  // non-inverting PWM on OC1B
| _BV(WGM11);  // fast PWM mode, TOP = ICR1
TCCR1B = _BV(WGM12)   // ditto
| _BV(WGM13)   // ditto
| _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}
didn't work I don't get how can I modify the last part correctly

@allta: Your modified setup() works for me: I get the PWM signal on pin 10.

Now it worked for me too, thank you again

Sure - if you program it to.

Turn on an output.
Wait for 500µs less the amount of time it took to turn on the output
Turn off the output
Wait for 0.9995 seconds minus the amount of time it took to turn off the output
Go to 1.

You would probably find using the micros() function easiest to get the timing right - in exactly the same way as the BlinkWithoutDelay example in the IDE.
Also direct port manipulation may be of benefit to make things as fast as possible.

Yes, hence my instruction to use micros.

Sure. Two easy way to do it.

0,05 percent is 1:2000. So modify timer settings to produce a pen of the desired frequency and duty cycle.
Use timer interrupt: either the overflow or compare match interrupt. In the first case, load the timer with -duty cycle and -(period - duty) to produce a wave form of duty cycle / period.

The same can be done using compare match as well: just advance the match point alternately.
edit: to show how it can be done with compare match, here is what I have:
#define PR_PWM          (F_CPU / 256 / 10)      //period for the pwm waveform
#define PR_ON           (PR_PWM * 25 / 100)         //prescaler at 256:1, 25% duty cycle
#define PR_OFF          (PR_PWM - PR_ON)            //pin off period, to achieve 1Hz
//end hardware configuration

//global defines

//global variables

//timer1 ch a compare match isr
ISR(TIMER1_COMPA_vect) {
    static char pr_index=0;     //0->PR_ON, 1->PR_OFF

    //clear the flag  -  done automatically
    //advance to the next match point
    if ((pr_index++ & 0x01) == 0) {
        OCR1A += PR_ON;
        IO_SET(PWM_PORT, PWM);  //set the pin on
    } else {
        OCR1A += PR_OFF;
        IO_CLR(PWM_PORT, PWM);  //clear the pin
    }

}

for this demo, we tried to generate a 25% duty cycle pwm with a period of 100ms. Here is the output of that code.

The follow changes the duty cycle to 0.05%:
#define PR_ON           (PR_PWM * 0.05 / 100)           //prescaler at 256:1, 0.05% duty cycle

and the corresponding output is:

Now, there are other ways to do it, for example, with higher resolution, or more precision, ..., but at the cost of more coding.
But the basic concept is the same.
hope it helps.
edit2: for those brave souls, the isr can be simplified to:
OCR1A += (pr_index++&0x01)?PR_OFF:PR_ON;  //advance the match point
IO_FLP(PWM_PORT, PWM);  //flip the pwm pin

@LookAlterno Unless he means to draw the waveform on a piece of paper...?!


text:
Deceleration time logger between frequencies
i need to measure the air resistance and roll resistance of a vehicle. I plan on using a toothed disc with a proximity sensor which will output a square wave signal in to an arduino. Then I will drive until I reach a certain speed, after which I will disconnect the drive from the wheels and let the vehicle roll until it has reached another certain speed (2 or 3 kph lower than the speed at which I started). By measuring the time it takes to decelerate I can calculate the air and rolling resistance.
I want to use an arduino as the brain box. Once the frequency of the sensor signal drops below a given value the arduino should start measuring time. Once the frequency drops below a second given value the arduino should stop measuring. For example between 25Hz and 20Hz. I would like to change the Frequency (that corresponds to a speed) so i can test at different speeds. I would then want to log the time it took to my pc on the serial monitor. I plan on using an Arduino Mega 2560.
My knowledge of coding in C is very limited so I'm a bit stuck on how I would write such a program. Anybody got any ideas on how to program something by using interrupts? The vehicle on which I want to do this is an Urban Concept car for the Shell Eco-marathon efficiency race.


text:
Arduino UNO reset using SIM800L
I'm using the SIM800L module but i've problems. I'm triying to connect it to the Elegoo UNO i've, but it restarts at all times. Also the led of signal strengh blink every second, so i dont get signal.

I also upload a video to Youtube to explain the problem, this is the link.
Thanks in advance!

do not connect Reset RST

reset pin of a device should be connected to a gpio pin, to be able to reset the device from sketch

@Juraj Doesnt work, now the module seems to restart, the indicator led start blinking and after that get paused for a few secons and start again, idk what to do :(

you did not connect it or you connected it to some io pin? the library you use, should have a parameter with the reset pin number and taking care of setting that pin

@Juraj i didnt connected, you said that i need to connect it to a io pin and define it on the code?

When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.
You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.
The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.
If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.
If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.
The usual required state for reset is LOW so the output must be HIGH for the device to work.
Some tutorials and libraries require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.

Besides the RST pin situation that the others pointed out, you're not going to do much with the way you're powering the module. It might turn on, but you will never be able to register on the network.
You have to power the module with an external power source and common the ground.
Also, if the module you're using is the one on the image, you might need a logic level shifter to use the Tx-Rx connection.


text:
How can I tell which fuses are set on an ATtiny?
Following on from this question, Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature,
if the response from avrdude is 0x000000 then the internal oscillator is probably not being used and an external one (be that crystal or clock signal) is required.
However, as this menu, from Engbedded Atmel AVR® Fuse Calculator, shows, there are a lot of options:

So, instead of having to configure circuits for each of the options, in turn, until the ATtiny responds, is there any way that I can read which of the CKSEL and SUT fuses are set?1

Background
I am using a Nano/Uno as an ISP programmer, and the ATtiny is on a dev board like this (although it would be the same issue if I were to use a breadboard):

I know for sure that the connections are fine as I have checked them from pin to pin of the two ICs (ATmega328PU to ATtiny85), using a DMM.
I am receiving 0x000000 as in:
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

because the ISP programmer can't read the ATtiny, because an external clock source has been set via the fuses. However, I wish to know how to read which clock source has been specified, without having to manually try all of the circuit permutations.
I don't think that just connecting a crystal (and two ceramic capacitors) will work if the exact setting, i.e. external clock, has been selected. However, if a 16MHz crystal works for all, or any, of the external clock settings then that would be great, but I'm sure it doesn't work like that, as you can have a crystal attached but the it might not be used, see Does device signature 0x000000 mean the atmega is bad:

Even though you have a crystal connected, that does not mean it is oscillating. For example, IF you set fuses for "External Oscillator", that will turn the crystal oscillator off.

When I move the ATtiny85 to a breadboard and add a crystal (16 MHz) and two 22 pF capacitors, the error has changed for the better (at least now it sees that a ATtiny is connected)
avrdude: Device signature = 0xff0000
avrdude: Expected signature for ATtiny85 is 1E 93 0B
         Double check chip, or use -F to override this check.

Interestingly the signature varies:

0xff0000
0x00ffff
0xff00ff

When I add an external power supply to the ATtiny on the breadboard, following advice from Atmega (any chip) Device Signature issues and stk500_getsync()(resolutions), then unfortunately the device signature in the response returned by avrdude reverts back to 0x000000
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

1 This is, admittedly, a bit chicken-and-egg, as if I can't communicate with the ATtiny, due to the incorrect clock setting, then how can I read which fuses have been set..?
It's a bit like saying "If I don't have petrol in my car, then how can I drive to the petrol station to fill up?" - but I was hoping that there might be some sort of time saving measure

How are you powering the Attiny during programming? Extra capacitor on VCC-GND? https://forum.arduino.cc/index.php/topic,51819.0.html?utm_source=rb-community&utm_medium=forum&utm_campaign=device-signature-0x000000-while-burning-bootloader

The USB port on that board is only used for power! You can't program the ATTiny over that USB port.

@Gerben - I am using the ICSP pins and a Nano as the ISP programmer. Once you get the micronuleus bootloader installed then you can use the USB port to program it... see Breathing life into the DigiSpark clone with ATtiny MCU

@MikaelPatel - No I didn't have one of those... interesting... I added a 20 uF, but still the same random signature errors... I notice that in the link, an external supply is recommended, in addition to the extra cap. However, when I added the regulator and additional cap, then situation regressed and the device signature reverted back to 0x000000, unfortunately.

It could be that the ISP-disable fuse is set. I've had some ATTiny13s from China that had their fuses preprogrammed, which made them unusable. I build a simple High Voltage Programmer, to reset the fuses. I think I used this code and schematic https://github.com/tsaarni/avr-high-voltage-serial-programming. Pretty simple circuit. Only two resistors and a transistor. For the 12V source I just stacked 4 CR2032 coincells on top of each other, holding two jumper wires at both end with one hand. Very hacky, but it worked.

This seems to be an X -> Y problem, with X being the missing clock source on your ATTiny, which prevents communication.
If you have a second Uno or other AVR device, you can use that to generate a clock signal on any of the digital pins:
void setup() {
  DDRB = 0b00100000;
}

void loop() {
  PINB = 0b00100000;
}

This creates a square(~ish) signal on Pin 13 with a frequency of 1.6 MHz.
Depending on the IDEs optimization level (platform.txt), a frequency of 4 MHz is also achievable (at -O3 instead of -Os).
Connecting this to the XTAL1 pin of your ATTiny85 should allow you to communicate with the board.
Make sure to interconnect all grounds.

You need a Programmer that connects to the ISP pins
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
The programmer will hold Reset low, then communicate via the SCK/MOSI/MISO pins to read/update the fuses, read/program memory, and optionally read/program the EEPROM.
Section 20.2 discusses the 3 fuse bytes.
I use an older Atmel AVR-ISP MKii. Atmel stopped making them, there seem to be plenty of replacement choices available, and Atmel Studio 7 when I struggle with Atmega328P, '1284P, and 2560. I haven't used an Attiny in a project yet.
https://www.microchip.com/mplab/avr-support/atmel-studio-7

I obviously wasn't clear in my question. I am using a Nano/Uno as an ISP programmer. I am receiving 0x000000 as in  avrdude: Device signature = 0x000000 because the ISP programmer can't read the ATtiny, because an external clock source has been set via the fuses. However, I wish to know how to read which clock source has been specified, without having to manually try all of the circuit permutations. This is, admittedly, a bit chicken-and-egg, as if I can't communicate with the ATtiny, due to the incorrect clock setting, then how can I read which fuses have been set..?

I think you just need to supply a clock, easy way is to connect a crystal and two 22pF caps.  Read here, Nick Gammon goes thru a lot of the fuse settings stuff.  https://www.gammon.com.au/forum/?id=11643

I was thinking that it might not work if the exact setting hasn't been selected, if a 16MHz XTAL works for all or any of the external clock settings then that would be great, but I'm sure it doesn't work like that, as you can have a XTAL attached but the it might not be used, see Does device signature 0x000000 mean the atmega is bad:  Even though you have a crystal connected, that does not mean it is oscillating. For example, IF you set fuses for "External Oscillator", that will turn the crystal oscillator off.

The best way to know for sure is to use a High Voltage (12V) Programmer to reset everything.  https://gammon.com.au/forum/?id=12898

This High voltage serial resetting looks promising, but the page isn't particularly clear on how you reset the particular fuses, or to what value. I guess more reading is required. Just applying the 12V momentarily doesn't reset the fuses per se, it just puts it in serial programming mode. I'll need to read around it more.

Sure, see section 20.7 of the data sheet and Table 20.16.  If I recall, you have to do a Chip Erase before you can Reset the fuses.


text:
How to read OC0A when in CTC (toggle) mode?
I have this code, which puts the Arduino into CTC mode with interrupts, and outputs a square wave on PD6 (OC0A):
void setup_timer(double p_ms, double duty){
  DDRD |= (1 << 6);  // set pin 3 as output
  TCCR0A = _BV(COM0A0); // toggle OC0A on Compare Match
  TCCR0B = _BV(WGM01); // set CTC mode WGM0[2,1,0] = 0b010
  TIMSK0 |= _BV(OCIE0A); // Enable CTC interrupt
  OCR0A = 128;  // set on and off time
  TCCR0B |= ( (0 << CS02) | (0 << CS01) | ( 1 << CS00)); // CS02:0 - No prescaling
  sei();
}

In the ISR (which is not shown) I want to be able to see whether OC0A (i.e. PD6) is HIGH or LOW.
I assumed that I could do a digitalRead(), but this post, Re: How to read the state of an output pin ? says:

Looking at the code the digitalRead() function just does a read of the appropriate bit in the appropriate PINx register without modifying anything, so it should work.
One catch, if it's a PWM pin the PWM will be stopped.

So, will the toggling of OCR0A be stopped?
This answer to How can I digitalRead a pin that is in pinMode OUTPUT? suggests reading PORTD directly, with
bitRead(PORTD,6);

However, will that work for PWM output or will PWM also be stopped by reading PORTD?

Addendum
I plan to use this code either as (primarily) a stand alone AVR µController (48/88/168/328 IC), but maybe in a Nano/Uno (if it will work) for testing purposes. I understand that using Timer0 will affect the operation of millis(), delay() etc., but the rest of the code will not rely on any of those functions... so I presume (maybe incorrectly) that the code will work as expected. Is that correct?
In addition, I don't intend on using a setup() & loop() program structure but rather main(). Just out of interest, would loop() work (i.e. is it reliant on Timer0)? I don't believe that it is.

What Arduino board?

If you look into the Arduino Core, you'll find this code for the digital read:
int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

That means, disabling PWM is just weird feature in digitalRead.
For reading bitRead(PORTB,3); I'm not so sure if you'll get output value of OC0A, it might be different signal line internally. However you'll get logical level on the port pin by reading bitRead(PINB,3);.

Preliminary note: If you are using any of the ATmega48/88/168/328,
then the OC0A pin is PD6, not PB3.
As four your idea of reading the PORT register (PORTD, not PORTB),
it won't work either, as that will only tell you what was the last value
that was written to the port with digitalWrite(). Here is a schematic
showing how the timer controls the output pin. It's taken from the
ATmega328P datasheet, but the other AVRs of that family behave
identically in this respect:

As shown in the schematic, the value written to the port comes from a
multiplexer and is controlled either:

by the PORT flip-flop when the timer is not generating a PWM output
or the OC0A flip-flop when it is.

Quite importantly, the timer does not write to the PORT register, it
only overrides it.
Thus, it would look like you want to read the OC0A flip-flop in your
ISR. Alas, this schematic also shows that, contrary to the PORT
flip-flop, the OC0A flip-flop is not connected to the data bus. Thus
you cannot read it, and it doesn't even have an address.
What I would recommend is to read the PIN register instead. This won't
tell you what the timer is writing to the port, but what you can read
back. However, unless the pin is loaded well beyond its absolute maximum
rating, what you read back what has been written. There is a small delay
between the write operation and the value been available to read back (a
couple of CPU cycles IIRC), but this is way shorter than the execution
time of an ISR prologue.

Thanks for pointing out that I had the incorrect port. I mixed up datasheets, and it is the ATmega16 that uses PB3 = OC0 (page 56 of the ATmega16 datasheet)

Just to clarify: I need to use bitRead(PIND,6);?

@Greenonline: Either that or PIND & _BV(PD6). I tend to favor the later: avr-libc style when doing direct port access, and Arduino style when programming the Arduino way. But in the end it's just a matter of style.


text:
error: expected primary-expression before ',' token
I'm gettng an error "error: expected primary-expression before ',' token" in the following line of code - I have initialized an array with 220 ints. What am I doing wrong here?
const PROGMEM int P7Val[] = {1635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,12601635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,1260,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180,,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180};

#include using namespace std; class sample { int x; public: int get_val(int a); void show_val(); }; int sample::get_val(int a) { x=a; } void sample::show_val() { cout<<" "<<x; } int main() { sample obj[3]; for(int i=10;i<13;i++) { obj[i].get_val(int a); } for(int i=10;i<13;i++) { obj[i].show_val(); } return 0; }

Two things:

You have a comma missing: 1260,12601635,1635,
You have an extra comma: 1180,1180,,1255,1255

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.


text:
How to calibrate the MQ7 sensor module?
I recently bought a MQ7 sensor module like the one in the attached picture. I have read several tutorials, and they're all different. Some of them says that i need to connect the module directly to 5v and wait 24 hours to made it work properly, others says that i need to program different periods (5v and 1.4v) and wait the same time to make correct meditions. I read this Datasheet, but i think that the information it has is not for the module.
If anyone knows how to setup this module i will aprecciate an answer (i want to read analog values).
Thanks in advance and sorry for my bad english.

first of all, you need to understand how these sensors work.

the sensor itself is just a resistor (like a normal resistor, with 2 legs) which is constructed from materials that are affected in presence of a specific gas. the gas changes its resistance. but as it's obvious, these type of materials are not calibrated.
in order to make that resistor sensitive enough, we have to warm it. so the manufacturer puts a simple coil element near the resistor in the capsule and you connect it to 5v. it warms up (it draws a lot of current) and thus, the effect of gas on the resistor becomes greater and we can measure it easily. when they say connect and let it be for 24 hours they mean warming up the resistor. I think it's a little high. I used them after a few minutes of warming up but it depends on situation and desired precision.
the resistor and element, have separate pins and are completely independent. you have to connect the coil to 5v (because manufacturer made it like that) and use the resistor anyway you like. even with a ohmmeter.
as we have to use Arduino, so we have to measure a resistor with the ADC of Arduino. the procedure is straightforward. you put a normal resistor in series with the sensor resistor and make a voltage divider (search that if you don't know about it. it's a fundamental thing to know in electronics).I think there should be a schematic in datasheet for it. and you measure the voltage with ADC.

and some notes :

you have to use A0 pin of the module if you want reading the value like the procedure above. this pin is the output of voltage divider(the sensor + blue pot on the board) and should be connected to ADC.
the D0 is just the output of another circuit present on board for another purpose. it's a comparator output. it's used for situations where you only need to do something (like turning emergency lights on and off) when the gas goes up from a level. you don't read anything with ADC. you just turn the pot to set a threshold (that's empirical) and digital pin get high and low according to that.
the voltage divider's GND and VCC are connected to GND and VCC of heating element accordingly. so you have just one pair of GND/VCC

So basically i just need to connect it to the respectives pins and wait to let the module heat. No different periods (5v and 1.4v) nedeed in the code, right?


text:
In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor?
I would like to know if there are always the latest features in Arduino Desktop IDE if I update it every day.
I mean if there is a new feature in Arduino Web Editor, can I get it on Arduino Desktop IDE?

A new GUI feature, or a new feature of the language / API?

Is it possible to know for both?

How are you updating it? The Arduino IDE beta build is actually a little more closely aligned with the Arduino Web Editor because they both use arduino-preprocessor. The hourly build of the IDE does not currently use arduino-preprocessor (this will change as soon as some serious bugs in arduino-preprocessor are resolved). Arduino Web Editor users are actually unknowing beta testers for the unfinished arduino-preprocessor.

You will always get the same API features in both, because the API is separate to both of them - it's a plugin that's developed separately.
Would you get the same GUI facilities? No idea. Maybe - maybe not. It depends how useful they would be. You may get features added to the GUI that don't appear on the web. Or you may get the other way around. If they are essential to the operation of the system, though, you will get them added to both.


text:
What is the difference between Arduino board and Genuino Board?
I've got an Arduino UNO REV3 SMD EDITION.
In the Arduino Editor, I've selected Arduino/Genuino Uno.
In a tutorial, I saw Hardware required : Arduino or Genuino Board
What is the difference between Arduino board and Genuino Board?

The name Genuino grew out of the split between Massimo and Gianluca (aided in part by Microsoft of course, and a trademark wrangle that went wrong). Each side wanted to appear to be more "genuine" than the other. That lead to the "Genuino" name (a genuine Arduino), and a version number war with the IDE.
Both sides started making their own variants of boards, with some only available from the USA (Arduino) and others only outside the USA (Genuino).
Since they have patched up their differences now the two boards are one and the same. A Genuino Uno and an Arduino Uno are the exact same board. They always have been, there has just been arguments over the name.

At this moment I think people use term "Genuino" to describe the "original board" from official website, and "Arduino" as "any compatible board" including the 2$ Chinese clones.

Not so. I see Arduino as the originally made boards, and clone as anything else. Arduino's use Atmega16U2 (Uno & Mega) or FT232 (Nano) for USB/Serial, while $2 clones use CH340g for that purpose. I use FT232 or FT232 modules in my designs as the US distributors do not carry CH340g chips, and I won't design in parts I cannot source from reputable suppliers.


text:
Arduino IDE / Specified folder/zip file does not contain a valid library
I trying to add library here but it doesn't seem to work https://github.com/esp8266/Arduino
This happens
"Specified folder/zip file does not contain a valid library"
This problem make me no longer upload any library. any solution about this??
Manual installation does not either.

You don't install that repository as a Arduino library.
Read the README file in that repo. It explains how to install it using the Arduino IDE Board manager. That's the correct way to install it.