text:
Using ATtiny85, NRF24L01+, DHT2: can't get data from DHT22
I am trying to make a sensor that gets temperature and humidity values from a DHT22 and send it through NRF24L01+ to a Raspberry Pi 2 Model B.
To connect NRF24L01+ to ATtiny85 and to free two pins for the DHT22, I used this link.
There is a scheme of my sensor:

There is a photo of the test board with the sensor (sorry, it is very untidy, because I remade it many times before to fix the problem):

I program the ATtiny85 with Arduino IDE (with 8 MHz clock).
I used this library and radio communication is working perfectly (it can't be an error during the radio transmission).
Here is the code of my ATtiny85:
#include <DHT.h>
#include <RF24.h>

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object
DHT dht;          // Create instance of DHT22 module object

void setup() {
  // Set up the radio
  radio.begin();
  radio.openWritingPipe(currentNodeAddr);
  radio.stopListening();
  dht.setup(3); // Set up the sensor on PB3 pin
}

void loop() {
  // This DHT library can calculate the delay but it may be 2+ sec
  delay(dht.getMinimumSamplingPeriod());
  // Get values from DHT22
  data.temp = dht.getTemperature();
  data.hum = dht.getHumidity();
  radio.write(&data, sizeof(Data));  // Send data to the Raspberry
}

But I can't the get temperature and humidity values from the DHT22. I used a lot of different libraries for DHT22 (for example, github.com/ringerc/Arduino-DHT22, github.com/nethoncho/Arduino-DHT22, github.com/jscrane/DHT22, etc.) and none of them works (they return zeros, NAN, or, generally, timeout error). And it seems that the connection with the DHT22 is correct (there were connection errors and I fixed them). I tried to use a lot of DHT22 modules, so the problem can't be a defective module.
Yes, I put a 2 second (and more) delay in between read requests. Yes, I added a 10k resistor between pin 1 and 2 of the DHT22.
Now I am thinking that the libraries work fine, but may be free pins (PB3 or PB4) of ATtiny85 can't receive data for some reason.
Tell me please where may be an error or a bug? Thank you in advance! And also many thanks to authors of all links and repositories that I have mentioned here!
EDIT (in accordance with frarugi87's answer):
At first I have grounded 3 and 4 pins of the DHT22.
When I program ATtiny at the 1 MHz, values are sent every 2 seconds (as it should be), but when I program ATtiny at 8 MHz, values are sent every 16 seconds (is it correct?).
I used the suggested code to check the radio library and it seems it works pretty well (values are being incremented and sent):

After that I used the suggested library (RobTillaart/Arduino v. 0.1.21) and at first time it returned some strange values (humidity and the status were 0 and temperature was MAX_INT value), but when I have tried to get only status value as string, the library also has returned -2 (DHTLIB_ERROR_TIMEOUT). This time I program ATTiny at 8 MHz:

Also I tried to get values without NRF24L01+ through I2C connection between the ATtiny85 and the Raspberry Pi. Result was the same (DHTLIB_ERROR_TIMEOUT):

Maybe the problem is in timings of ATtiny85 or in the program process?
I used these links (1, 2, 3) to set up Arduino IDE on Raspbian.
Here is list of useful links for this project which I found to implement it (I hope the authors will not mind that I posted their links here):
Arduino/AVR DHT projects and libraries:

Arduino Wireless Weather Station
Mini weather station with Attiny85
Easy IoT weather station with multiple sensors
ATtiny84 & RFM12B wireless sensor node
DHT11 HUMIDITY & TEMPERATURE SENSOR MODULE
DHT22 running @ 8MHZ
DHT22 not working with 8mhz clockspeed?
Adafruit DHT Library and ATtiny85
Class for DHTxx sensors
An Arduino library for reading the DHT family of temperature and humidity sensors
Using a RHT03 (aliases: RHT-22, DHT22, AM2302) temperature/humidity sensor from Arduino
Arduino-library for DHT11/DHT22 sensors reading
Efficient DHT library for Arduino
Feuchtesensor AM2302/DHT22
7 Segment Digital Thermometer using ATtiny 85
Wiring up DHT humidity sensors
Attiny85 RF Transmitter to Arduino Uno Receiver
Arduino library for the DHT22 humidity and temperature sensor
Arduino library for DHT11DHT22, etc Temp & Humidity Sensors
A simplified DHT11/DHT22/AM2302 library for use with the Trinket/Gemma
Arduino library for the DHT22 humidity and temperature sensor
Arduino sketch code for reading RHT03 (also known as DHT22, RHT22, and AM2302) temperature/humidity sensor

Arduino/AVR nRF24L01 projects and libraries:

Optimized fork of nRF24L01 for Arduino and Raspberry
Optimized Network Layer for nRF24L01(+) Radios on Arduino and Raspberry Pi
nrf24l01+ control with 3 ATtiny85 pins
NRF24L01 real life range test
Optimized fork of nRF24L01 for Arduino and Raspberry Pi
NRF24L01 SIX CHANNELS TO ONE RECEIVER
Arduino attiny support files for nRF24L01 RF modules
ARDUINO + RASPBERRY PI Switching light with NRF24l01+

Programming the ATtiny85 from Raspberry-Pi:

Programming the ATtiny85 from Raspberry Pi
Arduino IDE Installation
Arduino for other Chips
Tiny AVR Programmer Hookup Guide
ATtiny85 with Arduino IDE and Gertboard
Setting up the Arduino IDE on Raspbian

Arduino/AVR FR433 libraries:

433Kit is a collection of code and documentation designed to assist you in the connection and usage of RF 433MHz transmit and receive modules to/with your Arduino and Rapberry Pi
Tiny AVR Programmer Hookup Guide

Troubleshooting:

Wrong reading value for DH22 & get stuck after running for a while
DHT22 Sensor - sync timeout

Did you try the examples coming with the DHT library? Just to check if the library is working... or if the DHT is faulty...

Do you have access to another Arduino? If you had an Uno or some other Arduino with a serial support it would make debugging easier.

@frarugi87 Thank you for the suggestion. I tried to run examples all these days (and also without the radio module) but nothing changed.

@dlu Unfortunately I have no such boards.

@Alexander ok, then if neither the examples (without modifications) work, probably the DHT is faulty. Do you have another one to test?

@frarugi87 Yes, I have a pack of 15 DHT22 modules. I tried to use almost all of them. I have read in many forums that this module requires careful timing to grab data. Maybe there is something wrong with it.

I added an answer with two sketches for you to try. Try them and then report back

Probably I don't have an answer... but... I need same identic project. What libraries for Arduino AND Raspberry PI are used here? I hope someone will respond me...

@sineverba I added some links to the question that I used for the project or that were helpful for me.

@Alexander fantastic! Thank you very much. One question, please: you don't have neither one Arduino, all right? And you can program the ATTiny85 from the PI simulating Arduino / loading sketchs with the PI, all right? This is my also another my trouble... Thank you

@sineverba That's right. In this project I only worked with ATtiny85. As you can see in the question and in articles of the "Programming the ATtiny85 from Raspberry-Pi:" section, with Raspberry Pi you can assemble a scheme for programming AVR microcontrollers, install Arduino IDE and program ATtiny in the same manner as Arduino. But look at the answer. You have to choose microcontroller speed carefully (thats why I asked this question). But I used pretty old software 8 month ago. Maybe for now situation is better. By the way, I also plan to continue the work on this project in this month.

@Alexander thank you. Last question. In 2nd imahe I see on the right the PI console sniffing data. Path in title "/home/examoles" etc. Do you remembre what exactly script from which libraries was? Thank you!

@sineverba I have added the final code for both ATtiny85 transmitter and Raspberry Pi receiver to my answer below.

@sineverba I have also added the Makefile code to compile Raspberry Pi receiver to the answer below.

@sineverba Also in the answer I wrote that I used the next libraries: RobTillaart/Arduino DHT11, 21, 22, 33 library, Arduino driver for nRF24L01 http://maniacbug.github.com/RF24

Thanks to Rob Tillaart, the autor of the Arduino DHT library suggested by @frarugi87 (also thank him), the problem has been solved (see this issue for more information).
In my case to fix the problem there is only needed to to set a specific value of DHTLIB_TIMEOUT by leaving the definition #define DHTLIB_TIMEOUT 1000 in the dht.h file of this library and commenting other definitions written next to it:
// #ifndef F_CPU
#define DHTLIB_TIMEOUT 1000 // should be approx. clock/40000
// #else
// #define DHTLIB_TIMEOUT (F_CPU/40000)
// #endif

The ATtiny is programmed on 8 MHz. The DHT22 is working at a voltage of 3.3V with a 3K3 resistor.
The cause of the problem may be the way I program the ATtiny85 with old version of Arduino IDE installed in the Raspberry Pi (see comments to the @frarugi87's answer).
Libraries used:

RobTillaart/Arduino DHT11, 21, 22, 33 library
Arduino driver for nRF24L01 http://maniacbug.github.com/RF24

Here is the final code of the ATtiny85 transmitter and the Raspberry Pi reseiver respectively (I took the most part of the code from different examples of RF24 libraries and DHT libraries! Excuse me, if the code is not tidy.).
NRF24Transmitter.ino:
#include <dht.h>
#include <RF24.h>

#define DHT22_PIN 3
#define LONG_DELAY_MS 900000

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  float temp;  // Temperature value
  float hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object
dht DHT;          // Create instance of DHT22 module object

void setup() {
  // Set up the radio
  radio.begin();
  radio.openWritingPipe(currentNodeAddr);
  radio.stopListening();
}

void loop() {

  unsigned long startMillis = millis();
  while (millis() - startMillis < LONG_DELAY_MS);

  do {
    data.status = DHT.read22(DHT22_PIN);
    data.temp = DHT.temperature;
    data.hum = DHT.humidity;

    if (data.status != DHTLIB_OK) {
      delay(1000);
    }

  } while(data.status != DHTLIB_OK);

  radio.write(&data, sizeof(Data));  // Send data to the Raspberry
}

Receiver.cpp:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

uint8_t addresses[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node"};

// Struct for sending measured data
struct Data
{
    float temp;  // Temperature value
    float hum;   // Humidity value
    int status;     // DHT22 module status
} data;

RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

int main(int argc, char** argv)
{
    uint8_t currentPipe = 1;
    data.temp = -888;
    data.hum = -888;

    printf("BEGIN: %d\n", (int)radio.begin());

    radio.setAutoAck(1);
    radio.setRetries(15,15);
//  radio.setDataRate(RF24_1MBPS);
//  radio.setPALevel(RF24_PA_MAX);
//  radio.setCRCLength(RF24_CRC_16);

    radio.openReadingPipe(1, addresses[0]);
    radio.openReadingPipe(2, addresses[1]);
    radio.openReadingPipe(3, addresses[2]);
    radio.openReadingPipe(4, addresses[3]);
    radio.openReadingPipe(5, addresses[4]);

    radio.startListening();

    radio.printDetails();

    sleep(1);

    cout << "Start!" << endl;

    while(true)
    {
        cout << "Waiting for data..." << endl;

        while (radio.available(&currentPipe))
        {
            cout << "Reading: " << addresses[currentPipe - 1] << "..." << endl;

            radio.read(&data, sizeof(Data));

            cout << "Temp: " << data.temp << endl;
            cout << "Hum: " << data.hum << endl;
            cout << "Status: " << data.status << endl;
        }

        sleep(1);
    }

    return 0;
}

Here is Makefile to compile the receiver.cpp:
#############################################################################
#
# Makefile for librf24 examples on Raspberry Pi
#
# License: GPL (General Public License)
# Author:  gnulnulf <arco@appeltaart.mine.nu>
# Date:    2013/02/07 (version 1.0)
#
# Description:
# ------------
# use make all and make install to install the examples
# You can change the install directory by editing the prefix line
#
prefix := /usr/local

# Detect the Raspberry Pi by the existence of the bcm_host.h file
BCMLOC=/opt/vc/include/bcm_host.h

ifneq ("$(wildcard $(BCMLOC))","")
# The recommended compiler flags for the Raspberry Pi
CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s
endif

# define all programs
#PROGRAMS = scanner pingtest gettingstarted
PROGRAMS = receiver #gettingstarted gettingstarted_call_response transfer pingpair_dyn test
SOURCES = ${PROGRAMS:=.cpp}

all: ${PROGRAMS}

${PROGRAMS}: ${SOURCES}
    g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@

clean:
    rm -rf $(PROGRAMS)

install: all
    receiver -d $(prefix) || mkdir $(prefix)
    receiver -d $(prefix)/bin || mkdir $(prefix)/bin
    for prog in $(PROGRAMS); do \
      install -m 0755 $$prog $(prefix)/bin; \
    done

.PHONY: install

Ok, let's troubleshoot it.
Try with the following sketch:
#include <RF24.h>

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object

void setup() {
    // Set up the radio
    radio.begin();
    radio.openWritingPipe(currentNodeAddr);
    radio.stopListening();
    data.temp = 0;
    data.hum = 1;
    data.status = 2;
}

void loop() {
    data.temp++;
    data.hum++;
    data.status++;
    radio.write(&data, sizeof(Data));
    delay(2000);
}

You should see a bunch of data being sent to the raspberry every second (you should see temp = 1, hum = 2, status = 3 then, after two seconds, temp = 2, hum = 3, status = 4 and so on. Of course you need something to display the data.
If there is some problems then it's the radio library fault, otherwise let's integrate the DHT22.
So, AFTER having tried the previous sketch and confirming that everything is working, download the library from here, install it and then use this sketch:
#include <RF24.h>
#include <dht.h>

dht DHT;

const byte DHT22_Pin = 3;

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object

void setup() {
    // Set up the radio
    radio.begin();
    radio.openWritingPipe(currentNodeAddr);
    radio.stopListening();
}

void loop() {
    data.status = DHT.read22(DHT22_Pin);
    data.temp = (int)DHT.humidity;
    data.hum = (int)DHT.temperature;

    radio.write(&data, sizeof(Data));

    delay(2000);
}

Now, instead of displaying increasing numbers, it should say the temperature, the humidity and, most important, the status:
 0 -> OK
-1 -> ERROR_CHECKSUM
-2 -> ERROR_TIMEOUT
-3 -> ERROR_CONNECT
-4 -> ERROR_ACK_L
-5 -> ERROR_ACK_H

Check if this works.
IMPORTANT NOTE: I read somewhere that sometimes the ground pin on the DHT is 3 instead of 4. Try grounding both pins if something does not work.

Thank you very much for your answer! I will describe results by editing the question.

Done! The question has been edited.

This "When I program ATtiny at the 1 MHz, values are sent every 2 seconds (as it should be), but when I program ATtiny at 8 MHz, values are sent every 16 seconds (is it correct?)." is absolutely not normal You should have experienced the opposite behavior. First of all I onticed you are using an old version of the Arduino IDE (1.0.1). Try updating to 1.6.x (instructions here if sudo apt-get upgrade does not find the version; you need to use latest raspbian version - jessie)

Then setup arduino 1.6.x to use the attiny85: see here how to do that, particularly "Adding Third Party Boards to the Arduino v1.6.4+ IDE" and I think you can use the recommended attiny85 board repository, but the second one (drazzy) is more updated; you can choose one. Then select the board from the list and try uploading again. With both 1MHz and 8MHz the 2seconds delay should remain 2 seconds delay

You are right, it is not normal. But this is all I could install and get to work on the Raspbian Wheezy. I will try it again later with your suggestion. By the way, a solution has been finally found. I will post it a little bit later in another answer. Thank you for your your help and for useful links!


text:
Does ATmega328 on Uno need to be burned?
I'm new to the Arduino world so please bear with me. I'm not sure whether the ATmega328 bootloader needs to be burned. What I'm reading is all that needs to be done is plug the board into the computer by USB cable. Then burning the 328 is also mentioned. I appreciate any help.

As mentioned, an Arduino style board usually comes with a bootloader in the chip.  You can also buy loose chips already programmed with a bootloader at a small price premium.  And you can use a working Arduino or similar board as an ISP programmer to burn the bootloader into a chip that doesn't have one, or has a different one that you want, or to directly program a sketch alone without a bootloader.

You've mentioned Arduino in your first sentence, but then refer to it as ATMega328 and the board. Is it an Arduino board or is it an ATMega Development board? Two similar but different things. I used several versions of ATMega boards since before Arduino was conceived. Those were the days :). For those you would need to burn your own, but anything with Arduino on it would already have it edit: why is it that right after I post the comment, I notice you specifically mention UNO in the title  It would be highly unlikely a UNO board (even a compatible one) would not have it already

If you bought an Arduino Uno the bootloader comes pre-programmed.
"The ATmega328 on the Uno comes preprogrammed with a bootloader that allows you to upload new code to it without the use of an external hardware programmer. It communicates using the original STK500 protocol (reference, C header files)." - from the oficial page.
Might want to take a look at this discussion if you're confused.

You only ever need to burn a bootloader if:

You are building your own "breadboard" Arduino
You have somehow erased the bootloader that is on your Arduino
You have replaced the original chip on the Arduino

The chip that came already inserted into the Arduino board already has the bootloader installed into it.

It depends. If you bought the arduino from most places, it will be already be burned. However, some less reputable sources might not burn it. If the LED on pin 13 blinks when you power on the arduino, that means the bootloader is installed.

It would be incredibly rare for an Arduino (even compatible Arduino) board not to have a bootloader installed. I've bought a couple early on that were compatible boards without realising it (I know better now), but they always worked "out of the box". Good point about the LED blinking, I would have tested just by plugging it in and trying to send a sketch to it, so good point right there. And welcome to SE Arduino! :)

I bought a pack of 15 arduino clones for a class, and roughly half of them had bootloaders. If they are from Arduino.cc they will likely come with the bootloader, but some clones don't.

source: Stack Exchange

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

sort: votes


text:
Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino
Intel Edison Kit for Arduino Hardware Guide instructs:
echo 28 > /sys/class/gpio/export
echo 27 > /sys/class/gpio/export
echo 204 > /sys/class/gpio/export
echo 205 > /sys/class/gpio/export
echo 236 > /sys/class/gpio/export
echo 237 > /sys/class/gpio/export
echo 14 > /sys/class/gpio/export
echo 165 > /sys/class/gpio/export
echo 212 > /sys/class/gpio/export
echo 213 > /sys/class/gpio/export
echo 214 > /sys/class/gpio/export
echo low > /sys/class/gpio/gpio214/direction
echo high > /sys/class/gpio/gpio204/direction
echo high > /sys/class/gpio/gpio205/direction
echo in > /sys/class/gpio/gpio14/direction
echo in > /sys/class/gpio/gpio165/direction
echo low > /sys/class/gpio/gpio236/direction
echo low > /sys/class/gpio/gpio237/direction
echo in > /sys/class/gpio/gpio212/direction
echo in > /sys/class/gpio/gpio213/direction
echo mode1 > /sys/kernel/debug/gpio_debug/gpio28/current_pinmux
echo mode1 > /sys/kernel/debug/gpio_debug/gpio27/current_pinmux
echo high > /sys/class/gpio/gpio214/direction

However line 3 already gives an error:
echo: write error: No such device

Any suggestions on how to enable I2C?

It was a strange problem which we were not able to resolve in an acceptable manner after all.
The problem disappeared after we re-flashed the device.

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


text:
Arduino Uno - Firmata/Serial Communication in Visual Studio C++
I need to pass std::vector <double> values from a C++ console program (written in Visual Studio 2015) running on a PC to Arduino in real-time using USB serial communication. Can anyone of you give any advice on how to implement Firmata or something similar into a C++ console application?
I googled everywhere and could not find a decent example for C++. Almost everything can be computed in console app, Arduino needs to work only with LCD display and beside that it can have StandardFirmata uploaded.

If you are willing to use python to write a simple scripts you can use Telemetry (See on github) to exchange the data to Pytelemetry. Using a technique called indexing you can send arrays and sparse arrays. The C implementation of the protocol doesn't support it out of the box but it's 2 lines of code to add to your embedded application. Let me know (I am the author)

Do you have an upst date on this issue?  I looking to compile the FIrmata test app in VIsual Studio 2017 in C++


text:
avrdude: stk500_rcv :programmer is not responding
I'm a newbee to Arduino programming and hoping someone can help me with this. These are the error messages.
avrdude: stk500_rcv() : programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10:not in sync:
Problem uploading to board.
I'm using a Arduino UNO clone on com port 3,the blink sketch is functioning. I get the mentioned error message on all sketches I have ran. Not sure what to do.

Are you running Arduino IDE, and get the message when you click upload?  What board model and speed is the IDE showing at its bottom right?  What programmer, in preferences?   Have you tried things suggested in 'Related' questions in sidebar?  Have you uploaded to any other boards?  Please answer the above by editing your question

And what do you mean by "the blink sketch is functioning" and "error message on all sketches"? Is the blink sketch working or not?

Yes the blink sketch works fine. In fact all the LED sketches work. I get the

Yes the blink sketch works fine, in fact all the LED sketches upload successfully. When I upload  any other sketches such as LCD, stepper and servo I get the mentioned errors.  Thanks for your help

try this site: https://github.com/Makeblock-official/Makeblock-USB-Driver/ , it works for me. This is a driver for arduino, and command for bash

I had a same problem with UNO R3 (CH340G) MEGA328P for Arduino UNO R3
On Ubuntu 14.04 I checked the whether the USB chip not recognized, but it looks ok:
~$ dmesg | tail -n 6

[ 3350.417900] usb 2-2: new full-speed USB device number 5 using xhci_hcd
[ 3350.546759] usb 2-2: New USB device found, idVendor=1a86, idProduct=7523
[ 3350.546763] usb 2-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[ 3350.546764] usb 2-2: Product: USB2.0-Serial
[ 3350.547255] ch341 2-2:1.0: ch341-uart converter detected
[ 3350.547996] usb 2-2: ch341-uart converter now attached to ttyUSB0

But the upload went wrong like this:
~$ avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -Uflash:w:/home/oliver/Arduino_Build/Blink/Blink.hex:i

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/oliver/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]
....

After reading bunch of articles 1, 2, 3, 4, 5, 6 it turned out my bad Chinese Arduino clones does not have bootloader installed on the Atmel microcontroller ship. To solve this problem you need a working Arduino and the clone Arduino we want to fix.
Walk trough who to burn the bootloader: http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/
Shortly: Burn the bootloader

You need a working Arduino
Connect the working Arduino with a usb to the computer
Upload Examples->ArduinoISP on working Arduino
Connect the wires from the working Arduino to the clone as follows:

Pin 10 goes to reset pin
Pin 11 -> 11, 12 -> 12, 13 -> 13
5v to 5v and ground to ground

Go to Tools->Board and select the chinese board that is not working. in my case it's an Arduino Uno.
Go to Tools->Programmer and select Arduino as ISP.
Go to Tools again and select "Burn Bootloader".
Your clone should work just fine now, but don't forget to restore Programmer (set back to ArduinoISP or AVRISP).

My clone board does not had integrated LED on 13 pin :) you need to connect it for Blinking test.

I assume that you're trying to upload the code with the Rx and Tx pins connected..
Try removing the Rx and Tx and then click the upload button in the IDE..
This happens because your computer communicates with the Arduino via Serial communication. The Rx and Tx pins also do communicate via Serial communication. An Arduino does not have the capability to handle two such communications simultaneously. So, it goes out of sync.. And that's how you get this error...

this has been such a headache! thank you!

Anytime @Ryan Loggerythm

You mentioned arduino uno clone, do you know what USB chip it's using and what chip you are uploading the sketches to?
The clone I have is very fussy and hangs up continuously. I have had luck once or twice with uploading the sketches. Depending on the chips on the board downloading the proper driver will help and selecting the proper chip under the board setting i.e. Atmega328 or atmega8 depending on the chip. Hope this helps as it worked for me.

I'm not familiar with Arduino Uno, but in case of a Nano switching to another Processor in the Tools menu of the Arduino IDE solved the problem for me. For my Nano the ATmega328P (Old Bootloader) is the one that works, maybe there is a similar option for Uno.
Steps and screenshot: https://gyorgybalassy.wordpress.com/2020/10/16/arduino-programmer-is-not-responding-not-in-sync-error/

authors: влад орехович

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


text:
Simple Speed question - Mapping PWM values
I am working on an Arduino project for school to power a 12V DC cooling fan.
I want to adjust the speed of the fan. The instructions say to set the motor pin at an equation of (0 to 9) * 10 + 150 to get a range of 150 to 240.
I need to write a mathematical equation but can not figure out what 150 to 240 means.  Is this voltage, resistance...?  Thanks for the help.

The analogWrite() function takes a value that is between 0 (fully off) and 255 (fully on).
Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

(150 / 255) * 100 = 58.8% on time
(240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive.  Let's call this value "i".  You want an output value, let's call it "o".
The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula.  0-9 is i, remember:

o = i × 10 + 150

If i is 0 then o = 0 × 10 + 150 = 0 + 150 = 150.
If i is 9 then o = 9 × 10 + 150 = 90 + 150 = 240.
As Ignacio mentions, the Arduino API has a map function which is meant to be used for this kind of thing;
o = map(i, 0, 9, 150, 240);

However: the map() function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.

Doesn't map just approximate with integer division instead of using floating-point?

Actually it looks like the current version does use long not float. I am sure an older iteratipn was float based. They probably changed it because it was too heavyweight. So yes, you can use map if you like, but since it is a generic function it will be less efficient anyway than doing the correct specific simple calculation.

They're the value to pass to analogWrite() in order to generate a PWM waveform with an appropriate duty cycle.
But don't bother writing your own algorithm, just use map().

He said he needs to write the equation

The map() function is the answer. It "rescales" the range of the data, using this formula:
(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

You input these five values:
map(value, fromLow, fromHigh, toLow, toHigh)

value is the X value you want to resize
fromLow and fromHigh is the range that X is currently in
toLow and toHigh is the range that you want to scale X to

The question wanted to know what the "150 to 240" means so, no, this isn't the answer.


text:
Peer to peer communication
Hello guys ,
             I want to perform a mesh network between 3-4 modules using ESP8266 . Any one have idea how to do it?

@Stewart Mayer, your code above (AP & ST) is work! Thanks in advance! Greeting from Indonesia

Stewart, I'm an ESP8266 newbie and have been working on this all day. I stumbled across this client/serve code and it worked first time! Thanks for writing and posting. Peter

Peer to Peer Example
Written by Stewart Meyer (engineer retired from the FAA).
This is first time that I have given an answer, hope you can read this:
Not only can the ESP8266 connect to a WiFi network and interact with the Internet, but it can also set up a network of its own, allowing other devices to connect directly to it. This example demonstrates how to turn the ESP8266 into an access point (AP) also called a server, and serve up data to any connected client also called a station.
Server (Access Point)
First we will look at the server:
/* Server
*  We write the server first because we need its IP address
*/

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

const char* ssid = "Meyer";       // ssid of server (Access Point (AP))
const char* password = "";        // password of server (Access Point (AP))
WiFiServer server(80);            //Service Port

int ledPin = 2; // GPIO2 of Server ESP8266

void setup()
{
    delay(1000);
    Serial.begin(115200);    // to use tools->serial monitor

    pinMode(ledPin, OUTPUT);   // set GPIO 2 as an output

    WiFi.mode(WIFI_AP_STA);  // Set WiFi to AP and station mode

    // Connect to the WiFi network
    Serial.println();
    Serial.print("Connecting to: "); Serial.println(ssid);
    WiFi.softAP(ssid, password);

    // Display the server address
    Serial.print("Connected, My address: ");
    Serial.print("http://");
    Serial.print(WiFi.softAPIP());
    Serial.println("/");

    // Tell the server to begin listening for incoming connections
    server.begin();
    Serial.println("Server listening for incoming connections");
}

void loop()
{
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client) // if not available, return
    {
        return;
    }

    // Wait until the client sends some data
    Serial.println();
    Serial.println("Client connected");
    while(!client.available())
    {
        delay(1);
    }

    // Read the request
    String request = client.readStringUntil('\r');
    Serial.print("Request = "); Serial.println(request);

    if (request.indexOf("/ON/") != -1)
    {
        digitalWrite(ledPin, LOW); // turn LED on
    }
    if (request.indexOf("/OFF/") != -1)
    {
        digitalWrite(ledPin, HIGH); // turn LED off
    }

    client.flush();
    Serial.println("Client disconnected");
}

Client (Station)
Next we will look at the client:
/*  Client
*   This client will turn the LED on or off every 5 seconds
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

const char* ssid = "Meyer";   // ssid of access point (Server)
const char* password = "";    // password of access point (Server)
int port = 80;                // port number

byte ip[]= {192,168,4,1};

int LEDstatus = 0;

WiFiClient client;  // Declare client

void setup()
{
    Serial.begin(115200);
    delay(10);

    WiFi.mode(WIFI_STA);  // set mode to station (client)

    // Connect to wiFi
    Serial.println(); Serial.println();
    Serial.println("CONNECTING TO WiFi");
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");  // print dots until connection
    }
    Serial.println();
    Serial.println("WiFi CONNECTED");
}

void loop()
{
    // Connect client to server
    Serial.println("CONNECTING CLIENT TO SERVER");

    if (client.connect(ip, port))
    {
        Serial.println("CONNECTED");
    }
    else
    {
        Serial.println("CONNECTION FAILED");
    }

    // Send message to control the LED
    if (LEDstatus == 0)
    {
        client.println("/OFF/");
        Serial.println("LED OFF");
        LEDstatus = 1;
    }
    else
    {
        client.println("/ON/");
        Serial.println("LED ON");
        LEDstatus = 0;
    }

    client.println();

    client.flush();

    delay(1);
    Serial.println("CLIENT DISCONNECTED");
    Serial.println();
    delay(5000); // delay 5 seconds
}

You can't, that's not how the esp8266 works.
The esp8266 is WiFi, so you will either need an access point or nominate one esp8266 module to act as an access point running in softap mode.

you can provide  the sample

sorry @girishkolte but... I never used an esp8266, so I'm a newbie. But if Majenko says "you need to run the esp8266 in softap mode" I go on google (if you don't know it, it's a search engine) and search "esp8266 softap". The VERY FIRST result already has an example. And the second one too. And I didn't go through all the others, but I assume that a lot of them already have. So stop waiting for others to do your work and search on your own! It's also faster, because you will get results instantly instead of waiting for other people to search them for you


text:
Generating a 38 KHz signal without timers
I am currently trying to generate a 38 KHz signal for my TSOP4838 (http://www.vishay.com/docs/82459/tsop48.pdf) with an ATtiny84A.
I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.
I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).
So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (micros(), millis() etc.) stopped working and prevented me from using my serial communication. I tried to change the code in wiring.c to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.
I am now stuck with two options I guess:
A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.
B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.
I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?
If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()

Sorry, but.... are you really using a microcontroller to generate a 38khz square wave and nothing more?

A 38kHz square wave at 50% duty cycle would be a transition running at 38x2=76kHz.  That is 1/76,000 = 0.000013158s, or 13.158µs.  That's quite a high accuracy to try and achieve with delays on a small chip like the 84A.
I assume you are running it at 8Mhz (internal calibrated RC oscillator) - that means each clock tick is 1/8000000=125ns long. so 13156ns would equate to 105.248 clock cycles. That can't happen, so the closest you would get is 105 clock cycles, which would be 13125ns, or 76.190kHz, or an end frequency of 38.095kHz.  So fairly close.
So now you need to create a tight loop that is exactly 105 clock cycles long including the toggling of the IO pin and the comparisons and branches for the loop.  For that you need to do some careful instruction cycle counting and work in assembly language.  Page 268 of the data sheet details the clock cycles used for each instruction.
The simplest (though most long winded) loop would be an OUT or SBR (depending on port) instruction (1 clock) to set the IO pin HIGH, then 104 NOPs (1 clock each), then an OUT or CBR to set it LOW (1 clock), then 102 NOPs (1 clock each), then an RJMP to go back to the start (2 clocks).  That is then a grand total of 210 clock cycles, or 1/(210*0.000000125) = 38.095kHz.
You could compress all the NOP instructions down into a tight loop themselves by setting a register to a pre-defined loop count value, decrement it each pass - repeat if it's not 0. That means even more careful instruction counting to get that loop to equal the 104 or 102 clock cycles needed for the precise timing.
However all that is pretty much academic, because the loop will keep being interrupted by your timer 0 interrupt and cause jitter in your output as the interrupt routine is being run instead of your IO pin driving loop.
If you don't need absolutely reliable timing anyway it might be easier (though far less accurate) to use the micros() function to find when 13µs have elapsed and do it all in C instead of assembly.  You will still need high speed direct port access rather than using digitalWrite() since digitalWrite() adds way too much overhead to be able to do that kind of timing reliably.  Something like:
uint32_t start = micros();
while(1) {
    if (micros() - start >= 13) {
        start = micros();
        PORTB ^= 1<<4; // toggle B4
    }
}

Note the use of while (1) there rather than relying on the loop() function repeating itself.  There is quite a large overhead in using the auto-repeating of loop() that can be avoided by looping within it with a while (1) like that.  Of course, anything else you want to happen repeatedly would have to be inside that while loop, and most likely would impact your output timing somewhat.
So a much better solution would be to use a timer, since that is what they are there for.  But fidding with timers breaks things like millis() and delay().  So the answer to that is don't use millis() and delay().  Instead create your own timing functions that are controlled by your own interrupt that does the pin IO - instead of relying on a system provided tick you create your own.  If your interrupt is firing every 13µs then add 13 to a global counter - that counter is then the number of microseconds that have passed.  When that count exceeds 1000 you subtract 1000 (don't zero it) and add 1 to a millisecond counter.  Now you have the equivalent to millis() in a global (remember to make it volatile) variable that you can use instead of millis().

Thanks for the detailed answer ! I am using amtel studio with a cire that i compiled myself and therefore i am already not using loop or setup methods like i a arduino environment. I guess i'll try again to get the timer to do what i want. The bad thing is that i need to alter the TinyDebugSerial Class too because it seems to use the arduino milli functions...

I am using an arduino nano as frequence generator and it generated me a stable frequency with an error less than 0,1kHz. But the TSOP382 stops receiving after 200ms.  I have disabled all interrupts and made the on and off sequence equal.

It would be much easier to use a dedicated IC such as a 555 or a 556. I built such a system based on these circuits IR Bream Break Detector

The R/C combination used there yields 41 kHz. Better suitable would be 22 nF / 860 Ω (38.054 kHz) or 47 nF / 400 Ω (38.297 kHz).

Edit: As two resistors are necessary for the astable version, use Ra = 1.2 kΩ, Rb = 12 kΩ and C = 1.5 nF, yielding 38.095 kHz. Ra/Rb/C see NE555 Data Sheet.

Several approaches are possible, some of which, but far from all, have been listed in previous answers.  In following, I assume that by “use it as a light barrier” you mean that the TSOP4838 will be part of an object-intrusion detection system, rather than for transmitting data.  As a consequence, some jitter and/or inaccuracy is acceptable.  Note, all of the following methods assume that Arduino core code has set up timer 0 to support ordinary micros() and millis() calls.
Approach 1:  Compute or calibrate a simple loop:  In setup(), run a series of tests that find a value k to minimize error, via C code equivalent to the following Python:
for k in plausibleRange():
  err = genBurst19(k)
  if err < bestErr:
    bestErr = err
    bestK = k

where genBurst19() is like the following:
def genBurst19(k):
  t1=micros()
  for i in range(38):
    setPortBit(i&1)
    for j in range(k):
      nop
  t2=micros()
  return abs(t2-t1-500)

In other words, genBurst19() sends a burst of 19 cycles, which at 38 KHz should take 500 microseconds.  It returns a measure of error to the caller.
After finding bestK, you can subsequently use it as a limit for other delay loops, or could just use repeated calls to genBurst19(bestK) whenever you want to generate some "38KHz".
Note, you might wish to try some minor variations, such as adding a second or third nop in the inner delay loop, or generating some higher multiple of 19 cycles.  While a delay loop containing a single nop (or no nop at all, just an empty loop) has finer resolution than a loop with multiple nops, it may happen (depending on loop code) that a smaller error occurs with more.  [But also see Approach 3 regarding fine tuning.]
Summary:  This method is easy to use, has low jitter, but is limited in the accuracy it can attain.
Approach 2:  Use a method analogous to Bresenham's to produce a signal with high-accuracy period, on the average, but with more jitter than Approach 1.  Bresenham's algorithm tries to draw a straight line, on an x-y grid of pixels; you are trying to draw a straight line, on a time-vs-cycles grid.
In this method, you keep track of how many microseconds total should have elapsed, and when you fall too far behind, issue a delay with k-1 instead of k, to catch up; or if too far ahead, with k+1, to drop back.  See my answer to stackoverflow 8113883 for a little more re Bresenham's method, in the line drawing context.
Summary:  By applying Bresenham's method, you can get the average frequency as close as you like (when averaged over a few milliseconds).
Approach 3:  This is more of a fillip than a whole approach.  It modifies Approach 1 by adding the following C code before the for j in range(k): nop loop.  It also needs a second parameter, l.
switch (l) {
  case 9: nop;
  case 8: nop;
  case 7: nop;
  case 6: nop;
  case 5: nop;
  case 4: nop;
  case 3: nop;
  case 2: nop;
  case 1: nop;
  case 0: ;
}

To use this approach, first find the best k using a series of calls like err = genBurst19(k,5).  Then find the best l via err = genBurst19(bestK,l) for l from 0 to 9.  [Note, a number smaller than 9 can be used in the above, if the for j in range(k): nop loop uses fewer cycles.]
Summary: This fillip can tune genBurst19() closer to single-nop accuracy.

I just built an NE555 based circuit for 38 kHz. Sender is a 950 nm IR diode, receiver is said TSOP4838. According to the NE555 Data Sheet, the frequency in astable mode is approximately
f ≈ 1.44 / (C (RA + 2 RB) )

Using values of RA = 1.8 kΩ, RB = 18 kΩ, C = 1 nF, the NE555 should generate a frequency of 38.095 kHz. Using these values, my circuit generated 34 kHz with some small changes of a few 100 Hz when using different resistors/capacitors (due to tolerance), but it came nowhere close to 38 kHz. This is probably because the frequency formula is an approximation. The easiest fix is probably to put a variable capacitor in parallel to C and use it for fine tuning, or a variable resistor to RB.
This may not be necessary in every case as the TSOP48xx uses a band pass filter, and 34 kHz are still recognized, only at lower responsivity. Note that this IR receiver (as well as others) have some limitations on pulse length, so you cannot constantly send 38 kHz but only for up to 70/f, which is around 1.8 ms. After that, the TSOP output switches off again, probably because the internal threshold is raised.

Measurements
Some measurements from a logic analyzer (PulseView). This is from the above NE555 circuit which should yield 38 kHz.

I used an AND IC (74HCT08) to modulate a signal, generated by an Arduino, on top of the 38 kHz carrier. Sampling rate is 12 MHz. The probes measure:

D0: TSOP4838 output signal
D1: IR signal (carrier AND signal)
D2: Arduino signal
D3: 38 kHz carrier from NE555


text:
Read RC receiver channels using Interrupt instead of PulseIn
I am designing my own quadcopter control algorithm, whereby I currently read 4 RC receiver channels using PulseIn on each loop in the following manner:
ch1_raw = pulseIn(rcPin1, HIGH, 25000);

In other words, ch1_raw contains the length of a HIGH pulse in microseconds.
I now want to avoid PulseIn in the interest of speed and instead achieve the same using interrupt.
I have looked at http://playground.arduino.cc/Main/PinChangeIntExample and I am aware that other similar questions have been asked (e.g. How to read RC receiver channels without using pulsein() command with arduino and Is PulseIn fast enough for Quadcopter?), but I don't understand how to implement interrupt to give me the correct ch1_raw value on each loop.
Can somebody help me? (I'm new to Arduino, so go easy on me please!) Thanks!

Edit:
So far I have tried to implement the following:
#include <PinChangeInt.h>

unsigned long pulsestart, pulsewidth;

int rcPin1 = A0;

void setup(){

  pinMode(rcPin1, INPUT);

  Serial.begin(9600);

  PCintPort::attachInterrupt(rcPin1, counttime,RISING);
  PCintPort::attachInterrupt(rcPin1, subtracttime,FALLING);

}

void loop(){

  Serial.print("  pulsewidth: ");
  Serial.println(pulsewidth);

}

void counttime()
{
  pulsestart = micros();
}

void subtracttime()
{
  pulsewidth = micros()- pulsestart;
}

Edit 2:
(Somewhat) successful implementation so far, using EnableInterrupt.h instead. It seems that FALLING is being detected, but not RISING.
#include <EnableInterrupt.h>

#define rcPin1 10

volatile uint16_t pulsestart=0;
volatile uint16_t pulsewidth=0;
//volatile unsigned long pulsestart=0;
//volatile unsigned long pulsewidth=0;
volatile uint16_t risingcount=0;
volatile uint16_t fallingcount=0;

void counttime()
{
  pulsestart = micros();
  risingcount++;
}
void subtracttime()
{
  pulsewidth = micros()- pulsestart;
  fallingcount++;
}

void setup() {
  Serial.begin(9600);
  pinMode(rcPin1, INPUT_PULLUP);
  enableInterrupt(rcPin1, counttime, RISING);
  enableInterrupt(rcPin1, subtracttime, FALLING);
}

void loop() {
  //delay(1000);
  Serial.print("risingcount: ");
  Serial.print(risingcount);
  Serial.print(" fallingcount: ");
  Serial.println(fallingcount);
  //Serial.print("pulsewidth: ");
  //Serial.println(pulsewidth);
}

For some reason, this code posted above does not work on the mega 2560 and only works on the uno. Please let me know if you can find out why.

Regarding the question, “Does PinChangeInt only work on digital pins?”, note that PCI's work on all the digital pins of an ATmega328, and on the first six analog pins.  (32-pin '328s have eight analog pins, A0-A7; 28-pin '328s only six, A0-A5.)
Regarding the problem symptom that “pulsewidth just seems to increase continuously”, that could happen if for some reason rising edges aren't processed.  To debug, add a couple more volative byte variables, say nrises and nfalls; increment each of them in the appropriate interrupt handler; and report their values from time to time.
Regarding your #include <PinChangeInt.h> statement, note that PinChangeInt.h is deprecated (as of 3 April 2015).  Consider using EnableInterrupt.h instead.
It's possible you'll resolve your problem while changing libraries.  If so, fine.  If not, or if that library's performance isn't adequate, consider changing over to handling the  pin change interrupts more directly.  The ISR in the following sketch shown below runs several times faster than code that uses PinChangeInt or EnableInterrupt library calls.
[Edit: This edit encloses the ISR in a sketch that compiles.  The code previously shown was missing two array length specifications.  This code was tested with a rotary encoder attached to A2, A3, with A0 and A1 grounded; an output sample (using an Arduino Nano) follows the code.]
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

The code shown above uses Streaming.h, a contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, either install it via Streaming5.zip from arduiniana.org or manually translate the Serial << ... statement to Serial.print statements.
A sample of the sketch's output on serial monitor:
t=35773 0 0 14196 13456 4
t=35775 0 0 14196 13456 3
t=35778 0 0 14196 5748 4
t=35781 0 0 5244 5748 3
t=35783 0 0 5244 5748 4
t=35785 0 0 5244 5748 3
t=35786 0 0 5244 28 12
t=35788 0 0 3024 28 3
t=35789 0 0 3024 28 4
t=35792 0 0 3024 28 3
t=35796 0 0 3024 6396 4
t=35802 0 0 9316 6396 3
t=35809 0 0 9316 6396 4

In the output above, the two 0's are from A0, A1 being grounded and not changing.  The next two numbers are from the DT and CLK lines of a KY-040 rotary encoder, which toggle alternately to encode step-direction.  They should represent on-times in microseconds, and are always multiples of 4 because micros() reports multiples of 4.
The last number is the number of times the ISR's change-checking loop ran since loop()'s previous print.  An A2 change will show a count of 3 or more, and an A3 change 4 or more.  Cases where times are the same may represent contact bounces shorter than the ISR's service time; ie, several falling edges in a row might be detected, or several rising edges.  A storage scope or logic analyzer probably is necessary for finding out exactly what happens.

Many thanks! So I have implemented nrises and nfalls as you suggested; and I have also tried to run the code here: http://playground.arduino.cc/Main/PinChangeIntExample - I have tried both on several different pins. The result is always the same: nrises and nfalls stay on 0, i.e. it seems that indeed the rising/falling edges are not being processed.

I have also tried the code you provide above, which looks great for my application, since speed is of the essence. I am having some trouble implementing it though. Right now, I am getting a compiling error on "rcRises[channel] = now;": "invalid types 'volatile long unsigned int[byte]' for array subscript

I have now been somewhat successful using EnableInterrupt.h instead (see edit 2 above). When attaching a simple switch between the rcPin1 and ground, I have managed to narrow down the problem to FALLING being detected (fallingcount increases each time I press/depress the switch) but not RISING (rising count stays at 0). This also occurs when attaching the RC receiver instead of the switch.

Does anybody know why this would be? and how I can resolve this issue? Thanks!

Add [4] before ; in  declaration of rcTimes, and similarly for rcRises.  See edit.

Brilliant! It works perfectly, and very fast. I am now able to run my complete quadcopter control loop (including inputs from gyro and accelerometer, outputs to ESCs, etc. not shown here) at ~200 Hz, whereas before (using PulseIn) the fastest I could achieve was ~12 Hz. BIG difference! Thanks so much.

Are you aware there is a library that does this? https://github.com/jantje/libraries/tree/master/RCLib

@jantje, I wasn't aware of that library.  Thanks for mentioning it!  Note, the example Maga6ChanelsA8_A13.ino includes PinChangeInt.h which
is deprecated (see EnableInterrupt.h instead). Both of PinChangeInt.h
and EnableInterrupt.h are slow -- they do a bunch of extraneous
processing the code shown above avoids.

Thanks for the feedback.
Note that the library only uses pinchange int if you want to use pins that do not support pin interrupts by hardware.

Interrupts don't obey, or even understand the concept of, the "loop" paradigm.
An interrupt fires when it needs to fire, and if you're reading a PWM signal then that means it's firing hundreds of times a second.
As long as your interrupt is updating a variable that can be read from within the loop, and you ensure that the variable doesn't get updated during your reading of it (Google: Critical Sections) then you will always have the most up to date value at your fingertips whenever you need it.
As for the interrupt itself, that's very straight forward - you just need to recognise if it's a rising or falling edge:

If rising edge: record the timestamp (micros()).
If falling edge: Subtract the recorded timestamp from the current micros() and store in the global variable.

Actually the repetition rate for a channel is traditionally around 50hz, meaning the loop will probably be running faster than the data source.  However the channels are usually time multiplexed, so if downstream of a demux reading individual servo leads, we might say time striped.

50 Hz = 100 edges per second. That counts as hundreds to me ;)

Many thanks! That's a lot more clear already. I have edited my question to show what I have tried to implement so far. However, it is not quite right yet. "pulsewidth" just seems to increase continuously and does not respond to any change in RC transmitter input. Can you see what I have done wrong?

Pin A0 is an analogue pin. Does PinChangeInt only work on digital pins?

Make your interrupt variables volatile.

ok I've done that (simply by putting "volatile" in front of the "unsigned long"). but still the same symptoms

authors: Γιωργος Βεζυρης


text:
LM35 and Character LCD
I have an arduino pro mini and I have attached a 16x2 character LCD and an LM35 analog temperature sensor. When I upload a sketch using only the sensor and send the readings to serial monitor, the readings are OK. When I upload a sketch that displays the readings to the LCD the readings are about 130°C in room temperature. Where is the problem and how can I solve it. Thanks in advance
Code with lcd:
#include <LiquidCrystal.h>
byte smiley[8] = {
  B00000,
  B01110,
  B01010,
  B01110,
  B00000,
  B00000,
  B00000,
};
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.createChar(0, smiley);
  lcd.begin(16, 2);
  analogReference(INTERNAL);
  // Print a message to the LCD.
  lcd.print(analogRead(0)/1024.0 * 500);
  lcd.write(byte(0));
  lcd.print("C");
  lcd.setCursor(0, 2);
  lcd.print("21");
  lcd.write(byte(0));
  lcd.print("C");

}

void loop() {
  // Turn off the cursor:
  lcd.print((analogRead(0)/1024.0)*500);
  lcd.write(byte(0));
  lcd.print("C");
  lcd.setCursor(0, 2);
  delay(5000);
  lcd.clear();
}

Only sensor code:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(analogRead(0)/1024.0*500);
  delay(500);
}

Adding your code would be helpful.

I think adding code is essential...

I just added it sorry for the delay.

Firstly you do not keep your code consistent between you temperature test and your LCD test code. The problem lies in your use of the internal analog reference, that reference is 1.1V and that is giving you 130°C.
Temp = 260*0.5= 130
The 260 is the ADC reading worked back from the 130°C you gave
To use Internal reference-
Internal ref = 1.1÷1024=0.001074219
That multiplied by one hundred to account for the mV reading of the lm35 gives 0.107 that will give you the correct temp when using the internal reference
Analog reference from the arduino site.
If you want to use the analog reading *0.5 comment out the analogReference()


text:
Arduino Simple Task - sweeping a buzzer and led, not working as expected

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

UPDATE: IT seems that there is a problem using pin 11 and 13 together but if I use a different pwm pin like pin 5. It's okay. I'm guessing that the timers used at pin 11 is connected to tone() but not sure...
I’ve encountered a weird problem with an Arduino with this simple task. It involves just a buzzer and LED and a very simple custom library that I made.
I wanted the buzzer to sweep back and forth with a specified frequency range (f1, f2), the led will also display a specific brightness (0, 50) based on the frequency being played.
The buzzer works perfectly on its own, and also the LED, but when you put them together, it malfunctions.
A more detailed explanation can be found here: https://tilarduino.wordpress.com/2015/11/27/weird-arduino-problem-buzzer-led-brightness/
And i've included all the files i've used here: https://gist.github.com/mithi/09ae419a3c7eba285221
Using this code below, commenting out line 19 with line 18 uncommented-out will make the buzzer work, and commenting out line 19 with line 18 back in will make the led work as expected. But together, the code malfunctions. buzzer is attached to pin 13 and led is attached to pin 11.
#include "SimplestLibrary.h"

Sweeper sweeper;
Buzzer buzzer;
AnalogLED led;

int f1 = 3000;
int f2 = 4500;
int f = 0;

void setup() {
    sweeper.New(f1, f2, BACKANDFORTH);
    buzzer.New(13);
    led.New(11);
}

void loop() {
    f = sweeper.Update(1);
    buzzer.Play(f, 4, 2);
    led.NewBrightness(map(f, f1, f2, 0, 50));
    delay(1);
}

From Arduino.cc:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

Simple solution is to use a PWM that isn't an output from Timer2 :
Timer      OCxA pin    OCxB pin
  0           6        5
  1           9        10
  2           11       3


text:
Unable to read any SMS's other than the first SMS using SIM908 shield
I'm using two SIM908 shields to communicate with each other. One of the shields will be connected to a sensor and it should send values contentiously to the second SIM908 (receiver). I'm facing a problem on the receiver side, I'm only able to receive the first SMS and when sending a new SMS it displays the older one.
The code that I'm using is from (cooking-hacks.com) where I bought the shield. In the original code the instructions were in void setup function so I  moved them to void loop function to keep checking for new SMS and print any received values. I also made other minor changes. Here is the code
int8_t answer;
int x;
int onModulePin= 2;
char aux_string[30];
char SMS[200];
float fSMS;
char data[20];

void setup() {
  pinMode(onModulePin, OUTPUT);
  Serial.begin(115200);
  Serial.println("Starting...");
  power_on();
}

void loop() {
  Serial.println("Setting SMS mode...");
  sendATcommand("AT+CMGF=1", "OK", 1000);
  // sets the SMS mode to text
  sendATcommand("AT+CPMS=\"SM\",\"SM\",\"SM\"", "OK", 1000);
  // selects the memory
  answer = sendATcommand("AT+CMGR=1", "+CMGR:", 2000);
  // reads the first SMS (since all other messages are deleted from previous delete statement)
  if (answer == 1) {
    answer = 0;
    while(Serial.available() == 0);
    // this loop reads the data of the SMS
    do {
      // if there are data in the UART input buffer, reads it and checks for the answer
      if(Serial.available() > 0) {
        SMS[x] = Serial.read();
        x++;
        // check if the desired answer (OK) is in the response of the module
        if (strstr(SMS, "OK") != NULL) {
          answer = 1;
        }
      }
    }while(answer == 0);
    // Waits for the answer with timeout
    SMS[x] = '\0';
    /*  strtok(SMS, ",");
    strtok(NULL, ",");
    strtok(NULL, ",");
    strtok(NULL, "\n");
    strcpy(data,strtok(NULL, ""));*/
    Serial.println(SMS);
    //Serial.println(data);
    /*    fSMS= atof (data);
    Serial.println(fSMS, 5);*/
  } else {
    Serial.print("error ");
    Serial.println(answer, DEC);
  }
  Serial.println("AT+CMGDA= \"DEL ALL\"");
  //delete all messages from SIM card
  delay(5000);
}

void power_on() {
  uint8_t answer=0;
  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0) {
    // power on pulse
    digitalWrite(onModulePin,HIGH);
    delay(3000);
    digitalWrite(onModulePin,LOW);
    // waits for an answer from the module
    while(answer == 0){
      // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
    }
  }
}

int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout) {
  uint8_t x=0,  answer=0;
  char response[100];
  unsigned long previous;
  memset(response, '\0', 100);
  // Initialice the string
  delay(100);
  while( Serial.available() > 0) Serial.read();
  // Clean the input buffer
  Serial.println(ATcommand);
  // Send the AT command
  x = 0;
  previous = millis();
  // this loop waits for the answer
  do {
    // if there are data in the UART input buffer, reads it and checks for the answer
    if(Serial.available() != 0) {
      response[x] = Serial.read();
      x++;
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer) != NULL) {
        answer = 1;
      }
    }
    // Waits for the asnwer with time out
  } while((answer == 0) && ((millis() - previous) < timeout));
  return answer;
}

