text:
Multi-LED Toggle Switch
I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB.  The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch.  I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever.  It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it.  If anyone can tell me what I am doing wrong please let me know.
Here is the Python3 GUI code:
import serial # import the serial library
import time # import the time library
from tkinter import * #import Tkinter GUI library

def toggleRed():
    if redBtn.config('relief')[-1] == 'sunken':
        redBtn.config(relief="raised")
        arduino.write('a'.encode())
    else:
        redBtn.config(relief="sunken")
        arduino.write('b'.encode())

def toggleGreen():
    if greenBtn.config('relief')[-1] == 'sunken':
        greenBtn.config(relief="raised")
        arduino.write('c'.encode())
    else:
        greenBtn.config(relief="sunken")
        arduino.write('d'.encode())

def toggleBlue():
    if blueBtn.config('relief')[-1] == 'sunken':
        blueBtn.config(relief="raised")
        arduino.write('e'.encode())
    else:
        blueBtn.config(relief="sunken")
        arduino.write('f'.encode())

def toggleYellow():
    if yellowBtn.config('relief')[-1] == 'sunken':
        yellowBtn.config(relief="raised")
        arduino.write('g'.encode())
    else:
        yellowBtn.config(relief="sunken")
        arduino.write('h'.encode())

print ('Connecting...')
arduino = serial.Serial("/dev/ttyACM0", 9600)
time.sleep(3)
print ('Connection established successfully')

appWindow = Tk() # creates the application window (you can use any name)
appWindow.wm_title("RGB LED Control") # displays title at the top left
appWindow.config(bg ="#037481")

mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
mainFrame.grid() #grid the frame into the App Window

btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
btnFrame.grid() #grid the frame into the main frame

redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
redBtn.grid(column=0,row=0,sticky='EW')

greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
greenBtn.grid(column=0,row=1,sticky='EW')

blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
blueBtn.grid(column=0,row=2,sticky='EW')

yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
yellowBtn.grid(column=0,row=3,sticky='EW')

appWindow.mainloop()# begins main loop

Here is the arduino code:
int ledRed = 13;
int ledGreen = 11;
int ledBlue = 9;
int ledYellow = 7;

//int ledRedStatus;
//int ledGreenStatus;
//int ledBlueStatus;
//int ledYellowStatus;

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledYellow, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() == '97') {
    digitalWrite(ledRed, LOW);
  }
  if(Serial.available() == '98') {
    digitalWrite(ledRed, HIGH);
  }
  if(Serial.available() == '99') {
    digitalWrite(ledGreen, LOW);
  }
  if(Serial.available() == '100') {
    digitalWrite(ledGreen, HIGH);
  }
  if(Serial.available() == '101') {
    digitalWrite(ledBlue, LOW);
  }
  if(Serial.available() == '102') {
    digitalWrite(ledBlue, HIGH);
  }
  if(Serial.available() == '103') {
    digitalWrite(ledYellow, LOW);
  }
  if(Serial.available() == '104') {
    digitalWrite(ledYellow, HIGH);
  }
}

I think that code won't compile; it should get error messages about invalid character constants like '97' ... '104'.
Either take away the single-quote marks so that you match against numbers (representing ASCII characters), or, better, substitute valid character constants like 'a', 'b', ... Also, as noted in answer, use Serial.read() to get actual data instead of number of buffered characters

Adding comments to your code would help us understand your intentions.
It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions.  And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.
Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the Serial.available() method call.  If your intentions were to read a byte of data you would instead call the serial.read() method.
It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value.  If you read the buffer many times you would be pulling a new byte of data from the buffer with each read.  If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.

  if(Serial.available() == '97')

Make sure the comparison is actually valid and Serial.available() does what you think it does. If you wish to read a value from serial port, .available() doesn't seem to be the right function for that.

I think the author of this answer asked this question to direct attention to the validity of the comparison not to get an answer.


text:
Weird formatting behavior with sprintf function
I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.
But that line:
sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

returns something like this:
3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

It's suppose to return something like this:
3000;110;291;263;230;0;0;245

Here is my sketch:
int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;

volatile boolean interruptFlag = 0;
char read[45];
char signal[2048];
volatile int count = 0;
volatile long x = 0;

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

  noInterrupts(); // Stop interrupts.

  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.

  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);

  interrupts(); // Allow interrupts.
}

ISR(TIMER1_COMPA_vect){
  if (!interruptFlag){
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag){
    writeAnalogSignals();
    count++;
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  if (strlen(read) == 0) {
    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  } else {
    sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  }
  strcat(signal, read);

  x += 2;

  if (count >= 50) {
    Serial.print(signal);
    signal[0] = 0;
    count = 0;
  }
}

Why are you even using sprintf? What's wrong with just printing the values direct to serial?

I was just using sprintf to format data instead of using concat or «+», it seems more efficient to me. But hey, I'm open to improvement. My C is far far beyond me! Is this a best practice to do multiple acquisitions before sending it on the Serial or I can send it on each iteration?

Serial is way slower than your acquisition. It depends if you want a block of data followed by a delay while it sends, or a smooth sending of values over time. Either way using strings to store the data isn't good - it's a huge waste.

What are you proposing for storing the data instead of string type?

An array of ints if you really must store it. However, unless you have a requirement to do a block of high speed sampling followed by sending then don't bother storing - just write the values out as you sample them. You're not making the sending any faster by storing them, and that is by far the slowest operation.

Have you tried replacing \r with \r\n at the end of your strings? it is possible that the serial console on your computer uses \r to return to the beginning of the line without going to a new line, then the latest content will override the previous one.

@jfpoilpret that don't work

As mentioned by @jot your x is 4 bytes but sprintf expects it to be 2 bytes because you used %d in the format string. If you want to keep x as a long, then replace the first %d with %ld and that should fix it; otherwise declar x as int. Please accept @jot answer if that fixes your problem.

Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.
When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.
For a data rate of 50Hz, I suggest to raise the baudrate to 115200.
Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the BlinkWithouDelay example and use 20ms as an interval.

Thanks @Jot. In my first implementations, I used delay().The use of interrupt came off along the way while I tried to optimize my code. I will try another baud rate.

Ok, performance is much better at 115200 bauds!

source: Stack Exchange

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

sort: votes


text:
Setting the sampling rate for timer interrupt
I had performance problems with the data acquisition and after some reading on the web, someone told to define a timer with the frequency I need (50hz):
// TIMER 1 for interrupt frequency 50 Hz:
cli(); // Stop interrupts.

TCCR1A = 0; // Set entire TCCR1A register to 0.
TCCR1B = 0; // Same for TCCR1B.
TCNT1  = 0; // Initialize counter value to 0.

// Set compare match register for 50 Hz increments.
OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
// Turn on CTC mode.
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 64 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
// Enable timer compare interrupt.
TIMSK1 |= (1 << OCIE1A);

sei(); // Allow interrupts.

But with that, I was unable to achieve good performance; I was expecting 50 reading / seconds. Luckily, I've changed for 8 bits prescaler instead of 64 and I've start to get better performance:
// Set CS12, CS11 and CS10 bits for 8 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

But, honestly, I'm a newbie and I don't understand why!

This is definitely no newbie-level stuff. If yo have enough patience, study http://www.gammon.com.au/timers and you will have all your answers.

@EdgarBonet thanks for the reference. I see Atmega2560 code. I start from Atmega328 samples to implement timer.

The Timer 1 of the ATmega2560 and the ATmega328P are essentially identical. You can study either and apply what you learn to the other.

// = 16000000 / (8 * 50) - 1 (must be <65536) that 8 in the formula refers to the prescaler. So this formula expect you to have a /8 prescaler. But four lines below you used a /64 prescaler. So your timer runs 6.25 Hz.
When you changed it to /8, you got the correct frequency.

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


text:
Arduino GPSlim 236
I'm looking to connect an old GPSlim236 device to my Arduino via serial comms. I have seen references online on how to connect the device but in the data sheet it says TTL level between 3V - 5V.  Does this mean that the GPS can automatically switch between logic level 5V -3V when needed?
Here is the link to data sheet for the GPS - http://www.holux.com/JCore/UploadFile/3205400.pdf

The datasheet says:

Power Supply
External Voltage: 5VDC +/- 10%

So I take that to mean you supply 5V to it.

Later on it says:

Transmit Data. From organizer to peripheral. (Voltage Level is 3.3V ~ 5.0V)

I presume that means that it will supply (or accept) 3.3V to 5V as a high level, and less than 3.3V as a low level. This is perfectly normal for an Arduino.

Does this mean that the GPS can automatically switch between logic level 5v -3v when needed ?

No I would not read it like that. If you read the datasheet for the Arduino processor chips it states things like an output high is a range of voltages, similar to what this device is saying. A "high" is not necessarily 5V exactly, it might be 4.7V, for example. However the Arduino input pins are similarly designed to take a range of voltages.

My confusion here is that the datasheet says 3-5v but what if I connect the device to a raspberry pi which (I think) only accepts 3v, would it still work?

Well, the datasheet says 5V +/- 10% for charging the internal battery. I'm not sure what your situation is if you are trying to run it from a Pi.

Hi Nick, thanks for the reply.  So does that mean if the GPS was connecting to a device that only accepted 3v as a logic high that it would work ? My confusion here is that the datasheet says 3-5v but what if I connect the device to a raspberry pi which (I think) only accepts 3v, would it still work ? Feel free to point me to a good document or source of information that can help me understand the difference between the different logic level.

See amended answer. If you want to connect it to a Pi, you may need level shifters, because the 5 V output would be too high for it.


text:
Adafruit feather M0 wifi firmware update
I just noticed that the firmware on the m0 wifi might need updating but says not to use the provided updater, how do you update the firmware so ?
Thanks

USE AT YOUR OWN RISK
Here's what I did... (maybe some steps not necessary, but this worked for me)
1) First run the "CheckWifi101FirmwareVersion" found in the Arduino WiFi 101 library.

NOTE: You need to add in the WiFi.setPins(8,7,4,2); after void setup() {
If it's backlevel (before 19.4.4), then

2) Download the Adafruit WiFi101 Updater on github (
   https://github.com/adafruit/WiFi101-FirmwareUpdater/archive/master.zip
   )
3) Install the "FirmwareUpdater" from the Arduino WiFi 101 Library

Add in the recommended changes (even if it's the defaults)
#define WINC_CS 8
#define WINC_IRQ 7
#define WINC_RST 4
#define WINC_EN 2

and the usual WiFi.setPins(8,7,4,2) after void setup() {

4) Copy the firmware you wish to flash to same directory as "winc1500-uploader.exe"
5) Run the command:

winc1500-uploader.exe --port [YourComPort] --firmware [YourFirmwareFileName].bin

So for example I did:

winc1500-uploader.exe --port COM9 --firmware m2m_aio_2b0.bin

NOTE: Check your board version.  It could also be:
winc1500-uploader.exe --port COM9 --firmware m2m_aio_3a0.bin


text:
Arduino JSON extract using ArduinoJSON Library
I'm having a problem extracting the Object/Array from this sample json

[
   {
     "sensor":"gps1",
     "time":1351824120
   },
   {
     "sensor":"gps1",
     "time":1351824120
   }
]

Would anyone have some pointers or sample code to allow me to extract the 'time' from each of the objects ?
Thanks

Check the library examples?

What have you tried? Post the code. Tell us in what way it doesn't work, such as error messages on compile, or unexpected response/behaviour.

You can use the ArduinoJson Assistant on arduinojson.org to create a skeleton.
Here is what it generates in your case:
const size_t bufferSize = JSON_ARRAY_SIZE(2) + 2*JSON_OBJECT_SIZE(2) + 70;
DynamicJsonBuffer jsonBuffer(bufferSize);

const char* json = "[{\"sensor\":\"gps1\",\"time\":1351824120},{\"sensor\":\"gps1\",\"time\":1351824120}]";

JsonArray& root = jsonBuffer.parseArray(json);

const char* root_0_sensor = root[0]["sensor"]; // "gps1"
long root_0_time = root[0]["time"]; // 1351824120

const char* root_1_sensor = root[1]["sensor"]; // "gps1"
long root_1_time = root[1]["time"]; // 1351824120

Thanks, that worked perfectly.  Great library and website to help building the code.


text:
Sampling rate issue
I have an Arduino code which runs decently.
// Read in 10-bits Magnetic Encoder AEAT-6010-A06  into Arduino Uno
// Sampling

// Declarate

const int CSn = 4; // Chip select
const int CLK = 7; // Clock signal
const int DO = 8; // Digital Output from the encoder which delivers me a 0 or 1, depending on the bar angle..
int analogPin = 3;
int val = 0;
unsigned int sensorWaarde = 0;