Did you get an answer to this? Looking to find solution to similar problem.
It gets stuck at the first AT command it encounters. Is there any special library that needs to be included? Thanks


text:
Better way than exit(0)?
The following code does what I need it to do (when a start switch is on and door switch is off - a warning light flashes. When the start switch and door switch are both on - a valve opens to allow water in for 2 seconds). I need the light to flash until the door is HIGH too at which point the valve program runs once.  The only way I have to get out of this is to use exit(0). Is there a better way to do this? Ideally, I would like to stay away from anything too Boolean! Thank you.
int start = 2;
int door = 3;
int light = 8;
int valve = 9;
int counter = 0;

void setup() {
  pinMode(start,INPUT);
  pinMode(door,INPUT);
  pinMode(light,OUTPUT);
  pinMode(valve,OUTPUT);
}

void loop() {
  if(digitalRead(start)==HIGH && digitalRead(door)==HIGH) {
    digitalWrite(valve, HIGH);
    delay(2000);
    digitalWrite(valve,LOW);
    exit(0);
    //breaks out of loop. Arduino then needs reset.
  }

  if (digitalRead(start)==HIGH && digitalRead(door)==LOW) {
    digitalWrite(light,HIGH);
    delay(500);
    digitalWrite(light,LOW);
    delay(500);
  }
}