void setup() {
  Serial.begin(115200);
  //Fix de tris

  pinMode(CSn, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(DO, INPUT);

  //Let's start here
  digitalWrite(CLK, HIGH);
  digitalWrite(CSn, HIGH);
}

void loop() {

  val = analogRead(analogPin);
  // val = val - 670;
  sensorWaarde = readSensor();
  delayMicroseconds(1); //Tcs waiting for another read in
}

unsigned int readSensor() {
  unsigned int dataOut = 0;

  digitalWrite(CSn, LOW);
  delayMicroseconds(1); //Waiting for Tclkfe

  //Passing 10 times, from 0 to 9
  for (int x = 0; x < 10; x++) {
    digitalWrite(CLK, LOW);
    delayMicroseconds(1); //Tclk/2
    digitalWrite(CLK, HIGH);
    delayMicroseconds(1); //Tdo valid, like Tclk/2
    dataOut = (dataOut << 1) | digitalRead(DO); //shift all the entering data to the left and past the pin state to it. 1e bit is MSB
  }

  digitalWrite(CSn, HIGH); //
  Serial.print(dataOut);
  Serial.print("");
  Serial.print(" ");
  Serial.println(val);
  Serial.print(" ");

  delay(2);
  return dataOut;

}

From the delay data i assumed that i will be having approximately a sampling rate of 500 Hz, however it seems that the sampling rate is approximately 300+- Hz, without a proper confirmation.
My system is to be run in a Magnetic Encoder by Avago, but i have difficulties determining the sampling rate.
If possible, may i know what code should i use to indicate the time and sampling number?

At 115200 baud your serial prints will take 1/11520 seconds per byte.

Serial.print("");

What does that do?

I count 14 bytes here:
  Serial.print(dataOut);  // 5 bytes, say
  Serial.print("");       // zero bytes, lol
  Serial.print(" ");      // one byte
  Serial.println(val);    // 5 bytes + cr/lf = 7 bytes
  Serial.print(" ");      // 1 byte

Multiply 1/11520 (0.0000868) by 14 and you get 1215 µs.

Now add in your delays:
  delay(2);  // 2000 µs

And this:
 for (int x = 0; x < 10; x++) {
    ...
    delayMicroseconds(1); //Tclk/2
    ...
    delayMicroseconds(1); //Tdo valid, like Tclk/2
  }

Another 20 µs.

  val = analogRead(analogPin);   // 104 µs
  ...
  delayMicroseconds(1); // 1 µs

Total:
1215 + 2000 + 20 + 104 + 1 = 3340 µs

Inverse:
1 / 0.003340 = 299

So yes, I would expect around 299 iterations per second. That isn't counting the time for the other code to execute.

Suggestions

Get rid of the serial prints
Get rid of delay(2)

Wow, there's this kind of calculation. Thanks alot, that really2 helps alot!!! i just added, extra spaces for trial. Thank you


text:
How can I detect which baudrate a virtual COM port is set to?
I would like my software running on Leonardo to behave differently depending on the baudrate of the USB Serial set by the PC. For example, I want to make a smart USB to UART converter which performs some processing of the data it transmits. It would be much more elegant to set the UART baudrate to whatever value the PC is requesting on USB side, rather than hardcoding a value.
AFAIK 32u4 chip is used as a USB to UART converter on Mega, where it supports different baudrates, so this should be doable.
I also have a Teensy 3.2 board, so if anyone knows how to detect the baudrate on this board I'm also interested.

From looking at the source it appears that on 32u4 based boards Serial  includes extra methods to access the settings from the USB host:
see: https://github.com/arduino/ArduinoCore-avr/blob/b7c607663fecc232e598f2c0acf419ceb0b7078c/cores/arduino/USBAPI.h#L129
From USBAPI.h:
// These return the settings specified by the USB host for the
// serial port. These aren't really used, but are offered here
// in case a sketch wants to act on these settings.
uint32_t baud();
uint8_t stopbits();
uint8_t paritytype();
uint8_t numbits();
bool dtr();
bool rts();

I tried it out. On Leonardo, Serial.baud() works right after the serial has started, inside setup. On Teensy, Serial.baud() seems to return 0 inside setup, so I wait inside loop until a non-zero value is returned.

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


text:
Scheduler comparison for Arduino Uno
I understand that the official Arduino Scheduler doesn't support Uno, and there are several third-party schedulers to fill the gap, notably, Scheduler, Arduino-Scheduler and TaskScheduler. There are probably many more, though I see that many so-called "task schedulers" are actually just periodic function callers which don't handle context (i.e. they don't support yield()).
I need to make a choice of a scheduler to use in a project (a real one, with yield, not a periodic function caller). Is there any comparison of Arduino task schedulers? I'm specifically interested in the following aspects:

context switching time (the most important one)
RAM/ROM consumption estimation
list of supported boards

Arduino featured this on Facebook some weeks ago https://hackaday.com/2021/03/17/running-57-threads-at-once-on-the-arduino-uno/?fbclid=IwAR0r7ot5Yz6MYjDLW6d5_rPAbfLXv_bCqoO869QKmjz0qN1zvYtmUw1Wf8U

@Juraj This seems to be yet another cyclic function runner with no context handling. You simply can't fit 57 separate stacks in 2k of RAM.

I have just tested vbextreme/Scheduler and Arduino-Scheduler using the following code:
#include <Scheduler.h>

void setup() {
  pinMode(3, OUTPUT);
  Scheduler.startLoop(loop2);
}

void loop() {
  digitalWrite(3, LOW);
  yield();
  digitalWrite(3, HIGH);
  yield();
}

void loop2() {
  yield();
}

Without any Scheduler lines, the code occupies 734 bytes of ROM, 9 bytes of RAM, and the pin toggles with a period of 8.5 us (117 kHz). The numbers below represent the additional ROM/RAM/execution time:

vbextreme/Scheduler occupies additional 1676 bytes of ROM, 70 bytes of RAM, and the context switch takes 15.5 us (toggle frequency 14.18 kHz). It seems to only support AVR/SAMD boards.

vbextreme/Scheduler with CONFIG_AVR_OPTIMIZE_COOPERATIVE set to 1 occupies additional 1568 bytes of ROM, 70 bytes of RAM, and the context switch takes 11 us (toggle frequency 19.07 kHz).

Arduino-Scheduler occupies additional 578 bytes of ROM, 44 bytes of RAM, and the context switch takes 10.6 us (toggle frequency 19.59 kHz). It supports AVR/SAMD and some of the Teensy/STM32 boards. It seems that this scheduler is not compatible with tasks which use malloc().

CopyThreads occupies an additional 2148 bytes of ROM, 41 bytes of RAM, and the context switch takes 54.5 us (toggle frequency 4.417 kHz). This scheduler claims to have the advantage of using a single stack, so as long as tasks do not yield during peak stack usage, each task has essentially the complete stack at its disposal.

I couldn't get the equivalent code for TaskScheduler to run, I'll be grateful if someone posts an answer featuring schedulers I didn't test.

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


text:
Prevent Arduino IDE from rebuilding the core library after every restart
I have an Arduino IDE 1.8.5 setup (installed from the ZIP file) which I use to work exclusively with a single board. Every time the IDE is restarted, the first compilation takes much longer than subsequent ones. Apparently, the reason is that Arduino IDE rebuilds the core library:

Archiving built core (caching) in: C:\Users\User\AppData\Local\Temp\arduino_cache_976772\core\core_arduino_avr_mega_cpu_atmega2560_82177ffe36573ad451e992f583fff1d1.a

Is there a way to prevent that and make the IDE keep the cached core library across restarts? I have the "Aggressively cache compiled core" option checked, but it doesn't seem to help.

Use uecide instead. The caching works on there.


text:
How to rsync my node.js project to my intel edison board, through ssh?
I would love to get rid of Intel's heavy XDK software, and be able to quickly push the updates of my node.js code into my Intel Edison (arduino compatible) board.
I tried this: rsync -avz ./ root@192.168.100.177:/node_app_slot/
But rsync is not installed on the board.
How would you do this?

By installing rsync onto the edison?  I am not familiar with the flavour of Linux that Intel chose - what is it?

It's based on Yocto, which makes it not exactly trivial to add stuff, if one doesn't have previous exposure.

You have few options:

use the Yocto sdk to compile rsync and then deploy it
switch to Debian and then use the standard way to deploy rsync
use scp, like the OP wrote, using the answer from Rick

If you are already looking for a more typical Unix way of doing things, option 2 might be the most efficient for you, in the long run.
I have not tried it, but AFAIK it should be possible to revert easily, since Edison uses dfu for system upgrades, so you should be able to go back to the stock SW, in case you do not like the Debian installation.

How can you not like a Debian installation?!

Heh, I like it so much that I wrote the full howto for Galileo: https://sourceforge.net/p/galileodebian/wiki/DebianOnGalileo
Probably it sort of works also for Edison, assuming one has a microSD adapter, for supporting a less space limited installation.
But I haven't had time to try it.

rsync works by talking to the rsync executable running on the remote target; without said executable you will need to drop to either scp or a tar pipe.


text:
Problem with biased circuit for oxygen sensor (SGX EC410)
I have designed a circuit for an SGX EC410 oxygen sensor by using these application note -PAGE 4, FIGURE 4 - (http://www.sgxsensortech.com/content/uploads/2014/08/A1A-EC_SENSORS_AN2-Design-of-Electronics-for-EC-Sensors-V3.pdf). When I try to measure the biased voltage between working (SENS) and reference (REF) electrode, the value of -600 mV is held for about one second and goes down to few milli volts rapidly. The same happens when I connect the sensor without voltmeter. Am I doing something totally wrong, or the circuit is not quite right?

I'd try asking at electronics.stackexchange.com instead.


text:
Need lot GPIO pins on arduino mega - what are restrictions?
I would like to use as much as possible GPIO pins on Arduino Mega especially with (mis)using pinMode(x,INPUT); and pinMode(x,INPUT_PULLUP); to achieve two things at the same time - drive something else by the pin weakly down or up and measure the logical level there with digitalRead(x) to detemine, if that "something else" is input, or outputting some logical level.
Also I need I2C, Serial over USB and nothing else.
On Arduino UNO/nano/micro/pro it works just fine for Digital pins (except D0/D1 (RX/TX), D13 (LED as strong pull-down), A4/A5 (I2C) and A6/A7 which are not digital IO). The problem is limited number of pins, so I bought ArduinoMega.
The question is - which pins can be used that way there?
So far I am aware of D0/D1 (RX/TX), D20/D21 (I2C) and D13 (LED).
The rest (D2-D12, D14-D19, D22-D52 and A0-A15) seem aviable and usable.
Or I am missing something else?
Are there some libraries/objects I should disable to not interfere with my script?
Thank you.

"D13 (LED as strong pull-down)," You are misinformed there. D13 is also connected to the input of a comparator (LM358) which then drives the LED. The LED does not present a strong pulldown.  If you are not using I2C or SPI, those pins are also available.

I looked at it, but it depends on version, https://store.arduino.cc/arduino-uno-smd-rev3 shows still connection of direct led+resistor on D13, https://store.arduino.cc/arduino-uno-rev3 have comparator, my old UNO (with DIP) also have resistor+LED, Nano also have LED+resistor and no comparator. So only some revisions of some types have the comparator at all.

My last project had problems just for this reason and I was forced to rearrange the pin usage to avoid D13 for this very reason (unconnected D13 with INPUT_PULLUP had show  like 1.3V on voltmeter, while all others show over 4.5V ), so it is not just matter of some PDF, but real physical units proves that too.

All those pins should be available. But if you want to use Pin change interrupts, you have to check which pins are usable.

No more than 2 pin interrupts and it is not so much needed anyway (just reading buttons, digitalRead can work just as well, as there is a lot of points, where I can check regulary)


text:
burn arduino bootloader and compiled sketch at same time
How can I write the bootloader and sketch code to an Arduino through the ISP and then write the sketch code again using the Arduino IDE later?
Currently, I can write the bootloader through the ISP and then write the sketch through the Arduino IDE.  This works just like normal.
I can also write the bootloader and sketch through the ISP.  The code runs like normal, but I can't load a new version of the sketch through the Arduino IDE.  It just timesout.
Here's what the IDE says when it attempts to upload the program:
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

The Arduino IDE creates two hex files after compiling the sketch: one is just the compiled sketch (Sketch.ino.hex) and the other is the compiled sketch with the bootloader code appended to the end (Sketch.ino.with_bootloader.hex).  So, I feel like this should be possible because Arduino produces the file for me.

There are several plausible reasons that the bootloader doesn't work when contacted by acrdude, driven by the Arduin IDE. It may be that writing a combination of compiled Sketch and bootloader using ISP does not enable the ATmega to run the bootloader in response t the IDEs 'remote' RESET. For example the combination are not linked correctly, so the bootloader is not 'connected' to the RESET interrupt. Or the bootloader is not put into the correct place. DO you know how to use objdump to check that code is at the correct address, and interrupt vectors have the right value?

Summary: IMHO In theory, anything can be written into ATmega flash over ISP.  It should be possible to write the bootloader and program at the same time over ISP. However, IMHO you'll need to post the link script, avrdude configuration and command line, program, and a link to the bootloader to get an accurate answer.

You may well be able to simply concatenate the hex files.

The Arduino IDE concatenates the files for me.  That's the file I'm uploading.  Also, I'm not using AVR dude. My sketch code is compiled by the Arduino IDE.  Everything is done by the Arduino IDE except I am loading the bootloader using the mkII AVR-ISP which connects to Atmel Studio.

I've never seen the arduino IDE do this, but I'm sure you're not mistaken (I have to look into this myself). The first thing that comes to mind, that the wrong fuses are set, so it never jumps to the bootloader. Could you add the verbose output of compiling and uploading the code with bootloader to your question? Also what version are you using?

I figured out the problem.  Turns out the Arduino wasn't being reset after loading the code so it wouldn't startup properly, leading me to believe it wasn't working.  I just had to hit the reset button and then the sketch code executed as normal.  So, you can load the bootloader and sketch code at the same time without doing anything special and it will work as if you loaded the bootloader through ISP and sketch code through Arduino IDE.

Normally (using the IDE via the serial/USB interface) the bootloader is retained, and the bootloader itself replaces the main code.
If you do ICSP programming then the first thing the programmer has to do is erase the entire chip (including the bootloader). Now nothing is stopping you putting the bootloader back as part of the programming sequence (it would add to the programming time slightly).
As Chris Stratton suggests, this is basically combining the .hex file for the sketch, and the .hex file for the bootloader. I'm not sure that literally concatenating them would work because there are a couple of other "record types" in the .hex file which might confuse the programmer if they were encountered twice - in particular the "end of file" record type.
However a strategy along these lines should give you a file that could be uploaded and put the bootloader back:

Take the .hex file from the compiler, and copy up to, but excluding, the "end of file" record to a temporary file.
Append the desired bootloader .hex file (including the "end of file" line).
Program the chip with the resulting file.

For larger chips (like the Atmega2560) you would need to be cautious about handling the "extended segment address" record because that sets the high-order byte of the address to be programmed.
The hex file format, as documented in my programmer sketch is:
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

  nn     = length of data part
  aaaa   = address (eg. where to write data)
  tt     = transaction type
           00 = data
           01 = end of file
           02 = extended segment address (changes high-order byte of the address)
           03 = start segment address *
           04 = linear address *
           05 = start linear address *
  (data) = variable length data
  ss     = sumcheck

            * We don't use these

I belive what you want to do is program a Arduino by ISP and retain the bootloader, I have done this on occasion by first loading the bootloader onto a chip, then upload the Arduino sketch, then i use the ISP programmer to read the whole flash back into hex file.
This hex file is then used to program the rest of the chips for production. (If you feel this takes too much time, it is possible to strip the hex file down, but that might be a bit complicated)

If you program via ISP, it erases the boot loader, because you do not need it. The whole point of the boot loader is to allow programming over USB. So if you want to use the normal Arduino USB input to program, burn the bootloader and then do not use the ISP.
Note my knowledge of this dates back to older arduino ~1.0 software, it is possible modifications have been made, but the above should still be true. If you have an ISP you do not need the bootloader at all.

I am programming the sketch's code and bootloader at the same time so the bootloader is not erased.  The bootloader code is definitely there.  I can read the memory through the ISP and see that the bootloader code is there.

Are you setting the programmer option back to the arduino option in the Arduino software? Stk500, is that the programmer that arduino uses by default or is that your ISP?

I am using Atmel Studio to run the AVR-ISP.  Then I connect the USB cable and use the Arduino IDE.  So I'm not changing anything in the Arduino IDE.  The Arduino IDE uses STK500.

Hmm odd, I guess I was not to helpful, hopefully someone else will have more experience with this.


text:
ATtiny85 Timer 1 comparator A interrupt problem
I'm writing a program on attiny85 using interrupts. It is a simple program:
- when rising edge is detected on PCINT0, drive DEBUG_PIN to HIGH
- when TIMER1 counts up to OCR1A, drive DEBUG_PIN to LOW
Problem is that when program detects rising edge on PCINT0, it starts Timer1 comparator A and then immediately calls ISR(TIMER1_COMPA_vect). As an effect, on DEBUG_PIN there is only a little narrow spike instead of a nice square wave of length 50ms (checked it with oscilloscope).
Im using ARDUINO IDE. Here is the code:
/*
 * Movement detection using interrupts instead of linear approach
 *
 * POS_TIMEOUT will be checked using COMPA on TIM0
 * IMP_TIMEOUT will be checked using COMPB on TIM0
 * LOOP_TIME will be chcecked using TIMER1 overflow
 *
 * INT0_PIN_IN  (PB2) is the pin that receives the signal
 * INT0_PIN_OUT (PB4) is the pin used for external interrupt debugging
 * DEBUG_PIN    (PB3) is the pin used for debugging
 * STATUS_PIN   (PB1) - high when awake, low when asleep
*/

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
//#include "timers_init.h"

//Watch out! do not use the reset pin (PB5)!

#define INT0_PIN_IN     0
#define INT0_PIN_OUT    4
#define STATUS_PIN      1
#define DEBUG_PIN       3
#define POS_TIMEOUT     50

#define PRE_1     0
#define PRE_2     1
#define PRE_4     2
#define PRE_8     3
#define PRE_16    4
#define PRE_32    5
#define PRE_64    6
#define PRE_128   7
#define PRE_256   8
#define PRE_512   9
#define PRE_1024  10
#define PRE_2048  11
#define PRE_4096  12
#define PRE_8192  13
#define PRE_16384 14

/*******MONITORING*VARIABLES*VOLATILES**************/
/* variable keeping last state of INT0 input */
volatile bool lastState = false;

/*************STATUS FLAGS**************************/
/* flags used for movement detection */
/* all flags are initiated as false */

volatile bool positiveFlag  = false;
volatile bool fallingEdge   = false;
volatile bool risingEdge    = false;
volatile bool positiveTimeoutCheck  = false;
volatile bool impulseTimeoutCheck = false;
/*************UTILS*********************************/
void timerOneCompADisable( void ){
  bitClear(TIMSK, OCIE1A);
}

void timerOneCompAInit( uint8_t compValue  ){
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

/******************
 * INTERRUPTS!!!
******************/

/*
 * This interrupt is called every time PCINT0 input state changes
*/
ISR(PCINT0_vect){
  bool readPin = digitalRead( INT0_PIN_IN );

  //falling edge
  if( lastState && lastState != readPin ){
    fallingEdge = true;
    lastState = false;
  }
  //rising edge
  else if( !lastState && lastState != readPin ){
    risingEdge = true;
    lastState = true;
  }
}

//TIMER 1 COMPARE match A
ISR(TIMER1_COMPA_vect){
  positiveTimeoutCheck = false;
  digitalWrite( DEBUG_PIN, LOW );
  timerOneCompADisable();
}

/**********************
 * MAIN CODE!!!!!!!
**********************/

void setup(){

  /* Pin config */
  pinMode( INT0_PIN_IN, INPUT );
  pinMode( DEBUG_PIN, OUTPUT);

  /* Pin initialization */
  digitalWrite( DEBUG_PIN, LOW );

  /* Timers configuration */
  //prescaler is 8192 so one tick is ~1 ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

  /* Interrupts initialization */
  bitSet( GIMSK, PCIE );
  bitSet( PCMSK, PCINT0 );
}

/* function resetting flags */
void resetFlags( void ){
   positiveFlag  = false;
   fallingEdge   = false;
   risingEdge    = false;
   positiveTimeoutCheck  = false;
}

int main(){
  cli();
  setup();

  /* Variables initialization */
  lastState = digitalRead( INT0_PIN_IN );
  resetFlags();
  sei();

  while(1){
      /* State machine */

      //if nothing is going on and rising edge is detected
      //reset everything and ignite positive flag
      if( risingEdge ){
        cli();
        resetFlags();
        positiveFlag = true;
        sei();
      } // if

      //INT0 is high, initiate positive timeout check
      else if( positiveFlag && !positiveTimeoutCheck ){
        cli();
        resetFlags();
        timerOneCompAInit( POS_TIMEOUT );
        positiveTimeoutCheck = true;
        digitalWrite( DEBUG_PIN, HIGH );
        TCNT1 = 0;
        sei();
      } //else if

  } //while

  return 0;
}

Thank you guys! All I had to do is disable TIMER1, reset it, set COMPA, reset OCF1A ("bitSet(TIFR,OCF1A)") and set prescaler before sei();.
Here is my final, working code:
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
//#include "timers_init.h"

//Watch out! do not use the reset pin (PB5)!

#define INT0_PIN_IN     0
#define INT0_PIN_OUT    4
#define STATUS_PIN      1
#define DEBUG_PIN       3
#define POS_TIMEOUT     70

#define PRE_1     0
#define PRE_2     1
#define PRE_4     2
#define PRE_8     3
#define PRE_16    4
#define PRE_32    5
#define PRE_64    6
#define PRE_128   7
#define PRE_256   8
#define PRE_512   9
#define PRE_1024  10
#define PRE_2048  11
#define PRE_4096  12
#define PRE_8192  13
#define PRE_16384 14

/*******MONITORING*VARIABLES*VOLATILES**************/
/* variable keeping last state of INT0 input */
volatile bool lastState = false;

/*************STATUS FLAGS**************************/
/* flags used for movement detection */
/* all flags are initiated as false */

volatile bool positiveFlag  = false;
volatile bool fallingEdge   = false;
volatile bool risingEdge    = false;
volatile bool positiveTimeoutCheck  = false;
volatile bool impulseTimeoutCheck = false;
/*************UTILS*********************************/
void timerOneCompADisable( void ){
  bitClear(TIMSK, OCIE1A);
}

void timerOneCompAInit( uint8_t compValue  ){
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

void timerOneDisable(){
  TCCR1 |= (0<<CS13)|(0<<CS12)|(0<<CS11)|(0<<CS10);
}

/******************
 * INTERRUPTS!!!
******************/

/*
 * This interrupt is called every time PCINT0 input state changes
*/
ISR(PCINT0_vect){
  bool readPin = digitalRead( INT0_PIN_IN );

  //falling edge
  if( lastState && lastState != readPin ){
    fallingEdge = true;
    lastState = false;
  }
  //rising edge
  else if( !lastState && lastState != readPin ){
    risingEdge = true;
    lastState = true;
  }
}

//TIMER 1 COMPARE match A
ISR(TIMER1_COMPA_vect){
  positiveTimeoutCheck = false;
  digitalWrite( DEBUG_PIN, LOW );
  TCNT1=0;
  timerOneCompADisable();
}

/**********************
 * MAIN CODE!!!!!!!
**********************/

void setup(){

  /* Pin config */
  pinMode( INT0_PIN_IN, INPUT );
  pinMode( DEBUG_PIN, OUTPUT);

  /* Pin initialization */
  digitalWrite( DEBUG_PIN, LOW );

  /* Timers configuration */
  //prescaler is 8192 so one tick is ~1 ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);

  /* Interrupts initialization */
  bitSet( GIMSK, PCIE );
  bitSet( PCMSK, PCINT0 );
}

/* function resetting flags */
void resetFlags( void ){
   positiveFlag  = false;
   fallingEdge   = false;
   risingEdge    = false;
   positiveTimeoutCheck  = false;
}

int main(){
  cli();
  setup();

  /* Variables initialization */
  lastState = digitalRead( INT0_PIN_IN );
  resetFlags();
  sei();

  while(1){
      /* State machine */

      //if nothing is going on and rising edge is detected
      //reset everything and ignite positive flag
      if( risingEdge ){
        cli();
        resetFlags();
        positiveFlag = true;
        sei();
      } // if

      //INT0 is high, initiate positive timeout check
      else if( positiveFlag && !positiveTimeoutCheck ){
        cli();
        resetFlags();
        timerOneDisable();
        timerOneCompAInit( POS_TIMEOUT );
        positiveTimeoutCheck = true;
        digitalWrite( DEBUG_PIN, HIGH );
        bitSet(TIFR,OCF1A);
        TCNT1 = 0;
        TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
        sei();
      } //else if

  } //while

  return 0;
}

the code is a little too long for me to go through but sounds like this is a one-shot compare.
With that, you should turn off the timer1, clear the timer1 compa flag, set the compare match point forward (COMPA = target count if TCNT1 is reset, or COMPA = TCNT1 + target if TCNT1 is NOT reset), enable the timer1 compa interrupt, and start the timer1. All of that in the PCNT1 interrupt (where timer1 is armed).
Some of the actions can be structured in the timer1 initialization routine, or even after timer1 compa isr if you want to improve the code responsiveness.
Otherwise, your timer1 keeps running and once the counter passes COMPA, the flag is set, regardless of if the interrupt is set or not.

Man, youre great!!!! All I had to do was to: 1. Disable TIM1; 2. Reset TIM1; 3. Set COMPA 4.Enable TIM1 5.Enable interrupts . One more question: is there a way to disable timer (make it stop counting) without clearing  its prescaler bits?

there is no "prescaler counter" in the avrs so the answer is no (in general). in some cases, you can read the prescaler -> by externally switching the input to a gpio pin and flip that pin until the counter advances. But that doesn't seem to be the case here.

You should move the line TCNT1 = 0; from loop() into timerOneCompAInit() function:
void timerOneCompAInit( uint8_t compValue  ){
  TCNT1 = 0;
  //set comparatorA value
  OCR1A = compValue;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
}

Otherwise, during the timelapse between  OCR1A = compValue; and TCNT1 = 0;, it is highly possible that TCNT1 reaches OCR1A and thus sets the OCF1A flag in TIFR, which will generate an interrupt and call ISR(TIMER1_COMPA_vect) immediately after sei() is called in loop().
The fact is Timer1 is always running since it has been enabled at setup(), hence TCNT1 is continuously changing from 0 to 255 and back to 0.
Hence in your current code, at the time you execute OCR1A = compValue;, TCNT1 may have any value between 0 and 255, if its value is >50 (POS_TIMEOUT), then an interrupt will be generated.
Roughly the probability for this interrupt to happen is at least 80% (i.e. (255-50)/255).


text:
Attiny85: Watchdog does not initialize properly when using switch(case)
I have a project in which I am putting my ATtiny85 to sleep. Here is the watchdog configuration (in the setup) that works just fine:
void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( LED_PIN, INPUT );
  pinMode( STATUS_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );

  /*** Setup the WDT ***/

  /* Clear the reset flag of watchdog interrupts, so that they are available again. */
  MCUSR &= ~(1<<WDRF);

  /* Enable configuration changes */
  WDTCR |= (1<<WDCE) | (1<<WDE);

/*
WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                         Oscillator Cycles     VCC = 5.0V
  0         0      0        0             2K (2048) cycles       16 ms
  0         0      0        1             4K (4096) cycles       32 ms
  0         0      1        0             8K (8192) cycles       64 ms
  0         0      1        1            16K (16384) cycles    0.125 s
  0         1      0        0            32K (32768) cycles    0.25 s
  0         1      0        1            64K (65536) cycles    0.5 s
  0         1      1        0            128K (131072) cycles 1.0 s
  0         1      1        1            256K (262144) cycles 2.0 s
  1         0      0        0            512K (524288) cycles 4.0 s
  1         0      0        1            1024K (1048576) cycles 8.0 s
*/
  /* set new watchdog timeout prescaler value */
  WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

Here is the function that actually puts my microcontroller to sleep:
void enterSleep(void)
{
//  /* disable all interrupts */
//  cli();
  lcd.clear();
  lcd.print("Asleep...");

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
  sleep_enable();
  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );
  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);
}

Then I decided to do a switch case construction, so that I won't have to change manually WDTCR register each  time I want to change the sleep time. So here is my new setup code:
int sleepTime = 0;

void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( IN_PIN, INPUT );
  pinMode( STATUS_PIN, OUTPUT );
  pinMode( DEBUG_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );
  digitalWrite( DEBUG_PIN, LOW );

  /*** Setup the WDT ***/
//  sleepDevice.watchdogInit();
    /*** Setup the WDT ***/
    /* Clear the reset flag of watchdog interrupts, so that they are available again. */
    MCUSR &= ~(1<<WDRF);

    /* Enable configuration changes*/
    WDTCR |= (1<<WDCE) | (1<<WDE);

  /*
  WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                           Oscillator Cycles     VCC = 5.0V
    0         0      0        0             2K (2048) cycles       16 ms
    0         0      0        1             4K (4096) cycles       32 ms
    0         0      1        0             8K (8192) cycles       64 ms
    0         0      1        1            16K (16384) cycles    0.125 s
    0         1      0        0            32K (32768) cycles    0.25 s
    0         1      0        1            64K (65536) cycles    0.5 s
    0         1      1        0            128K (131072) cycles 1.0 s
    0         1      1        1            256K (262144) cycles 2.0 s
    1         0      0        0            512K (524288) cycles 4.0 s
    1         0      0        1            1024K (1048576) cycles 8.0 s
  */

  switch( sleepTime ){
    case 0:
      WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
    case 1:
      WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
      break;
    default:
      WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
  }

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

The enterSleep function is not changed.
But this time sleeping does not work at all! In fact, ATtiny sort of freezes. Does any one has any idea why it is so? To me it looks like the Arduino IDE is confused with switch case instruction, but maybe there is something wrong with my code...

Several things going on here. First, you do not need to fiddle with the change enable bit to change the prescaller. Second, you do not know the value of the watchdog timer at any point in your code, so random stuff can happen.  I would (1) disable to watchdog timer completely, (2) update the prescaller bits (3) only just before sleeping (a) clear the watchdog counter with a  wdt_reset(), (b) then enable to WDT and the interrupt. (c) sleep. On waking, disable the WDT immediately.

@bigjosh But why is it so, that everything works fine when I don't use switch? As soon as I use it, nothing works...

The switch statement is at least one additional compare and branch compared to the original code. This means more cycles, which may be enough for the WDT to expire. Do you get the result when you run the switch with the same prescaller? Do you get the same result when you add a few nops before the the line that sets the prescaller in the orginal version?

Also keep in mind that you are enabling config changes and then entering the switch statement, but you have no way to ensure that all cases of the switch will execute within the 4 cycle window that opens after the enable bit is written. I'd start with the simplest case and work your way back - too much unpredictable stuff going on here to be able to pin down which of the problems you are actually seeing.

Note that if the Watchdog is enabled, it keeps being enabled, even after a reset. This can be especially problematic, if you set it to a very short time. So the very first thing you should do in your setup is to disable the WDT.

@bigjosh So after I set the Enable bit, I have to ocnfig the watchdog prescaler, right? That shines some different light on issue...

Alright, thanks to you guys I fixed the issue.
The main thing is that any changes in the configuration have to be made within 4 cycles after the CONFIG ENABLE bit is set. It is done with this instruciton:
/* Enable configuration
WDTCR |= (1<<WDCE) | (1<<WDE);

Now switch works like a charm. So the final code for watchdog setup looks like this:
void Sleeper::watchdogInit( void ){
    /*** Setup the WDT ***/
      /* Clear the reset flag of watchdog interrupts, so that they are available again. */
      MCUSR &= ~(1<<WDRF);

    /*
    WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                             Oscillator Cycles     VCC = 5.0V
      0         0      0        0             2K (2048) cycles       16 ms
      0         0      0        1             4K (4096) cycles       32 ms
      0         0      1        0             8K (8192) cycles       64 ms
      0         0      1        1            16K (16384) cycles    0.125 s
      0         1      0        0            32K (32768) cycles    0.25 s
      0         1      0        1            64K (65536) cycles    0.5 s
      0         1      1        0            128K (131072) cycles 1.0 s
      0         1      1        1            256K (262144) cycles 2.0 s
      1         0      0        0            512K (524288) cycles 4.0 s
      1         0      0        1            1024K (1048576) cycles 8.0 s
    */

    switch( sleepTime ){
        case 0:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_500:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
            break;
        case MSEC_250:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_125:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 1<<WDP0 ;
            break;
        case MSEC_64:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_32:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
    default:
      /* Enable configuration changes*/
      WDTCR |= (1<<WDCE) | (1<<WDE);
      WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
    }

Try this for your sleep function...
void enterSleep(void)
{
  lcd.clear();
  lcd.print("Asleep...");

  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );

  /* disable all interrupts, if we get interrupted we might timeout the WDT */
  cli();

  /* Reset the watchdog counter so we know that we are starting at 0 */
  wdt_reset()

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */

  sleep_enable();
  sei();
  /* Now enter sleep mode. */
  sleep_cpu();
  cli(); // Make sure we have time to disable WDT before we get reset

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  sei();

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

}

Problem is that the whole program freezes right after I setup the watchdog prescaler with switch case. Even if I never use enterSleep function, it still does happen.

If the wdt is enabled when you change the prescaler, it is possible the whatever the current value of the counter is happens to be above the new prescaler, which would cause an instant wdt timeout. That is why it is important to always clear the counter before updating the prescaller- and to do it when no interrupts are possible so the processor doesn't get sidetracked in between the steps.

If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will **clear WDIE** and WDIF automatically by hardware, so calling WDTCR &= ~_BV(WDIE); is pointless.


text:
How to compile, upload and monitor via the Linux command line?
Interfacing an Arduino Uno (uploading etc.) with the Arduino IDE (using the Fedora package) works fine under Fedora 21.
But I rather want to use vim + make + vim-quickfix-mode etc.
How can I do that?
Preferably via the tools available from the Fedora repositories.
I assume that the IDE calls externals command line utilities for the uploading etc.
The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. screen) to /dev/ttyACM0, right?
Perhaps there is a good example project one can look at the makefile?

Bumping as all of these answers are quite old As of Jun 05th 2021, the arduino-cli tool is extremely good. You can make a very simple 2 line Makefile in no time.

A great way to compile for and flash an Arduino device from the command line and integrate with Vim is to use PlatformIO Core (CLI).
Since it's written in Python it's easy to install even when it's not packaged for your Linux distribution. PlatformIO supports many microcontroller devices, not just Arduino ones. Thus, you don't have to switch your development environment when you target another platform. PlatformIO takes care of downloading the right toolchain (compiler etc.) for your target.
Example
Getting started with PlatformIO and an Arduino Pro Mini 3.3v clone on Fedora 35:
mkdir -p ~/local
cd ~/local
python -m venv platformio
source platformio/bin/activate
pip install platformio

This installs PlatformIO (CLI) in a virtual environment, i.e. its main command is then available from ~/local/platformio/bin/pio and pio is found in your PATH when the virtual environment is activated.
Next, we need to find the right board ID for setting up a new project:
pio boards arduino | less

That means search for Pro.*Mini in the listing. There are several versions of the Pro Mini, in our example the pro8MHzatmega328 (3.3 V, 8 MHz, ATmega328, 30 kb flash, 2 kB RAM) is the right one as can be validated by looking at the board markings as well as its voltage regulator, and CPU markings.
To set up a new project
mkdir ~/project/some_new_project
cd ~/project/some_new_project
pio project init --board pro8MHzatmega328 --ide vim

Which prints:
The current working directory /home/juser/project/arduino/pro-mini will be used for the project.

The next files/directories have been created in /home/juser/arduino/pro-mini
include - Put project header files here
lib - Put here project specific (private) libraries
src - Put project source files here
platformio.ini - Project Configuration File
Platform Manager: Installing atmelavr
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
Platform Manager: atmelavr @ 3.4.0 has been installed!
Tool Manager: Installing platformio/toolchain-atmelavr @ ~1.70300.0
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
Tool Manager: toolchain-atmelavr @ 1.70300.191015 has been installed!
The platform 'atmelavr' has been successfully installed!
The rest of the packages will be installed later depending on your build environment.

Project has been successfully initialized including configuration files for `vim` IDE.

For a first test one can copy a simple blink-led example using the usual setup()/loop() functions. It's possible to re-use an existing 'sketch' from the Arduino IDE, one just has to add #include <Arduino.h> at the top and place it under src/some-name.cc or src/some-name.cpp.
To compile everything:
pio run

Which prints:
Processing pro8MHzatmega328 (platform: atmelavr; board: pro8MHzatmega328; framework: arduino)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/pro8MHzatmega328.html
PLATFORM: Atmel AVR (3.4.0) > Arduino Pro or Pro Mini ATmega328 (3.3V, 8 MHz)
HARDWARE: ATMEGA328P 8MHz, 2KB RAM, 30KB Flash
DEBUG: Current (avr-stub) On-board (avr-stub, simavr)
PACKAGES:
 - framework-arduino-avr 5.1.0
 - toolchain-atmelavr 1.70300.191015 (7.3.0)
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 5 compatible libraries
Scanning dependencies...
No dependencies
Building in release mode
Compiling .pio/build/pro8MHzatmega328/src/sos-switch.cc.o
Linking .pio/build/pro8MHzatmega328/firmware.elf
Checking size .pio/build/pro8MHzatmega328/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.4% (used 9 bytes from 2048 bytes)
Flash: [          ]   3.8% (used 1170 bytes from 30720 bytes)
========================= [SUCCESS] Took 0.51 seconds =========================

So for this example I created src/sos-switch.cc which is compiled to .pio/build/.../sos-switch.cc.o.
To upload (flash) the device:
pio run --target upload

As always, a common pitfall are the permissions of the USB device. For example, on Fedora, my USB2TTL serial device registers as /dev/ttyUSB0 with read-write permissions for just root:dialout. Thus, you have to add your user to the dialout group or adjust the permissions by other means.
Vim Quickfix Mode
For integrating with Vim's quickfix mode a simple makefile is sufficient, e.g.:

.PHONY: all
all: build

.PHONY: build
build:
    pio run

.PHONY: upload
upload:
    pio run --target upload

Thus, everything is built when :make is invoked in Vim, and there one can navigate the quickfix mode as usual.
Serial Monitoring
An easy way to monitor the serial interface is to use picocom, e.g.:
picocom --baud 9600 --echo --imap lfcrlf --noreset /dev/ttyUSB0

where:

--imap lfcrlf maps newline to carriage return + newline such that we can just write Serial.print("multi\nlines\n') instead of Serial.print("multi\r\nlines\r\n") in our program
--noreset tells picocom to not clear DTR - without it, when DTR is connected, the Anrdoid device is reset

Of course, one has to terminate picocom when uploading.

Alternatively, one can use the PlatformIO monitor command:
pio device monitor

In contrast to picocom, it doesn't require explicit mapping or DTR handling. However, as with picocom, it must be terminated when uploading/flashing. That means PlatformIO doesn't automatically suspends monitoring when pio run --target upload is invoked.
Closing Remarks

PlatformIO is currently packaged for Fedora and thus might be directly available in Fedora 36 or so
the classic Arduino IDE was packaged for Fedora, but isn't available anymore in Fedora 35 because of the big Java package exodus
there is also a PlatoformIO plugin for VSCode which seems to be quite popular

Nice answer. Re “--imap lfcrlf”: This is not needed if you use Serial.println(), which is the “Arduino way” of printing a new line.

@EdgarBonet yes, Serial.println() writes \r\n, thus we don't need the mapping if it's used exclusively. However, both the classic Arduino IDE and the PlatformIO monitor implicitly map \n to \r\n such that you get away with single \n. If you transmit \r\n you might end up with \r\r\n, which doesn't hurt. Even if your program uses Serial.println() you still might use \n in multi-line strings. Updated my answer to illustrate this point. However, for an end-user facing console, it makes sense to stick to \r\n and detect oversights by not having such a mapping.

I use the command-line interface to the arduino command.
I run it like this:
arduino --upload sketch/sketch.ino --port /dev/ttyUSB*

There is a page which describes other command-line tools, like inotool. That page also has an example Makefile. These alternatives seem enticing, but apparently, as of this writing, none of them work. I'm assuming this is due to some recent changes in Arduino IDE distribution files which they depend on.
Running arduino as above is a bit slow, because it has to load Java I guess, but at least it works. There is also an arduino-builder command that comes with the Arduino IDE distribution. As of this writing, it was not sufficiently well-documented for me to be able to figure out how to use it. For instance there are no example command lines in the README or in any of the tutorials I came across, and I couldn't figure out how to use it to upload code to the board. However, presumably it is able to give us a faster compile than arduino. The README also mentions being able to reuse object files from a previous compile, so there is some make-like functionality.

To view serial output I use something like
stty -F /dev/ttyUSB* 1000000 raw -clocal -echo
cat /dev/ttyUSB*

The number 1000000 should match the number you pass to Serial.begin() in your board code. You can also use screen if you have a board program which is appropriately interactive, or you can use whatever utility to write directly to the device. By the way, my Due shows up as /dev/ttyACM0 (rather than /dev/ttyUSB0 for the Uno).

Make sure you have a single *.ino file in the directory, as it does not seem to necessarily upload the one mentioned by the --upload parameter.

No X11 DISPLAY variable was set, but this program performed an operation which requires it.
For me

I would suggest Googling for Makefile projects. I did one a while back for the Blink program, by basically seeing what got generated by the IDE and replicating that in a more general way.
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

You would need to change ARDUINO_DIR at least, to reflect where you installed the IDE. If you use other things like the Wire library you would need to expand it somewhat to compile additional libraries. Again, you can use what the IDE generates itself to guide your changes.
The lines with the leading spaces above would need the tab character instead of spaces, as is normal for a Makefile.

An upload section in the make file would also be useful, to upload the compiled sketch to the arduino (using avr-dude).

That would definitely be useful. However as, so far, the IDE has met my needs for compiling and uploading, I am not strongly motivated to work out how to do it. :)

Take a look at Metamorphic answer for an easier solution

Someone suggested editing out the statement "I would suggest Googling for Makefile projects." on the grounds that people probably reached this page from Google anyway. However I think it is still a helpful suggestion, especially in direct response to the posted question. My answer gave one suggested way of achieving the result, a Google search may supply others.

What you need is a Makefile.  There are a few Makefile projects around for Arduino.  Googling for "Arduino Makefile" returns many results including what looks like a good one on Github: https://github.com/sudar/Arduino-Makefile
Compiling from the command line isn't trivial due to the way the Arduino IDE handles libraries.

The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. screen) to /dev/ttyACM0, right?

For the serial monitor I would recommend minicom. It is a fully functional terminal emulator (vt102) on the command line.
minicom -D /dev/ttyACM0 -b 115200

... for example.

This Makefile is essentially a maintained version of the accepted answer. There is also a template project on GitHub that shows you how to set it up: https://github.com/ladislas/Bare-Arduino-Project

Official CLI tool
The arduino team is developing a cli client
https://github.com/arduino/arduino-cli
Announcement: https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/
You can do almost everything with this, from downloading boards and libraries, to compile and upload scripts. What's missing is the monitoring part (you can use Metamorphic's method using stty cat, It works!)
The commands are very similar to Metamorphic's answer since this tool is branching out of that one
Instructions in the Github repo and the man page:
    $ arduino-cli Arduino Command Line Interface (arduino-cli).

    Usage:   arduino-cli [command]

    Examples: arduino <command> [flags...]

    Available Commands:
      board         Arduino board commands.
      compile       Compiles Arduino sketches.
      config        Arduino Configuration Commands.
      core          Arduino Core operations.
      help          Help about any command
      lib           Arduino commands about libraries.
      sketch        Arduino CLI Sketch Commands.
      upload        Upload Arduino sketches.
      version       Shows version number of Arduino CLI.

If you want a fully compatible solution for your arduino project (yes, you can share your project with other people that use just plain Arduino IDE) you need to check amake a tool to simplify the cli of the arduino, I use it with Geany but others are using it with vi, Atom, etc.
It's inspired and the now dead Ino and Arturo projects; please take 5 minutes to test it and please give feedback.
Example use:
cd ~/Arduino/Blink/
[move to your arduino project folder]