I don't really see what the exit(0) does here. If the door and start buttons remain pressed, the valve will go open for 2 seconds, then close for a while, but then open again for 2 seconds, etc. The only thing exit(0) does is create a bit of a delay. So replacing exit(0), with delay(3000) will do about the same thing. I think want you want is to remember that the valve has already been opened, on not open it again while both button are being pressed.

A better way to stop execution?  Some trap the operation in an endless loop with a while(1){}

I think the infinite loop is the best way.  I have to teach this to High School kids who will only do a small part of programming as part of a course.  I am trying to find Arduino solutions for questions that were originally designed for PBASIC (picaxe). There are a lot of questions which need the code to run once - and I need to restrict the commands to for, while, if....else commands ideally (in BASIC they would have used if/then, for/next and subroutines and that would be enough).

What you made a mistake is instead of using "if"(first one) you had to use "while".  And use the "if" to break out of the "while" using a "break" , what you have done is really a bad practice.

What you need to do is learn what a finite state machine (FSM) is.
An FSM is a way of having the Arduino in one of a finite number of states, such as "light flashing", or "letting water in", etc.
I have written a reasonable (IMHO) tutorial here: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


text:
Arduino Nano - programmer is not responding
I cannot seem to upload the simple blink program to my Arduino Nano. I keep getting the message:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