amake -v uno Blink.ino
[to compile/verify your code]

amake -u uno Blink.ino /dev/ttyUSB0
[to upload your code to an arduino connected via USB]

It has some smart glue in there, it can remember the board and file, and even autodetect the usb of the board; so after a successfull "amake -v" command you can do this on the command line and it will work.
amake -v
[to compile/verify your code]

amake -u
[to upload your code to an arduino connected via USB]

If you use some IDE macros you can craft the compile and upload commands easily, for example using Geany IDE it will became:

Compile/Verify: cd %d; amake -v uno %f
Upload: cd %d; amake -u uno %f

You can get more help running just "amake" or "amake -h" once installed.
Also, it can support EVERY board/lib/programmer you have installed/configured in your Arduino IDE, yes, modern board like the Adafuit Trinket M0 / Arduino M0 etc...
Just fire your Arduino IDE, go to the board manager, install support and that's all, jut follow some simple instructions and your are set.
The board you have is not supported? not a problem, detect the fqbn (read the README.md file) and pass it along as the board name.
I'm looking for testers to grow up the number or board aliases and auto detection of the proper USB signatures.
Remember this is a private grown tool, now shared with the public, you know, just a programmer scratching it's itch...
Cheers.


text:
Loop though array values at end of each for loop cycle
I'm using the NeoPixel Ring from Adafruit and trying to pulse though and array of colors. However, I'm having trouble with having the loop go to the next color at the end of each pulse (end of loop). Here is what I currently have:
uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed){
  int fadeAmount = 10; //how much to increase each loop
  int n = 0; //get first color
  for(int b = 100; b >= 10; b = b - fadeAmount) { //start pulse for loop
    for (int i = 0; i < strip.numPixels(); i++) { //select all pixels
      strip.setPixelColor(i, color[n]); //set color from our array
      }
    strip.setBrightness(b); //set brightness based on b
    strip.show(); // send the changes to the strip
    delay(speed); //wait before running again
    //if at the end of the loop (brightness is 10) change color
    if (b == 10){
      if( n > 6){ //if we are at last color in our loop start over
        n = 0;
      }
      else{
        n++; //auto increment color value
      }
    }
  }
}