What I have tried already with a lot of suggestions on Google. I have tried it on both a Windows 7 & 8 machine and with 2 different Nano's:

Set my Board to Arduino Nano
Set my Processor to ATmega168
Set my port to COM1
On windows 8 turned off driver signature
Installed the FTDI Driver
Checked my drivers in control panel

USB controllers says USB Serial Converter
USB Serial port says USB Serial Port (COM1)

Rebooted a Lot!

When I plugin the nano to the USB it starts blinking the L led 180 times a minute. When I start uploading, L blinks at about 80-100 times a minute, blinks the rx and then start blinking the L led fast again.

For me the problem was the selected "processor" type.
I had to change it to 328p (old bootloader).
Also, raise the IDE's verbosity, in order to have a nice progress bar when loading the sketch.
My specs:

OS: Linux Mint 18.3
Linux kernel: 4.13.0-37-generic
Arduino IDE: v1.8.5
board: the cheap and common Nano Chinese clone
USB to serial chip: CH340

If it's a new nano is probably the new version which has the 328 processor. Try switching to that.
Also does your computer make the windows "I just plugged something in" sound when you connect? Is the driver recognized?
Try this instead:
Set Board to Arduino Nano
Set Processor to ATmega328
Set port to COM2 or any other device if recognized. Test to see if the Com1 stays if you unplug it. Try other usb ports as well.


text:
Arduino with DS18b20 and ENC28J60 to thingspeak
Can anyone help me to make this work? I have been trying for a couple of days to make this work, but no luck. I use a DS18b20 Temperature sensor and an ENC28J60 Ethernet module. The last code that I find like close to work is:
/*
| Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
| ENC28J60 chip.
| Based on the Ethercard example from www.jeelabs.org
| Phil Grant Jan 2014
*/
#include <EtherCard.h>
// change these settings to match your own setup
#define APIKEY  "xxxx"

//DHT Setup
//#include "DHT.h"
//#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
//DHT dht(DHTPIN, DHTTYPE);

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0x12,0x11,0x22,0x12,0x21,0x11 };
char website[] = "api.thingspeak.com";
byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

void setup () {
Serial.begin(57600);
//dht.begin(); //Initializate DHT
  Serial.println("\n[webClient]");
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");
  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());
  if (millis() > timer) {
    timer = millis() + 60000; //Transmit every minute
    delay(2000);  // Wait a few seconds between measurements.
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  char h_buffer[10];
  String Hstring = dtostrf(h,0,5,h_buffer);
  //Convert Humidity value to String
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  //float f = dht.readTemperature(true);
  char t_buffer[10];
  String Tstring = dtostrf(t,0,5,t_buffer);
  //Convert Temperature value to String
  byte sd = stash.create();
  stash.print("field1=");
  stash.println(Hstring);
  stash.print("&field2=");
  stash.println(Tstring);
  stash.save();
  // generate the header with payload - note that the stash size is used,
  // and that a "stash descriptor" is passed in as argument using "$H"
  Stash::prepare(PSTR(
    "POST /update HTTP/1.1" "\r\n"
    "Host: $F" "\r\n"
    "Connection: close" "\r\n"
    "X-THINGSPEAKAPIKEY: $F" "\r\n"
    "Content-Type: application/x-www-form-urlencoded" "\r\n"
    "Content-Length: $D" "\r\n"
    "\r\n"
    "$H"),
    website, PSTR(APIKEY), stash.size(), sd);
    // send the packet - this also releases all stash buffers once done
    ether.tcpSend();
  }
}