I'm sure the problem is with the if statements but not sure how to fix it.

Where is the loop for going through each color?

@IgnacioVazquez-Abrams I was trying to do it with an if statement and n++ instead of a loop.

if is not a looping statement.

I can't quite make out what your if test is supposed to be doing, but don't you want a loop within a loop? Like this?
uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed)
  {
  const int fadeAmount = 10; //how much to increase each loop
  for (int currentColor = 0; currentColor < 6; currentColor++)
    {
    for (int i = 0; i < strip.numPixels(); i++)
      { //select all pixels
      strip.setPixelColor(i, color[currentColor]); //set color from our array
      }
    for(int brightness = 100; brightness >= 10; brightness -= fadeAmount)
      { //start pulse for loop
      strip.setBrightness(brightness); //set brightness based on brightness
      strip.show(); // send the changes to the strip
      delay(speed); //wait before running again
      }  // end of brightness loop
    }  // end of colour loop
  }  // end of pulseUp

Yep, that's what I was trying to do. I tried something similar but must of had something off. Also what's the difference between int and const int ?

@BandonRandon: One can be changed, the other can't. Which means that the compiler can do things such as inlining the value.


text:
Accelerometer axis inputs driving three RGB LED strips - Trinket Pro 5V
I am looking to take the analogRead Value of the x, y and z axis (at pins 0, 2 and 4) and if it's a motion state, perform a rainbow, cylone and cascade LED sequences using Adafruit Neopixel library.
Using serial connection, I saw that x,y,z axis are read at values of approximately 300.
When I run the code it executed the three Neopixel sequences (redPin at pin 3, GreenPin at pin 5 and BluePin at pin 6) and then continues, even if there is no change of the accelerometer position.
What am I doing wrong?
I am using Arduino Trinket Pro 5V and working with the x-axis and RGB strip at pin 3 only to start.
Thank you for your help.
#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"

#define PIN1 3
#define LED_COUNT1 5
#define PIN2 5
#define LED_COUNT2 5
#define PIN3 6
#define LED_COUNT3 5

// Create an instance of the Adafruit_NeoPixel class called "leds".
// That'll be what we refer to from here on...
Adafruit_NeoPixel RedPin = Adafruit_NeoPixel(LED_COUNT1, PIN1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel GreenPin = Adafruit_NeoPixel(LED_COUNT2, PIN2, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel BluePin = Adafruit_NeoPixel(LED_COUNT3, PIN3, NEO_GRB + NEO_KHZ800);

const int sensorPinRed = A0;
const int sensorPinGreen = A2;
const int sensorPinBlue = A4;

int analogValue = 0;

void setup()
{

  RedPin.begin();  // Call this to start up the LED strip.
  //GreenPin.begin();
  //BluePin.begin();
  clearLEDs();   // This function, defined below, turns all LEDs off...
  RedPin.show();   // ...but the LEDs don't actually update until you call this.
  //GreenPin.show();
  //BluePin.show()}

void loop()
{
  do{
   analogValue = analogRead(sensorPinRed);
  // Ride the Rainbow Road
  for (int i=0; i<LED_COUNT1*10; i++)
  {
    rainbow(i);
    delay(100);  // Delay between rainbow slides
  }

  // Indigo cylon
  // Do a cylon (larson scanner) cycle 10 times
  for (int i=0; i<10; i++)
  {
    // cylon function: first param is color, second is time (in ms) between cycles
    cylon(INDIGO, 500);  // Indigo cylon eye!
  }

  // A light shower of spring green rain
  // This will run the cascade from top->bottom 20 times
  for (int i=0; i<20; i++)
  {
    // First parameter is the color, second is direction, third is ms between falls
    cascade(MEDIUMSPRINGGREEN, TOP_DOWN, 100);
  }
  } while (analogValue>300);
}

// Implements a little larson "cylon" sanner.
// This'll run one full cycle, down one way and back the other
void cylon(unsigned long color, byte wait)
{
  // weight determines how much lighter the outer "eye" colors are
  const byte weight = 4;
  // It'll be easier to decrement each of these colors individually
  // so we'll split them out of the 24-bit color value
  byte red = (color & 0xFF0000) >> 16;
  byte green = (color & 0x00FF00) >> 8;
  byte blue = (color & 0x0000FF);

  // Start at closest LED, and move to the outside
  for (int i=0; i<=LED_COUNT1-1; i++)
  {
    clearLEDs();
    RedPin.setPixelColor(i, red, green, blue);  // Set the bright middle eye
    // Now set two eyes to each side to get progressively dimmer
    for (int j=1; j<3; j++)
    {
      if (i-j >= 0)
        RedPin.setPixelColor(i-j, red/(weight*j), green/(weight*j), blue/(weight*j));
      if (i-j <= LED_COUNT1)
        RedPin.setPixelColor(i+j, red/(weight*j), green/(weight*j), blue/(weight*j));
    }
    RedPin.show();  // Turn the LEDs on
    delay(wait);  // Delay for visibility
  }

  // Now we go back to where we came. Do the same thing.
  for (int i=LED_COUNT1-2; i>=1; i--)
  {
    clearLEDs();
    RedPin.setPixelColor(i, red, green, blue);
    for (int j=1; j<3; j++)
    {
      if (i-j >= 0)
        RedPin.setPixelColor(i-j, red/(weight*j), green/(weight*j), blue/(weight*j));
      if (i-j <= LED_COUNT1)
        RedPin.setPixelColor(i+j, red/(weight*j), green/(weight*j), blue/(weight*j));
      }

    RedPin.show();
    delay(wait);
  }
}

// Cascades a single direction. One time.
void cascade(unsigned long color, byte direction, byte wait)
{
  if (direction == TOP_DOWN)
  {
    for (int i=0; i<LED_COUNT1; i++)
    {
      clearLEDs();  // Turn off all LEDs
      RedPin.setPixelColor(i, color);  // Set just this one
      RedPin.show();
      delay(wait);
    }
  }
  else
  {
    for (int i=LED_COUNT1-1; i>=0; i--)
    {
      clearLEDs();
      RedPin.setPixelColor(i, color);
      RedPin.show();
      delay(wait);
    }
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<LED_COUNT1; i++)
  {
    RedPin.setPixelColor(i, 0);
  }
}

// Prints a rainbow on the ENTIRE LED strip.
//  The rainbow begins at a specified position.
// ROY G BIV!
void rainbow(byte startPosition)
{
  // Need to scale our rainbow. We want a variety of colors, even if there
  // are just 10 or so pixels.
  int rainbowScale = 192 / LED_COUNT1;

  // Next we setup each pixel with the right color
  for (int i=0; i<LED_COUNT1; i++)
  {
    // There are 192 total colors we can get out of the rainbowOrder function.
    // It'll return a color between red->orange->green->...->violet for 0-191.
    RedPin.setPixelColor(i, rainbowOrder((rainbowScale * (i + startPosition)) % 192));
  }
  // Finally, actually turn the LEDs on:
  RedPin.show();
}

Have you tried printing analogValue in your loop to verify that it is behaving the way you expect?

It seems to me that you are coding to always display something on the LEDs:
  void loop()
  {
    do {
      analogValue = analogRead(sensorPinRed);
      // display stuff
    } while (analogValue > 300);
  }

Assuming that you want the LEDs off when analogValue is <= 300, you have the test in the wrong place. That always does the loop at least once. How about:
  void loop()
    {
    analogValue = analogRead(sensorPinRed);
    if (analogValue > 300)
      {
      // display stuff
      }
    else
      {
      clearLEDs();   // Turn all LEDs off...
      RedPin.show();
      BluePin.show();
      GreenPin.show();
      }
    }

Thanks to @nick-gammon for debugging my code.
I cleaned it up so below is the working sample. X-axis of the accelerometer is related to PWM pin 3 RGB LED strip, Y axis of pin 5 and Z axis to pin 6.
The LED sequence cascades once in spring green color in response to the tilt in direction.
#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"

#define PIN1 3
#define LED_COUNT1 5
#define PIN2 5
#define LED_COUNT2 5
#define PIN3 6
#define LED_COUNT3 5

// Create an instance of the Adafruit_NeoPixel class called "XPin", "YPin" and "ZPin".
// That'll be what we refer to from here on...
Adafruit_NeoPixel XPin = Adafruit_NeoPixel(LED_COUNT1, PIN1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel YPin = Adafruit_NeoPixel(LED_COUNT2, PIN2, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel ZPin = Adafruit_NeoPixel(LED_COUNT3, PIN3, NEO_GRB + NEO_KHZ800);

const int sensorPinX = A0;
const int sensorPinY = A2;
const int sensorPinZ = A4;

int analogValueX = 0;
int analogValueY = 0;
int analogValueZ = 0;

void setup()
{

  XPin.begin();  // Call this to start up the LED strip.
  YPin.begin();
  ZPin.begin();
  clearLEDs();   // This function, defined below, turns all LEDs off...

}

void loop()
{
   analogValueX = analogRead(sensorPinX);
   analogValueY = analogRead(sensorPinY);
   analogValueZ = analogRead(sensorPinZ);
   if ((analogValueX > 400) || (analogValueY > 400) || (analogValueZ > 400) )
   {

  // A light shower of spring green rain
  // This will run the cascade from top->bottom i times
  for (int i=0; i<1; i++)
  {
    // First parameter is the color, second is direction, third is ms between falls
    cascade(MEDIUMSPRINGGREEN, TOP_DOWN, 100);
  }
   }
   else
   {
     clearLEDs(); // Turn all LEDs off
   }
}

// Cascades a single direction. One time.
void cascade(unsigned long color, byte direction, byte wait)
{
  if (direction == TOP_DOWN)
  {
    for (int i=0; i<LED_COUNT1; i++)
    {
      clearLEDs();  // Turn off all LEDs
      XPin.setPixelColor(i, color);  // Set just this one
      XPin.show();
      delay(wait);
    }

    for (int i=0; i<LED_COUNT2; i++)
    {
      clearLEDs();  // Turn off all LEDs
      YPin.setPixelColor(i, color);  // Set just this one
      YPin.show();
      delay(wait);
    }
    for (int i=0; i<LED_COUNT3; i++)
    {
      clearLEDs();  // Turn off all LEDs
      ZPin.setPixelColor(i, color);  // Set just this one
      ZPin.show();
      delay(wait);
    }
  }
  else
  {
    for (int i=LED_COUNT1-1; i>=0; i--)
    {
      clearLEDs();
      XPin.setPixelColor(i, color);
      XPin.show();
      delay(wait);
    }

    for (int i=LED_COUNT2-1; i>=0; i--)
    {
      clearLEDs();
      YPin.setPixelColor(i, color);
      YPin.show();
      delay(wait);
    }

    for (int i=LED_COUNT3-1; i>=0; i--)
    {
      clearLEDs();
      ZPin.setPixelColor(i, color);
      ZPin.show();
      delay(wait);
    }
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<LED_COUNT1; i++)
  {
    XPin.setPixelColor(i, 0);
  }
  for (int i=0; i<LED_COUNT2; i++)
  {
    YPin.setPixelColor(i, 0);
  }
  for (int i=0; i<LED_COUNT3; i++)
  {
    ZPin.setPixelColor(i, 0);
  }
}


text:
Two voltage sources on the same circuit
I am looking to power a Trinket Pro 5V microcontroller using a 9V voltage source. I have logic running on this controller to gather the data from an accelerometer (powered off of the 5V pin on the controller) and output it to three strands of 21 RGB LEDs (https://www.adafruit.com/products/1655).
RGB LEDs cannot exceed a power source of 5V and after passing through the Trinket voltage regulator the 5V pin on the Trinket just does not have enough power for all three strands.
Please, advise on the appropriate hardware for this case. What is the maximum voltage that RGB LEDs can handle and how does the schematic look on the protoboard.
Thank you for your expertise.

Use a second 5V power source for the LEDs. And connect the grounds.

@Majenko, thank you, do you mean connect the microcontroller ground pin to 9V voltage source gnd pin to the 5V source gnd pin?

The MCU and 9V will already be connected. Just the 5V and MCU and/or 5V and 9V grounds need to be connected. It's exactly the same as powering a motor, or a relay, or other things from external power supplies.

First of all: 9V means that you are using a 9V "transistor" battery (like this), right?
If so it won't last very long: I suggest you to use a different approach (e.g. four AA batteries in series).
As for your question, I couldn't find the power consumption for these leds. Try to measure it yourself, setting the max brightness and white color. I think that, anyway, the max current for each LED should be 60mA (20mA for each color). This means that each strand absorbs 1.2A (quite a lot!).
This power requires you to use at least a switching regulator. I always used some small modules I found on ebay (they have a LM2596 IC, so just search LM2596 on ebay to find them). They are rated for 3A, so you should put at least two of them (1.2 * 3 strands = 3.6A > 3A).
The connections are quite straightforward: the board has four pins: IN+, IN-, OUT+ and OUT-. IN+ of all the modules go to the positive terminal of the battery, IN- and OUT- of all the modules go to the common ground node (negative terminal of trinket, battery and leds), OUT+ is the 5V regulated output. Oh, by the way, they are adjustable modules, so BEFORE ATTACHING THE LEDS use a multimeter to set the correct voltage (if you attach the leds without regulating the voltage you can destroy them).
Since you will have a lot of current left on the second module, you can power the trinket from there (so you will not waste a lot of power).
One last thought: 9V batteries usually have a capacity of around 600mAh; if you use one of them with the switching modules and drain 4A from the 5V your battery will last 0.6Ah / 4A * 9/5 = 0.27h = 16 minutes; if you switch to 4 AA batteries (around 2000mAh) it will last 2Ah / 4A * 6/5 = 0.6h = 36 minutes. More than double (calculations made rounding up the power drained by 21 leds set at max brightness and white color)

@frarigu87 could you recommend an optimal power source for the project?

@K.Nadkina It depends on 1) the leds usage, 2) the desired duration 3) the required size of the battery 4) the money you want to spend. Usually the best weight (or size) over energy ratio is with the lithium batteries (LiPo or LiIon). A 7.4V (2 cells, also called 2S) 5200mAh I found on ebay costs about 30€, is 165x60x35 mm and, at full brightness white, will last about 2 hours. The drawback is that you need an appropriate charger for these (you can also find small modules, but be sure they are for 2S batteries too). I suggest you to avoid 1S (3.7V) batteries, because you will need a step up

According to the link you supply you might either receive the WS2812 or the SK6812, datasheet on Ws2812 claims you can supply up to 7V , but this is still less than 9V , the SK6812 is lacking in max voltage but says 5v typical.
If you still want to use the 9V supply you will need a extra voltage regulator.
A little math: each pixel can max draw 60mA, if you have 21 of them we multiply and get 1260mA, thats 1.26 Amps but thats max values we might divide by two and still be relative safe. Let's not.  So we need a 1.26A source from 9V to 5V then we can calculate the power we need to dissipate. (9-5) x 1.26 = 5.04W of heat. Ok you need a regulator that can dissipate that kind of heat.
A 7805 regulator will not do,  you need a switching buck converter.
As to driving this on battery power I don't think alkaline will be able to deliver 1.3A (adding for the MCU) without loosing voltage to inner resistance, some rechargeable might. Lipo can deliver but at a different voltage that will need a new calculation of potential waste using linear regulation, or a buck regulator.  In my opinion the charging of lipos require special attention and are not my preference, but might be option here.

The question doesn't give any indication that only half the LEDs are likely to be on, or only at half power. Arbitrarily halving the current draw seems a little dangerous to me.

I second @MarkSmith; moreover as I wrote in my answer I think that they are 3 strands of 21 leds, not 21 total. Moreover, please, be precise. Currents are expressed in milliamperes (symbol: mA, not mah

@Mark Smith you are absolutely right. I'll correct my answer

@HansNeve, do you think using a 3.7V Lithium Polymer Battery @ 2000mAh would be enough and eliminate the need for a regulator? Would it power the Trinket and one LED Strand? Could another battery of that sort power the other 2 LED strands?

@K.Nadkina You could use one lipo for each strain to lessen the load yes, but be aware that there might not be cirquitry to stop theese lipos from beeing completely drained, which is a bad thing. and you will have to disconnect them to charge them.

@HansNeve Incorrect again: the LEDS should be powered at 5V, so 3.7V is out of specs. Read the provided datasheets...

@frarugi87 will using 3.7V at 2000mAh per strand not work at all? or just last less time than that of a 5V?

@K.Nadkina it will work fine.

@K.Nadkina Of course, USING A SWITCHING STEP UP CONVERTER, a 3.7V 2000mAh will last half of a 7.4V 2000mAh (using a switching step down converter). Usually I tend to prefer to lower the voltage instead of increasing it because of the less stress the components have to bear (5V 4A means 7.4V 2.7A or 3.7V 5.4A). Moreover the step up converter has a higher input ripple. And for my experience they are a bit more unstable than the step down ones. This said, a 3.7V 2000mAh at 4A will last about 20 minutes, but it will work


text:
Flash Esp-01 and Esp-12 using NodeMCU module
I am building a test IOT architecture. At the moment I do have a NodeMCU "Amica" V1 module (more will come) and some ESP-01. I have not yet tried to flash the ESP-01 because the MCU is just so user friendly, while buying 6 MCU is more pricey than .
I was wondering, if I do de-solder the ESP-12 from the NodeMCU and then connect a female receptacle for the ESP-01 to the now empty MCU breakout board, would i be able to flash the ESP-01 from the Arduino IDE?
Would it maintain the automatic Reset and Flash pulls (as on the stock ESP-12)?
Will it also work with a pogo-pin assembly to flash other ESP-07/12 ?
Approximate answers and thoughts are well accepted, thank you very much.

look it up, it's open source hardware: https://smartarduino.gitbooks.io/user-manual-for-esp-12e-devkit/content/schematics_for_esp-12e_devkit.html

I know this is an ancient question, but I think it could help somebody in the future to know you don't really need to desolder the package. You can pull the EN pin down to disable the onboard ESP and connect an external through the board's pins directly, here they have a guide: https://web.archive.org/web/20230605171634/https://www.instructables.com/3-Simple-Ways-of-Programming-an-ESP8266-12X-Module/

On this site there's a description of how to use a USB-serial adapter to flash a ESP-01 with the Arduino IDE. I'm not very familiar with the NodeMCU boards, but I imagine that they contain a USB-serial chip, and thus it is possible to desolder the ESP-12 and connect a ESP-01 (with cables or an adapter with pogo-pins) and program it that way. I'm not sure about the Reset/Flash pulls, but I imagine that it could be possible, study the pinouts for the ESP-12 and ESP-01 and circuitry for flashing (see the link). I did flash my ESP-01 this way, before I got other ESP8266 boards.
I would only do this operation if I was very handy with a soldering iron and the NodeMCU/ESP-12 was something that could go to waste if anything went wrong.
I think picking up a 3.3V LDO and USB-serial (3.3v!) breakout much easier, and more failproof, so that's what I'd recommend.