But on the serial monitor I get this message:

[webClient]
IP:  192.168.88.252
GW:  192.168.88.1
DNS: 8.8.8.8
DNS failed
SRV: 0.0.0.0

I have try all of this network configurations and I am sure that arduino have access to internet from my home router. I can ping arduino IP address from other computers in my network and all computers have access to Internet from same router and same subnet with same DNS.
Any more ideas?

But on serial monitor I get msg: [webClient] IP: 192.168.88.252 GW: 192.168.88.1 DNS: 8.8.8.8 DNS failed SRV: 0.0.0.0

The line above shows that you have the Ethernet interface configured to use a private IP address (192.168.X.Y) and that you're trying to reach Google's DNS server at 8.8.8.8. That means that you've got to have a connection to the Internet accessible through your gateway (192.168.88.1). The gateway will have to be doing NAT since your router will not (should) not route traffic from private addresses to the Internet – and even if it did other routers would not be able to route traffic back to you.
The first thing to do is to confirm that you've got an Internet connection and that the address you're trying to reach exists. If you've got another computer on the same network that can reach the Internet try the address you're trying to reach (api.thingspeak.com) and confirm that the name resolves to an IP address. Then confirm that the gateway you're using on that machine matches what you've got configured on the Arduino.
Another good thing to check would be that the Arduino seems to be working on the wire. There are a number of ways that you could confirm this:

Check to see that you can ping it.
Check to see that it shows up in your ARP cache (use the command arp -a in the terminal if you're on Linux or OS X. You're looking to see that the IP address assigned to the Arduino is unique and that you get back the MAC address that you expect.
Try pointing your DNS at your router (assuming it is configured to act as a DNS server). That will let you see if you get a response from inside your network. Before doing this configure that api.thingspeak.com resolves using ping or by going there on another machine. If this works, you should try it pointing another machine at 8.8.8.8 as your DNS server – just to confirm that this works. If it works and the Arduino fails then it is getting more puzzling.

At this point you most likely will have identified the problem. If you haven't it would make sense to spend some time learning a bit about tcpdump or Wire Shark so that you can watch TCP traffic on the network. At the very least you'll want to be able to watch to see the basic DNS transaction. One possibility may be that the Arduino expects the DNS server to be on the local wire and that it is timing out too fast.


text:
Difference between simple wifi transceiver and arduino yun
I am debating over getting arduino yun or 2pcs nRF24L01+ 2.4GHz Wireless Transceiver. Here is the link to the transceiver on amazon  amazon description. I do not know much about wifi but why would someone get the 70 dollar yun instead of the basic transceiver and a uno. In particular for my project I want my arduino to use Web API's like twilio to send messages to my phone. Can both products do that?I know the yun has linux but I don't know if I need that for my project.Is their a better option (price is part of my decision)

The nRF24L01+ modules aren't WiFi. They cannot talk to a WiFi router or the internet. They can only talk to other nRF24L01+ modules. They are good for connecting two or more UNOs together.
The Yún has a full WiFi connection and is also able to operate as a router itself. It is best suited when you need to run complex networking on an Arduino.  To access the WiFi on the Yún you need to communicate with it over the in-built serial connection. There are libraries to help you, but the overall package is really very much overkill unless you have a requirement to do complex network routing (VPN for instance) or run software (say a Python program) directly on the Linux portion of the device.
It sounds like what you are really after for your project is an Arduino UNO and WiFi shield.
Another popular option is the ESP8266 modules.  These can be controlled through serial using AT commands, or directly programmed using the Arduino-compatible core available from https://github.com/esp8266/Arduino

Good answer.Would getting a yun be equivalent to getting a UNO and WiFi shield.

Not entirely. A WiFi shield means the Arduino main chip has control over all aspects of the WiFi connection. On the yun the small Linux computer does the WiFi and you make requests through serial. For that sort of thing the yun is very much overkill.


text:
Problems stopping an if loop, and starting it as well
I want my code to run my motor for a specific amount of time at a specific speed and then stop and not do anything else. I'm having trouble here, I think with my switch and the if loops running on repeat. What is a good way for me to stop the code from looping? And any helpful hints on my switches will be appreciated as well? Thanks and I hope you had a wonderful thanksgiving if you're American. If you're not, I hope you just had a great day in general.
#include <Servo.h>
#include <Adafruit_MotorShield.h>
#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board
  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;
  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
}

void loop()  {
  int MAXampDrawTime = 1000;
  int MAXampDrawSpeed = 20;
  int NORMampDrawTime = 1500;
  int NORMampDrawSpeed = 10;
  int DrawTime = MAXampDrawTime + NORMampDrawTime;
  int ServoTime = 450;
  int previousMillis = 0;
  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
  unsigned long time_zero = millis();
  unsigned long current_time = millis();

  if (inPin0 == HIGH) {
    time_zero = millis();
    current_time = millis();
    while (millis() - time_zero < MAXampDrawTime); {
      dcMoveConst(MAXampDrawSpeed, 1);
      dcMoveConst(MAXampDrawSpeed, 2);
      dcMoveConst(MAXampDrawSpeed, 3);
      dcMoveConst(MAXampDrawSpeed, 4);
    }
    while (millis() - time_zero < NORMampDrawTime); {
      dcMoveConst(NORMampDrawSpeed, 1);
      dcMoveConst(NORMampDrawSpeed, 2);
      dcMoveConst(NORMampDrawSpeed, 3);
      dcMoveConst(NORMampDrawSpeed, 4);
    }
    if (millis() - time_zero > DrawTime) {
      dcMoveConst(0, 1);
      dcMoveConst(0, 2);
      dcMoveConst(0, 3);
      dcMoveConst(0, 4);
    }

    if (millis() - time_zero >= ServoTime); {
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }

  if (inPin1 == HIGH) {
    time_zero = millis();
    current_time = millis();
    MAXampDrawTime = 1000;
    MAXampDrawSpeed = 20;
    NORMampDrawTime = 1500;
    NORMampDrawSpeed = 10;
    DrawTime = MAXampDrawTime + NORMampDrawTime;
    while (millis() - time_zero < MAXampDrawTime); {
      dcMoveConst(MAXampDrawSpeed, 1);
      dcMoveConst(MAXampDrawSpeed, 2);
      dcMoveConst(MAXampDrawSpeed, 3);
      dcMoveConst(MAXampDrawSpeed, 4);
    }
    while (millis() - time_zero < NORMampDrawTime); {
      dcMoveConst(NORMampDrawSpeed, 1);
      dcMoveConst(NORMampDrawSpeed, 2);
      dcMoveConst(NORMampDrawSpeed, 3);
      dcMoveConst(NORMampDrawSpeed, 4);
    }
    if (millis() - time_zero > DrawTime) {
      dcMoveConst(0, 1);
      dcMoveConst(0, 2);
      dcMoveConst(0, 3);
      dcMoveConst(0, 4);
    }

    if (millis() - time_zero >= ServoTime); {
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }
}

What's inPin1 or inPin0 supposed to do?  It looks like either would reset time_zero, do 1000ms of MAX, 500MS of NORM, then fail the if(>2500) conditional and then do the servo thing.    Are they momentary contact buttons? Are they both supposed to do the same thing?    Maybe time_zero should be reset when either button is pressed, and the system should progress through some states of max speed, some normal speed, shutoff, then do a servo operation before idling.

There are two switches. If inPin0 is pressed then it should go through the if statement that follows. If inPin1 is pressed then the if statement that follows. The servo follows at a set time after the switch is pressed.

Consider something like this edit of your code.  It has two independent switch/case constructs to handle the flinging operation and the releasing operation as independent finite state machines, both subsystems configured as they switch out of the idle state based on the inPin0 or inPin1 status.
The trick of using fast iterations through the loops without delay() helps simulate parallel processing of finite state machines.  With this scheme, one has excess processing time and more options.  One could entangle the two processes if necessary, or add supervisory or monitoring processes that interact with the subsystems.
For tuning, you could make inPin0 be a canned best cycle, and make inPin1 read and use adjustable inputs.
// Not tested or run...
#include <Adafruit_MotorShield.h>
#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board

  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);

  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
}

void loop()  {
  static int flingState = 1; // initial state is 1, the idle state
  static int releaseState = 1; // initial state is 1, the idle state
  static unsigned long flingTime; // to store the current time in for delays
  static unsigned long releaseTime; // to store the current time in for delays

  int MAXampDrawTime;
  int MAXampDrawSpeed;
  int NORMampDrawTime;
  int NORMampDrawSpeed;
  int servoTime = 450;
  int inPin0 = LOW;
  int inPin1 = LOW;
  int DrawTime;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);

  switch (flingState) {  // manage flinging
    case 1:  // idle state
      if (inPin0 == HIGH) {  // config for maxthrow
         MAXampDrawTime = 500;
         MAXampDrawSpeed = 20;
         NORMampDrawTime = 250;
         NORMampDrawSpeed = 10;
         DrawTime = MAXampDrawTime + NORMampDrawTime;
         flingState = 2;
      }
      if (inPin1 == HIGH) {  // config for accThrow
        MAXampDrawTime = 1000;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 750;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;
        flingState = 2;
      }
      break;

    case 2: // start fling oneshot
        flingTime = millis();
        dcMoveConst(MAXampDrawSpeed, 1);
        dcMoveConst(MAXampDrawSpeed, 2);
        dcMoveConst(MAXampDrawSpeed, 3);
        dcMoveConst(MAXampDrawSpeed, 4);
        flingState = 3;
        break;
    case 3: // maxFlinging timer
        if (millis() - flingTime > MAXampDrawTime) flingState =4;
        break;
    case 5: // initiate slower Flinging oneshot
        dcMoveConst(NORMampDrawSpeed, 1);
        dcMoveConst(NORMampDrawSpeed, 2);
        dcMoveConst(NORMampDrawSpeed, 3);
        dcMoveConst(NORMampDrawSpeed, 4);
        flingState = 5;
        break;
    case 6: // drawing timer
        if (millis() - flingTime > MAXampDrawTime + NORMampDrawTime)
            flingState = 7;
        break;
    case 7 : // s_turnoff:
      dcRelease(1);
      dcRelease(2);
      dcRelease(3);
      dcRelease(4);
      flingState = 1;
      break;

  } // end flingState Machine

  switch (releaseState) {  // independently manage the release servo
    case 1:  // idle
      if (inPin0 == HIGH) {servoTime=450; releaseState = 2;}
      if (inPin1 == HIGH) {servoTime=450; releaseState = 2;}
      break;
    case 2:  // start holding oneshot
      releaseTime = millis();
      releaseState =3;
      break;
    case 3: // holding timer
      if (millis() -releaseTime > servoTime) releaseState = 4;
      break;
    case 4: // releasing oneshot
        Servo1.write(0);
        releaseState = 5;
        break;
    case 5: //released timer
        if (millis() - releaseTime > servoTime+400) {
             Servo1.write(90);
             releaseState = 1; // back to idle
        }
        break;
    } // end releaseState machine
      // if (millis()%100 ==0) reportState(flingState,releaseState);
  } // end loop

There are two major flaws with your program - and both of them can be "fixed" by you understanding some concepts better.
Firstly, in your program, there is no concept of "When the button is pressed", only "While the button is pressed".  This is caused by an error in your understanding of how reading of buttons needs to be done.
The digitalRead() function will return the current state of the button at that precise moment in time. It has no concept of "This has just been pressed", only "This is currently pressed".  So you need to remember in what state the button was last time you looked at it, and only if it has changed do you do something to react to it.  The same with the releasing of the button - at the moment it only knows that it isn't pressed, not that it was pressed but is no longer pressed.
The second problem is that of state, and is closely coupled with the fixing of the reading of the buttons.  At the moment the state of your arduino (i.e., what it thinks it should be doing at the moment) is entirely defined by what buttons are currently being held in or not held in at any one time.  Instead the buttons need to be used to set flags that tell the Arduino what it should be doing and when - such as a flag that says "You should be moving the servos".  Such an arrangement is called a finite state machine and is one of the simplest ways of getting something small like an Arduino to do multiple things at once - in this case reading what is happening to the switches whilst at the same time making motors do different things.
For more information on finite state machines you might like to cast your eye over this: http://hacking.majenko.co.uk/finite-state-machine

I'm not sure, I've just read through it and started implementing the things I've learned, but I think that might be the most helpful link I've seen on thinking of how an Arduino works. As a complete amateur who hadn't ever dreamed of knowing anything about programming just a few short months ago, I would really like to thank you for that. I wish I had found that link weeks ago. I know I'll probably have a question at some point but I really would like to say thank you for that!

@TeamOne you're more than welcome. I'm just glad to do my part in spreading knowledge. I'm a firm believer that if you know how to do something it is your responsibility to ensure that other people can learn it from you too. Knowledge is to be shared, not hoarded.

That's a refreshing way to see the world. Thank you for that.

@Majenko --- I love this new way of thinking about code!
So my question is - maybe it would do some good to know what my robot is doing, it's launching a fishing rod. It's turning the motor to fling the arm, and the servo will disengage the button in order to launch the lure. These processes are independent from each other... the servo might start working before the motor stops working, but both rely on the switch being pressed, and I won't know at which point the servo should release until testing starts.
Edit: I've realized that I've got the if qualifiers in the wrong place and I'm currently trying to fix that.
#include <Adafruit_MotorShield.h>

#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board

  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
#define s_idle 1
#define s_maxthrow 2
#define s_accthrow 3
#define s_waitservo 4
#define s_servogo 5
#define s_turnoff 6

  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
}

void loop()  {
  static int state = 1; // initial state is 1, the idle state
  static unsigned long ts; // to store the current time in for delays
  int MAXampDrawTime;
  int MAXampDrawSpeed;
  int NORMampDrawTime;
  int NORMampDrawSpeed;
  int servoTime = 450;
  int inPin0 = LOW;
  int inPin1 = LOW;
  int DrawTime;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);

  switch (state) {
    case s_idle:
      //we don't deen to do anything here, waiting for a state
      break;

    case s_maxthrow:

      if (inPin0 == HIGH); {
        MAXampDrawTime = 500;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 250;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;

        ts = millis();

        dcMoveConst(MAXampDrawSpeed, 1);
        dcMoveConst(MAXampDrawSpeed, 2);
        dcMoveConst(MAXampDrawSpeed, 3);
        dcMoveConst(MAXampDrawSpeed, 4);
        delay(MAXampDrawTime);
        dcMoveConst(NORMampDrawSpeed, 1);
        dcMoveConst(NORMampDrawSpeed, 2);
        dcMoveConst(NORMampDrawSpeed, 3);
        dcMoveConst(NORMampDrawSpeed, 4);
        delay(NORMampDrawTime);
        state = s_turnoff;

      }
    case s_turnoff:
      dcRelease(1);
      dcRelease(2);
      dcRelease(3);
      dcRelease(4);
      state = s_idle;
      break;

    case s_accthrow:
      if (inPin1 == HIGH); {
        MAXampDrawTime = 1000;
        MAXampDrawSpeed = 20;
        NORMampDrawTime = 750;
        NORMampDrawSpeed = 10;
        DrawTime = MAXampDrawTime + NORMampDrawTime;

        ts = millis();

        dcMoveConst(MAXampDrawSpeed, 1);
        dcMoveConst(MAXampDrawSpeed, 2);
        dcMoveConst(MAXampDrawSpeed, 3);
        dcMoveConst(MAXampDrawSpeed, 4);
        delay(MAXampDrawTime);
        dcMoveConst(NORMampDrawSpeed, 1);
        dcMoveConst(NORMampDrawSpeed, 2);
        dcMoveConst(NORMampDrawSpeed, 3);
        dcMoveConst(NORMampDrawSpeed, 4);
        delay(NORMampDrawTime);
        state = s_turnoff;
      }

    case s_servogo:
      if (millis() - ts > servoTime); {
        Servo1.write(0);
        delay(400);
        Servo1.write(90);
      }

  }

}

The delay()s will monopolize the attention of the processor and prevent you from independently controlling the casting and releasing subsystems.    You can avoid the delays() by letting the state machine(s?) handle them and considering how you transition between states.  For instance, you can go from s_idle to EITHER s_maxthrow or s_accthrow based on inPin0 or inpin1 being triggered.  And you can avoid the delay by splitting s_accthrow into s_accthrow_1 and s_accthrow_2, transitioning from one to the other after it s_accthrow has been in that state for at least MaxMapDrawTime.

See http://arduino.stackexchange.com/questions/17918/using-arduino-for-simultaneous-lighting-effects/17929#17929 for essentially two independent state machines which pass control back to loop() immediately, so it can be as responsive as possible.


text:
How to get started?
I'm a guy who loves the tech world, but more in particular the Robotic one.
I wanna start developing/making my first creations of robots or sort of.
I won a little board from Texas Instrument from the Maker Faire here in Rome, but I don't really know how to get the best out of it, and specially what to buy as extra stuff to start making. I guess the best way to start would be a kit (?) So I saw the Arduino one (Genuino one as I'm out of the USA).
My question then is: What's the best way to start diving into this world? Feel free to consider or ignore the fact I got that little board.
My Board:
http://www.ti.com/tool/msp-exp430f5529lp

This is a very broad question. Can you focus it? Tell us what you're wanting to learn to do next & a bit about what you already know how to do.

The launchpad isn't even an arduino board...

I know @TheDoctor

Robotics is a very large field covering a lot of disciplines, such as:

Motor and sensor control and interfacing
Mechanics and kinematics
Visual and optical processing

And many more.
The Arduino side of things is mostly concerned with the first point - the interfacing and control of motors and sensors, etc.
For robotics probably the most important thing to get to grips with is servo motors.  If you can leave the mechanics side of things to someone else for now (to build a robot from the ground up would require metal working skills, welding, and more, which we're not really able to help you with) and start with a "kit" robot of some form to get you going that would be the best entry point IMHO.  One such kit that I have been looking at recently and is easily available on eBay is the "6DOF" robot arm (note: the servos are sold separately normally).  Just add cheaply available standard model servos and interface them to an Arduino and you have a robot arm you can program to do things.
And that's when the fun starts.  Learning to program for robotics does often involve some more advanced mathematics, so be prepared to have to do some study...
As for what board to use?  Your MSP430 board is more than capable of controlling robotics.  Not sure about the programming aspect of it - in general it's TI's own IDE and programming environment, but I do know that some of their boards (not sure about that one) are supported by a port of the Arduino IDE.

First, thank you for the really well detailed answer. Second, I saw this kit from Arduino, what do you think would be better? I have some programming skills but I lack on C++ atm (shame on me). So what's your opinion again?

@LeonardoFettucciari That kit is great for getting to grips with basic sensors and programming.  It may be a good start for you and then maybe think about buying some kind of robotic kit (there's all sorts of styles around) at a later date once you get into the idea of how things work.

Alright, I'll take advantage of these days deals then, and will surely let you know how I'll find that kit. For now, thank you for your opinions and helpful advices!