text:
Read/write data from 2 Arduinos simultaneously with Python
So for my project I have one Arduino Mega hooked up with a quadrature rotary encoder which is connected to the computer. An Arduino Uno is connected to a circuit I built, which in turn is connected to a valve and a touch connector (also connected to the computer via USB). Both of them should be controlled with a Python script.
If the rotary encoder is moved, I can read out a value via the serial port. The value of the rotary encoder is used in Python to move a dot on the screen. If the dot on the screen reaches a certain point, I want to give a signal to the valve to open (something like pin.write(1) to turn on or pin.write(0) to turn it off). At the same time I want to be able to detect the touch sensor if the circuit is closed.
The issue is now that I need to somehow need to read the rotary encoder, process the data and send it to the valve, as well as reading the touch sensor simultaneously. So far I have not found a way how to achieve this as my code does not function.
At the moment I have custom code on My Arduino Mega and a StandardFirmata on the Arduino Uno, but I am open to other suggestions that could work.
Arduino Mega code:
/*
by Ben-Tommy Eriksen
https://github.com/BenTommyE/BenRotaryEncoder
*/

// Encoder connect to digital pin 2 and 3 on the Arduino.

int counter = 0;
//This variable will increase or decrease depending on the rotation of encoder

void setup() {
  Serial.begin (4600);
  //Setting up interrupt
  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
  attachInterrupt(0, ai0, RISING);
  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
  attachInterrupt(1, ai1, RISING);
}

void loop() {
  // Send the value of counter
  Serial.println (counter);
}

void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
    counter++;
  } else {
    counter--;
  }
}

void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
    counter--;
  } else {
    counter++;
  }
}

Python code:
import pyfirmata
import serial
import time

#Associate pyfirmata with python for my UNO board
port='COM5'
board= pyfirmata.Arduino(port)
#Use iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start()

#Define pins (giving roles to pins: i.e. d=digital,7=pin number,i=input)
lickPin = board.get_pin('d:10:i') #records signal from the touch sensor
outPin1 = 12 #passes the signal to the valve

s = serial.Serial('COM4',4600)
while time<60s #generalized:
    rotary = s.readline() #reads the counter of the rotary encoder form arduino

    #convert the rotary to an integer try/except is needed to work
    try:
        var = long(rotary)
        last_var = var
    except:
        var = last_var
        pass

    value1 = lickpin.read()

    # Here I move the cursor up and down depending on the rotation of the encoder
    # if the cursor moves above a certain value
    if y>-18:
        board.digital[12].write(1) #should open the valve

Unfortunately the code above does not trigger the valve to be opened, and I do not know why. Help is greatly appreciated. Thanks!

If you really like Python, simply consider using a RPI instead.

Add a bunch of print()s. Verify that you're even receiving the right value through the serial port.

I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).
Here is the pinout:
ENCODER            ARDUINO UNO
====================================
GND            ⇒   GND
+              ⇒   +5V
SW  (button)   ⇒   pin D4 (PORT D4)
DT  (encoder)  ⇒   pin D3 (PORT D3)
CLK (encoder)  ⇒   pin D2 (PORT D2)

Here is a screenshot of the output in the serial plotter:

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

And here is the code :
/*
LECTURE D’UN ENCODEUR ROTATIF KY-040
====================================
# DESCRIPTION DU PROGRAMME
Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
série de l’IDE Arduino (CMD-SHIFT-L).
La rotation du bouton est détecté avec des interruptions sur les
broches 2 et 3 du port D.
Ce programme implémente un filtrage des rebond en deux étapes (voir
la procédure “lectureEncodeur”).
Ce programme est basé sur celui d’Oleg Mazurov
https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
Pour la gestion des interruptions, voir
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
# RÉFÉRENCE DE L’ENCODEUR
http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
# CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (bouton)   ⇒   pin D4 (PORT D4)
    DT  (encodeur) ⇒   pin D3 (PORT D3)
    CLK (encodeur) ⇒   pin D2 (PORT D2)
juin 2016, ouilogique.com
*/

#define ENC_A 2
#define ENC_B 3
#define ENC_C 4
#define ENC_PORT PIND
#define BtnRead  ! bitRead( ENC_PORT, ENC_C )

bool encodeurTourne = false;
byte ENC_PORT_VAL = 0;

// Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
// pas trop vite. Cette valeur représente le nombre de millisecondes
// avant un changement sur la sortie.
static const long sensibiliteEncodeur = 10;

// Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
static const int8_t minVal = 0;
static const int8_t maxVal = 10;

void setup()
{
  pinMode( ENC_A, INPUT_PULLUP );
  pinMode( ENC_B, INPUT_PULLUP );
  pinMode( ENC_C, INPUT_PULLUP );

  PCICR  |= ( 1<<PCIE2 );
  PCMSK2 |= ( 1<<PCINT18 );
  PCMSK2 |= ( 1<<PCINT19 );
  PCMSK2 |= ( 1<<PCINT20 );
  PCMSK2 |= ( 1<<PCINT21 );

  encodeurTourne = true;

  Serial.begin( 115200 );
}

void loop()
{
  static int8_t compteur = 0;

  // Lecture et affichage des valeurs de l’encodeur
  // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
  if( encodeurTourne )
  {
    int8_t encodeurVal = lectureEncodeur();

    // Si le bouton est pressé, on remet le compteur à 0.
    if( encodeurVal == 2 )
    {
      compteur = 0;
      Serial.println( 0 );
      while( BtnRead ){ _delay_ms( 1 ); }
      _delay_ms( 20 );
    }

    // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
    else if( encodeurVal != 0 )
    {
      if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
        { compteur = minVal; }
      else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
        { compteur = maxVal; }
      else
        { compteur = compteur + encodeurVal; }

      Serial.println( compteur );
    }
    encodeurTourne = false;
  }
}

/*
  lectureEncodeur() retourne
  -1 pour une rotation dans le sens anti-horaire
   0 pour une valeur impossible (rebond)
  +1 pour une rotation dans le sens horaire
  +2 si le bouton de l’encodeur est pressé
*/
int8_t lectureEncodeur()
{
  // Si le bouton est pressé, on quitte en retournant 2.
  if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
  {
    return( 2 );
  }

  // Lecture des signaux de l’encodeur et comparaison
  // avec les valeurs possibles dans le code de Gray.
  // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
  // Les valeurs à 0 représentent les transitions impossibles
  // et qui doivent être supprimées (resultat = 0).
  // Les valeurs à 1 représentent les transitions dans le sens horaire.
  // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
  static const int8_t enc_states[ 16 ] PROGMEM =
    { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
  static uint8_t old_AB = 0;

  old_AB <<= 2;
  bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
  bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
  uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

  // On accumule “maxVal” résulats dans un sens ou dans l’autre
  // avant de bouger. Ceci permet de supprimer les derniers rebonds
  // de l’encodeur qui n’ont pas été filtrés ci-dessus.
  if( resultat != 0 )
  {
    static int8_t resultatCumul = 0;
    const int8_t maxVal = 2;
    resultatCumul += resultat;
    if( resultatCumul >= maxVal )
    {
      resultatCumul = maxVal;
      resultat = 1;
    }
    else if( resultatCumul <= -maxVal )
    {
      resultatCumul = -maxVal;
      resultat = -1;
    }
    else
      { resultat = 0; }
  }

  // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
  // et éviter ainsi qu’il ne tourne trop vite.
  static long lastT = millis();
  if( millis() - lastT < sensibiliteEncodeur )
    { resultat = 0; }
  else
    { lastT = millis(); }

  // On retourne le résultat.
  return( resultat );
}

ISR( PCINT2_vect )
{
  ENC_PORT_VAL = ENC_PORT;
  encodeurTourne = true;
}

What relevance does this have to the actual problem of the question?

This sketch is the best I know to read KY-040 encoders, so I guess it is pretty relevant.

No, the poster had already solved that problem.  The question concerns a different problem.

OK, never mind. At least you know where to find a good solution to read KY-040 encoders if you need that in the future.


text:
Analog input weirdness (barrel connector vs USB power)
I noticed that my Arduino Mega performs differently in how it presents values from say analog input A0, depending on whether it is being powered by USB or by a fresh 9V battery wired and connected through the barrel connector.
There must be some sort of difference to what happens when both USB and the barrel connector are employed vs. just USB being used for power.
To be specific, when running just on USB power, the analog inputs seem to flicker more allowing for oversampling and measurements beyond the 10 bit accuracy of the DAC. In fact with analogReference(DEFAULT) it is possible with 64x oversampling to see 100uV level changes when only USB power is employed. Note that these changes are not just noise, they actually correspond to 100uV level changes in the input connected to A0 with high correlation.
As soon as I connect the barrel connector, the picture changes significantly. Values coming out of the ADC seem to pretty much snap and there is far less flicker. The ADC becomes, well, discrete and you get your 1,024 levels and that's about it. There may be a tiny bit of flicker as you increase or decrease voltage and approach the next increment, but this is not significant enough to actually increase the ADC resolution reliably.
Even going so far as setting the analogReference to EXTERNAL while the barrel connector is employed and connecting the AREF pin to the 5v connector directly, which by the way reads at 5.004 V  (unlike the 4.992 V it reads when USB is powering the device) still reproduces the problem.
Summary: Effectively, when running on USB power only I can oversample the analog inputs and get significantly more than 10-bit resolution. While when running using the barrel connector, with the USB still attached, I can only get the 10-bit resolution natively provided by the ADC.
If anyone has any ideas on what is causing this difference in behavior, I am all ears. If I failed to explain anything or perhaps created some confusion, I would be more than happy to clarify.
Note: This is an authentic Arduino Mega board.

Looking at the schematic the barrel plug has a couple of linear voltage regulators (top left of schematic), while the USB input just has a couple of MOSFETs (bottom right of schematic) which are basically just there to switch off the USB power if there is something plugged into the barrel jack (and also maybe provide a little input protection). So the Arduino is relying on the USB power to be pre-regulated. For the most part this is correct, but USB voltage can vary widely depending on the cable length (voltage drop), the power source it is connected to (no two computers or wall warts are the same), and how many devices are the same hub (if connected to a computer or hub). I would not rely on the two power sources being matched at all.
The flicker you are talking about sounds like the power coming from USB could have significant ripple. I doubt that the USB power is allowing you to "oversample". The way ADCs in AVRs work is they have a reference voltage and when sampling, will give you a reading of where the voltage is between 0 and the voltage reference. With a 10-bit ADC there are ~1000 steps, so to measure 100uV changes, you would have to have a 100 mV reference voltage, which according to the datasheet (p.379), the minimum is 1.0 V. Basically, it is physically impossible for the Arduino Mega to measure those kinds of changes.
What is more likely to be happening is that you are probably getting some weird aliasing between the ripple frequency of your USB voltage and the sampling frequency of your code. The best way to debug this kind of thing would be to pull out an oscilloscope and check if and how much ripple is coming off the USB power.
If accuracy is important to your project, and being able to accept both power inputs is a requirement, you might look into maybe getting your own external voltage reference and piping it into VREF. Otherwise, I would stick to only using the barrel plug as it is regulated and will be consistent.

Or use one of the internal voltage references (1.1V or 2.56V) in the ATmega1280.

@Gerben Yeah I thought of that, the asker didn't make it clear what types of sensors he was using and what village ranges he was looking at, but vaguely implied it was 5 volts.

@Jake, Analog Sensor A0, voltage range required = 0 - 5 V. analog reference DEFAULT(or EXTERNAL tied to 5V), same result.

source: Stack Exchange

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

sort: votes


text:
HC-05 and HC-06 Bluetooth not communicating well
I am trying to communicate between two Arduino UNO. One has a HC-05 which is configured as master, the other Arduino has HC-06 which is the slave. What I want to achieve is to be able to print a character on the Serial monitor of the slave Arduino when a button on the master Arduino is pressed. I have been able to pair the two and once they are powered, they connect automatically. When I press a button on the master, what I get on the serial monitor of the slave is the 254 instead of the character 'a' which is what I am sending from the master. I have tried changing the data type, and also switched the code for master and slave, but the problem persists. I have also used hardware serial instead of software serial. My HC-05, and HC-06 works well when paired with android phone and can send and receive useful data. My code is as shown below:
CODE FOR MASTER:(SENDER)

#include<SoftwareSerial.h>
const int rxPin = 10;
const int txPin = 11;
const int button = 2;

SoftwareSerial masterSerial(rxPin,txPin);//RX,TX.

void setup() {
   pinMode(button, INPUT);
   Serial.begin(9600);
   masterSerial.begin(9600);
}

void loop() {

   int buttonVal = digitalRead(button);
   if(buttonVal==HIGH){
       masterSerial.write('a');
      delay(1000);
   }
//mySerial.flush();
}

CODE FOR SLAVE( RECEIVER)
#include<SoftwareSerial.h>

const int rxPin = 10;
const int txPin = 11;

int incomingByte = 0;

SoftwareSerial slaveSerial(rxPin,txPin);//RX,TX.

void setup() {

   pinMode(13, OUTPUT);
   Serial.begin(9600);
   slaveSerial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:

   while(slaveSerial.available()){
      incomingByte = slaveSerial.read();
      delay(3);
      Serial.println(incomingByte);
    }
}

I have the same problem, anyone solved?

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


text:
How do I send tweets with flame sensor and ESP8266?
I want to send tweets with flame sensor and ESP8266. My flame sensor is digital. I think everything is good but it doesn't send.
This is my code:

#define ag_ismi "SSID"
#define ag_sifresi "PASSWORD"
#define IP "184.106.153.149" //thingspeak.com IP address

int sensorPin = 8;
int smoke_level = HIGH;

void setup() {
  pinMode(sensorPin, INPUT);
  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if (Serial.find("OK")) {
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu = String("AT+CWJAP=\"") + ag_ismi + "\",\"" + ag_sifresi + "\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  smoke_level = digitalRead(sensorPin); // Arduino reads the value from the smoke sensor
  Serial.println(smoke_level);// prints just for debugging purposes, to see what values the sensor is picking up
  if (smoke_level == HIGH) {
    // if smoke level is greater than 500, the buzzer will go off
    sicaklik_yolla();
  }
  delay(20000);
}
void sicaklik_yolla() {
  Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
  delay(1500);
  String tweet = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
  tweet += "Host: api.thingspeak.com\n";
  tweet += "Connection: close\n";
  tweet += "Content-Type: application/x-www-form-urlencoded\n";
  tweet += "Content-Length:67\r\n\r\napi_key=";
  tweet += String("MY API KEY");
  tweet += String("&status=");
  tweet += String("MY TWEET TEXT");
  Serial.print("AT+CIPSEND=");
  delay(100);
  Serial.println(tweet.length());
  if (Serial.find(">")) {
    Serial.println(tweet);
    Serial.println("AT+CIPCLOSE=0");
    delay(100);
  } else {
    Serial.println("AT+CIPCLOSE=0");
  }
}

This schema is old. Sensor connected to pin 8.

I guess your baud rate and network connection with the wifi module is working fine. Have to say that it is a bit difficult to get the data sent to ThingSpeak with ESP8266. I actually did some experiments to get the data sent. The problem is actually with the delay. Adding a delay of 5000 ms between sending the tweet length and the tweet content sorts it out. You can use GET format. Check out this Instructable.

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

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


text:
Better cycling through the RGB colors
I have been trying to achieve a way to tap into the 16 million colors RGB provides for this LED strip. I thought of using LEDS.setBrightness(); but I have not been successful in my attempts. I have read the documentation on color fading, but I have not been able to write this to my Arduino Leonardo. Here is my code below, which cycles through the initial rainbow of 0-255. I was wondering how to get more than 0-255 if not all the colors.
#include <FastLED.h>

#define LED_COUNT 60
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];
int wait_time = 5;

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void loop() {
  //start from red
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 255;
    int g = 0;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }

  //into blue
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = colorStep;
    int g = 0;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from blue
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 0;
    int g = colorStep;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into green
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 0;
    int g = 255;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from green
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = colorStep;
    int g = 255;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into yellow
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 255;
    int g = colorStep;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
} //end main loop

but RGB's 0-255 levels is all the colors, what are you trying to do?

that's correct, but if you follow my loops you'll see that I am only doing the combinations 0 < 255 and 0 > 255 for rgb. I.E. 0, 0, 255 // blue or 255, 0, 0 //red which is why i said the initial rainbow. there are no combinations of let's say 128, 64, 250.

Ahh, i see; then just nest your loops...

tried that like w/ @6v6gt answer. unfortunately, it does not cycle thru the LEDs properly.  There seems to be a iteration problem with the first nested loop (not the code provided) just the way the FastLED class handles the nesting?

I think it's worth noting that the three 255 values for RGB colour space is just one way to encode the 255^3 (16,581,375) colours. These include each and every brightness level too.
If you are trying to get a rainbow effect, you may have more success or find it easier to use a HSL or HSV colour space.
HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:
https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors

Re-using fastled is indeed a very good option! You'll overcome reinventing the wheel, and have a more efficiënt wheel ;p

I've included a simple sketch that will cycle a single RGB led using the sine fade technique
// Cycle a single RGB led using the sine fade technique
// For common cathode led

const uint8_t lights[360]={
  0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 20, 22, 24, 26, 28, 30, 32, 35, 37, 39,
 42, 44, 47, 49, 52, 55, 58, 60, 63, 66, 69, 72, 75, 78, 81, 85, 88, 91, 94, 97, 101, 104, 107, 111, 114, 117, 121, 124, 127, 131, 134, 137,
141, 144, 147, 150, 154, 157, 160, 163, 167, 170, 173, 176, 179, 182, 185, 188, 191, 194, 197, 200, 202, 205, 208, 210, 213, 215, 217, 220, 222, 224, 226, 229,
231, 232, 234, 236, 238, 239, 241, 242, 244, 245, 246, 248, 249, 250, 251, 251, 252, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 253, 253,
252, 251, 251, 250, 249, 248, 246, 245, 244, 242, 241, 239, 238, 236, 234, 232, 231, 229, 226, 224, 222, 220, 217, 215, 213, 210, 208, 205, 202, 200, 197, 194,
191, 188, 185, 182, 179, 176, 173, 170, 167, 163, 160, 157, 154, 150, 147, 144, 141, 137, 134, 131, 127, 124, 121, 117, 114, 111, 107, 104, 101, 97, 94, 91,
 88, 85, 81, 78, 75, 72, 69, 66, 63, 60, 58, 55, 52, 49, 47, 44, 42, 39, 37, 35, 32, 30, 28, 26, 24, 22, 20, 18, 17, 15, 13, 12,
 11, 9, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

const byte redpin = 3;
const byte greenpin = 5;
const byte bluepin = 6;
int loopdelay = 5000; // ms
int displaylength = 50; // ms

boolean showiterations = false;

//_______________________________
void setup() {
      Serial.begin(9600);
}

void loop() {
for (int k=0; k<360; k++)
{
    if (showiterations) {
    Serial.print(k);
    Serial.print(F(","));
    }
analogWrite(redpin, lights[(k+120)%360]);
analogWrite(greenpin, lights[k]);
analogWrite(bluepin, lights[(k+240)%360]);
delay(displaylength);
}
if (showiterations) {
Serial.println("  ");
}
delay(loopdelay);
}

This sketch is derived from an Instructables posting entitled "How to Make Proper Rainbow and Random Colors With the RGB Color Model", http://www.instructables.com/id/How-to-Make-Proper-Rainbow-and-Random-Colors-With-/
It additionally provides information and rationale behind different techniques for cycling colours.

If you are trying to stagger the colours along the strip whilst creating a rainbow effect,  I have another sketch [from Adafruit, I believe] that will do this.  I've used it effectively with different Neopixel ring configurations.  The sketch demonstrates a number of different techniques. I have currently commented out the invocations of all but the theaterChaseRainbow, but you may wish to explore them all.
#include <Adafruit_NeoPixel.h>
// following atatement should be wrapped with an ifdef for __AVR__, but this facility botches it up.
// As it is, formatting for the sketch is not quite right, and I do not have a solution for that.
  #include <avr/power.h>

const  byte PIN = 7;

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800)`
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, 6, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
   colorWipe(strip.Color(0, 0, 0), 50); // blank
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Some example procedures showing how to display to the pixels:
//  colorWipe(strip.Color(255, 0, 0), 50); // Red
//  colorWipe(strip.Color(0, 255, 0), 50); // Green
//  colorWipe(strip.Color(0, 0, 255), 50); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
//  theaterChase(strip.Color(127, 127, 127), 50); // White
//  theaterChase(strip.Color(127, 0, 0), 50); // Red
//  theaterChase(strip.Color(0, 0, 127), 50); // Blue

//  rainbow(20);
//  delay(50000);
//  colorWipe(strip.Color(0, 0, 0), 50); // blank
//  rainbowCycle(10);
//  delay(5000);
//    colorWipe(strip.Color(0, 0, 0), 50); // blank
//   delay(5000);
  theaterChaseRainbow(50);
//  delay(5000);
//    colorWipe(strip.Color(0, 0, 0), 50); // blank
//   delay(5000);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

Although your answer is 100% correct, it might also become 100% useless
if that link is moved, changed, merged into another one or the main site
just disappears... :( Therefore, please [edit] your answer, and copy
the relevant steps from the link into your answer, thereby guaranteeing
your answer for 100% of the lifetime of this site! ;) You can always
leave the link in at the bottom of your answer as a source for your
material...

@Avamander, suggestion taken, pls re-evaluate.

You can make a smooth transition/sliding rainbow effect by using a sine wave lookup table, then phase shifting green and blue by 120 and 240 degrees.
#define RED 9
#define GREEN 10
#define BLUE 11

uint8_t sins[360] = {
  127,129,131,134,136,138,140,143,145,147,149,151,154,156,158,160,162,164,166,169,171,173,175,177,179,181,183,185,187,189,191,193,195,196,198,200,
  202,204,205,207,209,211,212,214,216,217,219,220,222,223,225,226,227,229,230,231,233,234,235,236,237,239,240,241,242,243,243,244,245,246,247,248,
  248,249,250,250,251,251,252,252,253,253,253,254,254,254,254,254,254,254,255,254,254,254,254,254,254,254,253,253,253,252,252,251,251,250,250,249,
  248,248,247,246,245,244,243,243,242,241,240,239,237,236,235,234,233,231,230,229,227,226,225,223,222,220,219,217,216,214,212,211,209,207,205,204,
  202,200,198,196,195,193,191,189,187,185,183,181,179,177,175,173,171,169,166,164,162,160,158,156,154,151,149,147,145,143,140,138,136,134,131,129,
  127,125,123,120,118,116,114,111,109,107,105,103,100,98,96,94,92,90,88,85,83,81,79,77,75,73,71,69,67,65,63,61,59,58,56,54,
  52,50,49,47,45,43,42,40,38,37,35,34,32,31,29,28,27,25,24,23,21,20,19,18,17,15,14,13,12,11,11,10,9,8,7,6,
  6,5,4,4,3,3,2,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,4,4,5,
  6,6,7,8,9,10,11,11,12,13,14,15,17,18,19,20,21,23,24,25,27,28,29,31,32,34,35,37,38,40,42,43,45,47,49,50,
  52,54,56,58,59,61,63,65,67,69,71,73,75,77,79,81,83,85,88,90,92,94,96,98,100,103,105,107,109,111,114,116,118,120,123,125
};

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
}

void loop() {
  for (int i = 0; i < 360; ++i)
  {
    analogWrite(RED, sins[i]);
    analogWrite(GREEN, sins[(i+120)%360]);
    analogWrite(BLUE, sins[(i+240)%360]);
    delay(2);
  }
}

You should consider making it non-blocking :)
loop(){
   //if(millis() > previous+100){//uncomment this part to only do a step of the rainbow effect every 100ms
   rainbowEffect();
   //previous = millis();
   //}

   //you can do other stuff, like check a buttons' state here.
   //using the same structure as above, you can choose to give it a higher or lower priority.
}

unsigned char r,g,b;
void rainbowEffect(){
   if(r>254){
      r=0;
      g++;
   }
   if(g>254){
      g=0;
      b++;
   }
   if(b>254){
      b=0;
   }
   r++;
   ledStrip.set(r,g,b);
}

If you want to display every one of the about 16 million possible colours, you will have to nest your for loops like in this example:
x = 1 ;  // only for testing
for ( int redx = 0 ; redx <= 255 ; redx ++ ) {
    for ( int greenx = 0 ; greenx <= 255 ; greenx ++ ) {
        for ( int bluex = 0 ; bluex <= 255 ; bluex ++ ) {
             leds[ x ] = CRGB(redx,greenx,bluex);
             delay(wait_time);
             LEDS.show();
        }
    }
}

An alternative could be to use HSB or HSV instead of RGB, this way you can increase the hue over time to get the rainbow effect.

I think @Mazaryk was correct, HSV is the way to go for this.  RGB's 16+ million colors include brightness, and some of them just won't display on the strip, so I found a way to at least better fade thru:
int thissat = 255;           //- LOOPS DELAY VAR
int idex = 0;                //-LED INDEX
int ihue = 0;                //-hue (0-255)

void rainbow_fade() {
    ihue++;
    if (ihue > 255) {ihue = 0;}
    for(int idex = 0 ; idex < LED_COUNT; idex++ ) {
      leds[idex] = CHSV(ihue, thissat, 255);
    }
    LEDS.show();
    delay(wait_time);
}

You could take advantage that the rgb color could be represented in a unsigned long. And use a counter.
But have patience looping through 16 mio colors with 1ms at iteration take some time :-). (around 4-5 hours:  16581375/(1000[ms] * 60[m] * 60[h]) = 4,6 )
void loopThrougAllColors(){
  // The trick here is to use a unsigned long value as the color representation.
  // Each byte represent a color (except the first)
  //          none, R  G  B
  //          0x00 00 00 00
  // Note: static means it is a global variable - but only seen in thisfunction.
  static unsigned long ledColor = 0;
  static int ledIndex = 0;

  ledColor++;
  ledColor &= 0x00FFFFFF; /* Overflow preventing (instead of if sentence checking the boundaries). */

  leds[0] = ledColor;

  FastLED.show();
  FastLED.delay(1);
  //delay(10);
}

authors: Вячеслав Фалелюхин


text:
Laser emitter + receiver for Arduino (Arduino to Arduino communication)
I'm working on a project using 2 Arduinos connected to 2 computers to demo Serial to Serial communication.
We're using Arduino Uno connected to the computer via Serial and software serial for inter-Arduino communication. We used wires to connect software serial RX & TX lines, but we'd like to connect these pins to a laser transmitter and receiver.
We're trying to show wireless communication using an optical medium, which is why we wanted to use a Laser transmitter and receiver.
We're trying something like the setup in this YouTube video $3 laser transmits audio over 100m (Arduino)
Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?
Receiver: Laser Sensor Module non-modulator Tube Laser Receiver
Transmitter: 5V ... Board For Arduino AVR ... KY-008 Laser Transmitter

you can use a red or ir led to receive, or a phototransistor, all of which should give dozens of KHz.

Speed is likely to be limited by use of software serial instead of the laser link.  You might consider using Mega2560's (which have 4 UARTs) instead of Uno's

This particular receiver module is advertised as being "non-modulated" which means it is just a digital on/off indicator.  I can't find info on the latency in the circuit before it determines whether or not it can find the laser signal, so presume the speed will be very very slow.  You would be better off using just a LDR or something else other than this module.

@dandavis I tried feeding a square wave to an IR LED. I hooked up a photodiode (and resistor) to an oscilloscope. The rise times became too slow above 2kHz.

hook the LED to the oscilloscope (w/o resistor), and shine a laser into the led. you should get up to the forward voltage an a few microamps of current. "waterclear" LEDs work a lot better than diffused.many in series adds voltage; i used 3 flat ones in series as an opto-isolated mosfet driver (K-d, A-g, 10Mohm s-g).

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a low-pass filter. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of 1.6 kHz). I would recommend checking the actual components. The above is a guesstimate.
Cheers!

Possible. But the capacitor is connected across the supply terminals of the component, not the signal (I'm too sure about filters, just guessing). Wouldn't the capacitor need to be connected between signal and ground (with a series resistor) for it to be a filter? A person on Youtube used this sensor with a 115200 baud rate, but I'm not sure about the error rate he encountered.

authors: ΔΗΜΗΤΡΗΣ ΔΙΚΑΙΑΚΟΣ


text:
Why are there 3 crystals on the Mega2560 schematic?
I am a software engineer who is new(er) to electronics, I only started a couple of months ago. I've built a bunch of custom circuits, then some arduino nodes that are around my apartment that communicate with a C# server. So I've at least got the breadboarding part down.
So now I am working on a controller board that connects to my home automation system and determines the color on the LED light strips I installed into my bookshelf. So I want to transfer from working with pre-built Arduinos to building my own full node, there are some things I think I'm missing.
I've noticed that there are duplicate parts on the schematic for the Arduino Mega2560 schematic (such as there being 2 voltage regulators - one is replacement if the other is not available). I couldn't find any such description however for why there are 3 crystals located on the board. I see 3 different circuits for crystals (all of which are 16MHz).
Specifically, I am referencing the following

Maybe different options. The top one may be a ceramic resonator rather than a crystal. What's actually fitted on the board? The other one with XT1 and XT2 may be for the FTDI serial chip.

Where did you get that schematic? That is not from the R3 schematic on arduino.cc.

link

@jippie That's a good point, I will trace back XT1 to see if it comes from the FTDI. This brings up an additional question, why are the FTDI chip and the ATMega on different clocks?

@jippie there is no FTDI chip on the R3. It is an ATMega8U2.

A second crystal may be cheaper than sharing the clock between the two.

Also, you can't ideally share a crystal between two ICs, the two oscillation circuits would likely affect each other. You could have one connect to the crystal and then feed a buffered clock to the other, but that would cost an I/O pin.

A shame this was migrated; it is actually a very good general EE question.

One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.
The other two crystals are both for the ATMega2560. Why two? Basically they only populate one of the two, but they have two different footprints. One is for a surface mount resonator, the other for a through-hole crystal.
Having two footprints gives the option during assembly to go for the cheapest package at the time. It also means that the hobbyist can replaces the low accuracy resonator with a high accuracy crystal if their project requires.

As a side note, if you look at Y1, you will notice it is not the symbol for a crystal, it is of a resonator.

Awesome! I couldn't tell why the design was different. I am new to the hardware side of things, could you point me to where I could find some information on how resonators and crystals are different?

@clamport See thisEE.SE question and this PDF. Or just google "crystal vs ceramic resonator".

@NickAlexeev it does - look in the top right corner.


text:
NRF24L01+ how much supply ripple is acceptable?
I'm trying to get a simple TX/RX pair to work. I've got identical Nanos and I'm using the example from:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
I followed the advice about adding a cap across the Vcc GND on the nrf board, and added a 10uF electrolytic to both.
I still haven't received a packet yet, and I wondering how to eliminate the power supply as a cause. I scoped the power pins, and even without a cap I got about 250mV of ripple. With the cap it goes down to about 100mV. Is this within tolerance? What kind of caps does anyone else use, and has anyone scoped the result to see where the threshold lies?
Aside form that, are there any other clever ways to debug this issue?
Update 20160122. I finally tested using those cheap piggyback 3.3v regulator boards that plug straight into the nrf board. Works perfectly, not one lost packet over 5000 packets sent. Interestingly, the RX side appears to be the fussy one. Thanks to everyones' suggestions. For a total combined cost of about 4$ per node, I have a great wireless TX/RX solution.

Having two units too close to each other can cause problems. Either have them apart, or lower the transmit power.

If you have, try a bit bigger capacitors. Capacitors on my modules are 100uF and they work.

In the end I put a scope across a 10Ohm resistor in series with the nrf power leads to see what kind of current draw the TX was using, and also played with adding different caps. You're right, the recomended 0.1uF to 10uF doesn't seem to be enough. I get best results with a 470uF electrolytic. But I still get about 20% packet loss across my desk. And the voltage on RX side is very noisy. Both boards are being powered by the 3,3v nano on-board regulator. I've ordered some piggyback regulator board for the nrf so I'll test with those when they arrive.

20% packet loss? Whoa, what are you using to power the regulator? Have you tried decoupling the power supply even more?

Right now I'm using the Nano on board 3.3V reg for both T and RX. They are plugged into the USB port on my laptop. The TX side seems to be quite stable. The RX side shows lots of noise, with Vpp of about 100mV. Strangely, using PowerOff, delay and PowerOn to try to limit the current draw on RX doesn't seem to have any effect. Whereas decreasing the retries on the TX shows a corresponding decrease in power consumption. And 20% loss is my best so far. If I use a 10uF cap I often get no packets at all.

I would suggest using a different power supply, that appears to be your problem.  250mV is 1/4 of a volt, that is a lot of noise/ripple.  I am assuming it is ripple from the AC mains.  The series resister is way to large, try something about 0.1 ohm.  Also put a filter cap on the load side of the resister.  If you have high frequency noise add a 0.01 cap that will help.  Be sure the grounds between the units are solid.
Gil
I have a feeling it is narrow fast rising spikes.  If so the odds are very high it is the power supply.  Can you try an analog one and see if the problem goes away?  Try adding more bulk capacitance, at the rate of at least 1000uF per amp.

Thanks for the suggestions. The ripple is of a much higher frequency than mains hum. I'm collecting together a few ideas and I'll test them when the alternative power supplies turn up. I'm pretty sure it's the receiver that is having trouble. I'm also not ruling out interference from other traffic in that frequency.

@mjk It's also worth mentioning clone modules have worse receiving ability. Check if you have original modules, it might solve your issue.

Thanks for the info. I tested using the 3.3v regulated piggy back boards last night, and they worked perfectly.

@mjk So you've fixed your issue?

Yes, as far as I can tell, the issue lay int he power supply. I tried direct from the Arduino 3.3v regulator. I also tried an external 3.3v supply from a bench supply, and all sorts of variations of caps to filter ripple. Funny thing is, as far as I can tell, the piggy back board has the same 3.3v regulator as the arduino. Same package size at least, with a few smd caps. Yet the result is clear. for the extra buck, I'll be buying a piggy back board with each radio device. All I have to do now is test the range, but for my current app, I  only need <10m max.

The additional load on the 3.3V regulator may be putting it at its limit and causing it to oscillate.  By adding the additional regulator you did two major things, first you reduced the length of the power line from the regulator and took some load off the regulator on the Arduino.  I remember reading a while back that that and several other modules reach the current limit of the Arduino.  Your solution is a good one and should remain stable over time.


text:
Arduino as ISP with serial monitor for ATmega328
I have an ATmeg328 TQFP on a board (in system). I use an Arduino Uno as an ISP to programm the chip. However, i would like to use Serial Communication with the chip through the Arduino board.

Is this possible?
If yes, how can i realize this?

EDIT: i have the tx and RX pins not available. The chip is on a board. With through arduino board, I mean that I would like to use the miso mosi sck pins to do this.

What do you mean "through the Arduino board" exactly?

The target chip is connected via ISP to an Arduino Uno. I want to use serial monitor to display information from the target chip, but the chip's only connection is through the Arduino.

Sure, it is possible - you can readily build additional functionality into the Arduiono-as-ISP sketch to accomplish run-time communication with the firmware, potentially including bridging between SPI and asynchronous serial.  But you will have to decide for yourself what exactly is required, and come up with some scheme for switching the interface Arduino between ISP vs. communication-bridge mode.

Using an "FTDI cable" and bootloader may be a little more straight forward. Worst case you can set up the Arduino to act like an FTDI cable after you've burnt the bootloader.

Just burn the arduino bootloader to your tqfp. Then connect the tx and rx on the tqfp to the tx and rx on your arduino, and pull the reset line on the arduino low.
Downside is you have to do a manual reset on the tqfp before programming. If you have an Uno you could remove the atmega from the socket, and connect the reset on the uno to the reset on the tqfp.
Another option is to connect the TX on the tqfp to the TX pin on the Arduino using a resistor. But for this to work you have to modify the ArduinoISP sketch to make it release TX pin (UCSRnB &= ~_BV(UCSRnB);) and set it to input. And reverse it when data is received on the RX. Not trivial, and only works one way (tqfp to PC).

Thanks for the answer, but i don't want to use tx & rx pins

as here? Nick Gammon has a sketch which includes an ISP with serial control. Sketch is available on GitHub here

In addition to my previous comment-suggestion that you could implement communication over SPI by adding functionality to both the ISP sketch and the target program, it now occurs to me that another approach would be to implement software serial functionality on both, assigned to some of the pins used for ISP during that process.


text:
Open the Uart0 Serial Port on Intel Edison
I'll preface this buy saying I am very new to working with Arduino boards or hardware in general.
I am attempting to follow a tutorial on instructables
http://www.instructables.com/id/PCBot/step4/Printer-test/
I have my board and printer wired up properly and I have git cloned the python thermal printer. My issue begins at this paragraph:

Open the UART0 serial port
  by default the GPIO's of the edison are disables.
You can enable them by programming the edison via the Arduino IDE or by using the MRAA library available for several programming languages.
To open enable the UART0 port, TX RX on the edison breakout board, open a Python shell in the thermal and write:
import mraa
x=mraa.Uart(0)

I opened a python shell and entered the import mraa lines and tried to run the printertest.py
I receive an error that says no module named serial. I am not sure where the issue is. I thought the Edison already had python serial installed. I did try to install it with opkg install python-serial but it didn't work. If my issue is with enabling the Uart0 port I am not sure how to go about doing it. I have the Arduino IDE installed but I have no idea how to go about enabling it via the Arduino IDE. The instructions are a bit vague in that paragraph.
*Update I have successfully installed pip and got pyserial installed. Now when I try to run the printertest.py I get an error OSError: [Errno 2] No such file or directory: '/dev/ttyAMA0' which I think is potentially caused by me not succesfully opening Uart0 port but I am not sure how to. I tried adding the import in a shell as well as adding it directly to the code via nano

did you try with pip?

I tried to install pip but I got an error.

I suggest you paste the opkg error. Just as you describe the problem right now, it's hard to say much, without logs. Same as with pip: show how it fails.

I just found out I need unofficial repos to install pip so i'll try that next

I followed this blog to install pip on the edison http://blog.salvius.org/2015/05/installing-pip-on-intel-edison.html ; however, when I try to install pyserial with pip it says -sh: pip: command not found

@IgorStoppa here is the error from just trying to use opkg `root@edison:~# opkg install python-serial
Unknown package 'python-serial'.
Collected errors:

opkg_conf_parse_file: Duplicate src declaration (all http://repo.opkg.net/edison/repo/all). Skipping.
opkg_install_cmd: Cannot install package python-serial.`

how about the full list of repositories? did you check if it's configured as in your example?

Another - painful, for sure - way to install it, is to modify the list of components and rebuild the image. But I'd keep it as really last resort, as it is likely to take easily a couple of hours straight, if not more.

@IgorStoppa I might have to try reflashing the newest image. I don't notice any errors adding official or unofficial repos. The pip installation appears to have no errors.

I have solved the issues and successfully connected this printer with the Compute Module. I solved the issue by changing the target of /dev/ttyAMA0 to /dev/ttyMFD1 as shown by http://iotdk.intel.com/docs/master/mraa/edison.html . This was the final step after I had installed pyserial.


text:
Can pin mode damage Arduino with connected electronics?
I am not that experienced with electronics, so this might be a silly question. But I dont know. Assume that I have connected some electronic circuit (transistors, leds, anything else) to the Arduino pins, is there any chance that I damage the hardware if I change the pinmode to input? What role do the integrated pullup/pulldown resistors play? Basically, is it possible to create some "unintended" flow of current, that damages the board or external hardware, if I change the pinmode or disable/enable the pullup/pulldown resistors (or something else that I dont know about)? Can I break the hardware by programming mistakes?

yes ... if you change pinmode to output and set output level that causes large current to flow

General rule: connecting input to input or input to output is ok. Connecting output to output is bad and can kill electronics.

You are coming with some good questions about a complicated subject. You will be going through a learning process. If you do not violate the design parameters of the micro (voltage and current to name a few) you normally will not damage it. Knowing all of those parameters and what the circuirity surrounding the micro has a huge impact on your what can damage your micro and design. Without a schematic, this will change with each circuit and integration, it is impossible to give a definitive answer but I will take a SWAG.
Question: "is there any chance that I damage the hardware if I change the pinmode to input?"  and it depends on what mode the pin is in before you change it and what is connected to the pin. Generally you will not damage it assuming your voltages are equal to or less then the voltage supplying the microprocessor and the pin is not connected to an inductive component. You can get changes in your external hardware.
You ask "Can I break the hardware by programming mistakes?". Again I cannot give a definitive answer unless the circuit and what is connected is known. LEDs etc are generally no problem. If in doubt place a resistor in series with the load, something in the range of 330 to 500 ohms and see what happens. If you turn on some external device that damages stuff that is one possibility.
You ask: "if I change the pinmode or disable/enable the pullup/pulldown resistors..."Probably not but it depends on what is connected to the pins. Generally if the pull up resistors are needed such as for a button turning them off will cause some intermittent problems where it is on then off but that will not damage the micro, the effect on external devices is unknown as are the devices.
This stuff is not going to be assimilated in a few days but over a much longer period. There is always more then one way to do a project, the best is probably what you decide. You will make mistooks, and possibly destroy some of your Arduinos, this is to be expected, that is why I have spares. The most important part of the process is to enjoy and have fun.


text:
Arduino Adafruit playground: Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory
I've tried installing the Arduino Adafruit playground but came across the same error.
sketch\src\Libraries\Adafruit_Circuit_Playground\utility\Adafruit_CPlay_LIS3DH.cpp:27:35: fatal error: Adafruit_CPlay_LIS3DH.h: No such file or directory

 #include <Adafruit_CPlay_LIS3DH.h>

                                   ^

compilation terminated.

exit status 1

I don't really know what else I can try. I've tried reinstalling the library and
different versions of the Arduino IDE but is doesn't seem to work.
IDE version: 1.8.7
Playground version: 1.8.1

the error start with "sketch\src". where is your "Libraries" folder located?

Sorry completely forgot about this post. Apparently I had a folder in my project with the playground library that wasn't updated. When I removed this folder everything worked fine.


text:
Updating ESP32 firmware from another ESP32 over USB, similar to how esptool.py works
Is there a way to update the firmware on one ESP32 from another ESP32 over USB, similar to how firmware can be updated using esptool.py?
This would essentially be like a port of whatever magic esptool.py uses over USB to update an ESP32, but instead of running through Python it would be an Arduino C++ sketch and would read the firmware to write to the other ESP32 from SPIFFS.

since ESP32 doesn't have an USB peripheral on chip, a better idea would be to that over the UART. did you research before asking? did you find something? did you try something?

Thanks for sharing your opinion, @Juraj.  However, all of the ESP32s that I am working with include a CP2102 USB to UART bridge.

can CP2102 act as USB host? no.

That's a great point, @Juraj

you know that you can use OTA upload?

Espressif has an official library. Here's the link:
https://github.com/espressif/esp-serial-flasher
Personally, I recommend this GitHub repository named "FlashBox - Esp32 serial flasher" by Machiel80. Here's the link:
https://github.com/Machiel80/esp32-serial-flasher
it has good documentation and even a video on YouTube explaining how it's done.
Finally, the flipperZero project also has a serial flasher project on Github, the "flipperzero-esp-flasher". Here's the link:
https://github.com/0xchocolate/flipperzero-esp-flasher

You can use the SD card to update the firmware.
Here is the example code


text:
Transmit IR-Signal A, Receive IR-Signal B
I used the following program to send an IR code and I got the an unexpected result as below:
/*
   IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
   An IR LED must be connected to Arduino PWM pin 3.
   Version 0.1 July, 2009
   Copyright 2009 Ken Shirriff
   http://arcfn.com
*/

#include <IRremote.h>

IRsend irsend;

int j = 0;
void setup()
{
}

void loop() {
  for (int i = 0; i < 3; i++) {
    irsend.sendNEC(0xFF6897, 32);
    delay(40);
    j = j + 1;
  }
  delay(5000); //5 second delay between each signal burst
}

With the following schematic:

I expected to receive:

FF6897 Decoded NEC: FF6897 (32 bits) Raw (68): 8750 -4450 550 -550 500
  -600 550 -550 550 -550 550 -550 550 -600 500 -600 500 -600 500 -1650 550 -1650 550 -1650 500 -1650 550 -1650 550 -1650 500 -1700 500 -1650
  550 -550 500 -1700 550 -1600 550 -600 500 -1650 550 -600 500 -600 500
  -600 500 -1650 550 -550 550 -600 500 -1650 500 -600 500 -1700 500 -1650 550 -1650 550

Instead I receive consistently

C101E57B Unknown encoding: C101E57B (32 bits) Raw (68): 8850 -4450 500
  -650 450 -600 500 -600 550 -550 500 -650 450 -650 500 -600 450 -650 450 -1800 450 -1700 500 -1750 500 -1700 500 -1750 500 -1700 500 -1750
  450 -1750 500 -600 500 -1750 450 -1750 500 -600 450 -1750 500 -650 450
  -600 550 -600 500 -1700 500 -600 500 -600 500 -1750 500 -600 500 -1700 500 -1700 550 -1700 450

anyone knows how to fix this?
Code the Reciever uses to decode the just send signal:
/*
 * IRremote: IRrecvDump - dump details of IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
 * LG added by Darryl Smith (based on the JVC protocol)
 */

#include <IRremote.h>

/*
*  Default is Arduino pin D11.
*  You can change this to another available Arduino Pin.
*  Your IR receiver should be connected to the pin defined here
*/
int RECV_PIN = 6;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void dump(decode_results *results) {
  // Dumps out the decode_results structure.
  // Call this after IRrecv::decode()
  int count = results->rawlen;
  if (results->decode_type == UNKNOWN) {
    Serial.print("Unknown encoding: ");
  }
  else if (results->decode_type == NEC) {
    Serial.print("Decoded NEC: ");

  }
  else if (results->decode_type == SONY) {
    Serial.print("Decoded SONY: ");
  }
  else if (results->decode_type == RC5) {
    Serial.print("Decoded RC5: ");
  }
  else if (results->decode_type == RC6) {
    Serial.print("Decoded RC6: ");
  }
  else if (results->decode_type == PANASONIC) {
    Serial.print("Decoded PANASONIC - Address: ");
    Serial.print(results->address, HEX);
    Serial.print(" Value: ");
  }
  else if (results->decode_type == LG) {
    Serial.print("Decoded LG: ");
  }
  else if (results->decode_type == JVC) {
    Serial.print("Decoded JVC: ");
  }
  else if (results->decode_type == AIWA_RC_T501) {
    Serial.print("Decoded AIWA RC T501: ");
  }
  else if (results->decode_type == WHYNTER) {
    Serial.print("Decoded Whynter: ");
  }
  Serial.print(results->value, HEX);
  Serial.print(" (");
  Serial.print(results->bits, DEC);
  Serial.println(" bits)");
  Serial.print("Raw (");
  Serial.print(count, DEC);
  Serial.print("): ");

  for (int i = 1; i < count; i++) {
    if (i & 1) {
      Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
    }
    else {
      Serial.write('-');
      Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
    }
    Serial.print(" ");
  }
  Serial.println();
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    dump(&results);
    irrecv.resume(); // Receive the next value
  }
}

Schematic wise:
one IR reciever with VCC and Ground connect and signal-out on pin 6

I Use a seperate arduino for that. It has an IR transmitter and an example sketch loaded.

What is the value of the voltage Vcc on the infrared transmitter circuit?

Possible duplicate of Arduino emits signal A (infrared) but another Arduino receives everything but A (IR-LED problem)

Eventho I did ask that question a two months ago and came across a similar problem. There is one key diffrence. Back then the signals where never ever constant. I never recieved the same IR-signal twice. Now after some changes and I dont know which made it so :). I get very consistant signals. Step closer to my goal.

The Vcc is connect to 5v on the arduino. I can check later today if this really is 5v

@Anton van der Wel: Show us the receiving half: Schematic and code. It will be sooo much easier to find where the problem is.

post updated aswell @AltAir I tested the voltage over the IR-LED  it was 1.7 V

In the received RAW codes, the width of the modulated pulses is less than the expected value. And the width of the spaces is bigger than expected.
This is due to the lack of an infrared sensor.
Use infrared receiver another model. For example TSOP4838.
Or try reducing MARK_EXCESS in the IRremoteInt.h of the Arduino-IRremote library from 100 to 50 or 0.
...
// Pulse parms are ((X*50)-100) for the Mark and ((X*50)+100) for the Space.
// First MARK is the one after the long gap
// Pulse parameters in uSec
//

// Due to sensor lag, when received, Marks  tend to be 100us too long and
//                                   Spaces tend to be 100us too short
#define MARK_EXCESS    0
...

And please increase the delay time in transmitter sketch (to avoid codes overlapping) :
...
for (int i = 0; i < 3; i++){
  irsend.sendNEC(0xFF6897, 32);
  delay(200);
  j = j + 1;
}
...

I changed the delay, still gives the same output as described in my post ;/ (C101E57B)

myReceiver.markExcess= 100;  gives me the exit status 1 'class IRrecv' has no member named 'markExcess'  so is my libary missing something?

@Anton van der Wel, in the previous question, you used the IRLib2 where the parameter is used. I updated my answer according to the library you are currently using.

sadly it didnt make a diffrence. Tried both 50 and 0 both send C101E57B. as IR reciever Im using VS1838B

Please, try to change tolerance to 30 or 35 in IRremoteInt.h #define TOLERANCE0       30 .

also didnt change the output ;/

@Anton van der Wel, you are using an LED without a limiting resistor.  This can lead to overload and distortion of the signal. Also, nothing is known about the infrared receiver and how it is connected to the power supply.

The IR reciever is connected to the 5v pin on an arduino the ground to the ground next to the 5v pin and the Output pin to pin 6 on the arduino. how to not overload the LED?


text:
ESP8266 + NeoPixel - Cannot set pixel color, I got "Exception 29: StoreProhibited"
I'm trying to use NeoPixel on the ESP8266.
I made simple test put all required code into setup() and loop() methods. Then, to keep everything in order I create a class LedModule which handle the led strip state, changes, etc.
Here some parts of my class
LedModule::LedModule(unsigned int numOfPixels, uint8_t dataPin)
{
    // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
    // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
    // example for more information on possible values.
    pixels = Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

    mState = LED_MODULE_STATE_IDLE;
    mIsLedStripOn = false;
}

...

// The method to set all leds of the strip to the same color
void LedModule::turnAllNeoPixelsTo(uint8_t red, uint8_t green, uint8_t blue)
{
    for (uint16_t i = 0; i < getLedCount(); i++)
    {
        // Avoid to light up the middle leds
        if (i < 5 || i > 9)
        {
            pixels.setPixelColor(i, red, green, blue);
        }
        else{
            pixels.setPixelColor(i, 0,0,0); // off
        }
    }
    pixels.show(); // This sends the updated pixel color to the hardware.
    mIsLedStripOn = true;
}

After this changes, when I call the method above, I got the exception:
Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
Decoding 15 results
0x4020ddbd: ieee80211_send_mgmt at ?? line ?
0x4020db5f: ieee80211_send_mgmt at ?? line ?
0x40102864: trc_NeedRTS at ?? line ?
0x4020fe6d: ieee80211_sta_new_state at ?? line ?
0x402101ab: ieee80211_sta_new_state at ?? line ?
0x4021060f: sta_input at ?? line ?
0x402109cb: ieee80211_parse_wmeparams at ?? line ?
0x402103ab: sta_input at ?? line ?
0x40204ce3: pp_tx_idle_timeout at ?? line ?
0x40204607: ppPeocessRxPktHdr at ?? line ?

It seems to crash during the pixels.setPixelColor(i, red, green, blue); method.

What is pixels?

instance of Adafruit_NeoPixel library object. I updated the class code above.

I don't like your method of constructing. I think you need a new in there and make it a pointer

I used the sample coming from the library. You can find it here: https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library

That is completely different, sorry.

pixels = Adafruit_NeoPixel(...) creates a local variable (an rvalue) then copies it to the class member. If Adafruit_NeoPixel does not have a proper operator= problems may arise.

Your "constructor" isn't doing what you think.
In the example you point to you have, efectively:
Class object = Class(parameters);

Whereas in your code you have:
Class object;

object = Class(parameters);

In the first form it results in a new object constructed at declaration time. In the second it first creates a new "empty" object and then at a later date tries to copy a newly constructed object into it - which may be failing if the class doesn't support copying.
Instead you should be working with new and pointers.
In your class definition you create a pointer to your Adafruit class:
private:
    Adafruit_NeoPixel *pixels;

Then you create a new object pointing to it:
pixels = new Adafruit_NeoPixel(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800);

Accessing it is then done with -> instead of .:
pixels->setPixelColor(i, red, green, blue);

Another option (to avoid new) would be to use the initializer list: LedModule::LedModule(unsigned int numOfPixels, uint8_t dataPin) : pixels(numOfPixels, dataPin, NEO_GRB + NEO_KHZ800) {...}

Yeah, I thought of suggesting that, but it can get a bit awkward with the Arduino API and the order things get initialized. I find it's best in general to do things in begin() rather than with constructors. Besides, there's no harm in using new in this situation.

Another option would be to extend the NeoPixel class creating a child class that adds more functions to it.


text:
ESP8266 EEPROM seems not working, saved data are different when I try to read them
I'm working on project which require to save some data into the EEPROM.
As I read online the ESP8266 has no real EEPROM, it use a section of FLASH just after the SPIFFS. Due to this read/write is quite different from standard Arduino, you need to call EEPROM.commit(). You also have to call EEPROM.begin(size) (I used size = 512) before start to use it.
I follow different tutorials online and I made some tests but it seems not working at all. When I try to save a value and then read it, values are different. I tried with
EEPROM.write(..)
...
EEPROM.read(..)

and with
EEPROM.put(..)
...
EEPROM.get(..)

but nothing change.
Is there any configuration on the board I need to set into Arduino IDE/Board Configuration?
EDIT: here's the code
void setup()
{
    Serial.begin(9600);
    Serial.println();

    EEPROM.begin(512);
    EEPROM.write(0, 62);
    EEPROM.write(10, 103);
    //EEPROM.commit();
    EEPROM.end();
    Serial.print("Read at 0:"); Serial.println(EEPROM.read(0), DEC);
    Serial.print("Read at 10:"); Serial.println(EEPROM.read(10), DEC);
}

I always read 0 in the output.

why not just use SPIFFS? it's way simpler, far larger, and better organized.

@dandavis I only need to store a few bytes, use a file system seems too much 'expensive' to achieve this simple task.

It's not that expensive, and in fact, it has wear-leveling, which is (potentially) a huge long-term reliability benefit, especially when most of your blocks will be empty. It's not really a full file system, there's not even paths (just names), so it's more a fast key/value store of it's own right. I would try it and see if it bogs down your project; I can't image it would be much worse than EEPROM unless your doing something that will wear out either...

you can read only between begin and end. it works with memory image. begin allocates the in-memory image. commit writes it to flash. end commits and deletes the memory image

@Juraj thanks a lot! For me it's the best answer. It works and now I understande the reason. Btw it is not very well documented this procedure.

You can read the emulated EEPROM only between begin and end. It works with memory image.

begin allocates the in-memory image.
commit writes it to flash.
end commits and deletes the memory image.

Here is some ESP8266 example code to store and read strings from EEPROM data:
#include <EEPROM.h>

void writeString(char add,String data);
String read_String(char add);

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

  EEPROM.begin(512);  // Note::

  String data = "Hello World";

  Serial.print("Writing Data:");
  Serial.println(data);

  writeString(10, data);  //Address 10 and String type data
  delay(10);
}

void loop() {
  // put your main code here, to run repeatedly:
  String recivedData;
  recivedData = read_String(10);
  Serial.print("Read Data:");
  Serial.println(recivedData);
  delay(1000);
}

void writeString(char add,String data)
{
  int _size = data.length();
  int i;
  for(i=0;i<_size;i++)
  {
    EEPROM.write(add+i,data[i]);
  }
  EEPROM.write(add+_size,'\0');   //Add termination null character for String Data
}

String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len=0;
  unsigned char k;
  k=EEPROM.read(add);
  while(k != '\0' && len<500)   //Read until null character
  {
    k=EEPROM.read(add+len);
    data[len]=k;
    len++;
  }
  data[len]='\0';
  return String(data);
}


text:
Which interrupts are enabled when programming an ATTiny85 with Arduino IDE?
I have programmed a tiny85 using the Arduino IDE. I am using the pulseIn() function. Wrapping it in noInterrupts()/interrupts(); appears to make the function more consistent. This would imply that interrupts are running.
Which interrupts are running? Can I disable them?
I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.
(I know I can improve the code by not using pulseIn and using interrupts, however the question I have at the moment is which interrupts are running when I am not explicitly enabling any.)

It could depend on the arduino core you're using for the ATTiny. As there are multiple, and there is not one present in the default IDE (afaik).

The only interrupt that is always running is the one which generates the count for millis() and micros(). Disabling interrupts disables your ability to keep track of time and use delay().
Timer interrupts are also used by the tone() function and for sending / receiving serial data if the chip has a UART.
Disabling interrupts would also affect the use of external interrupts and pin change interrupts should you be using them.
It sounds, from your brief description, that you would only be effecting the use of millis() and delay() since you aren't using the other systems that use interrupts at all.

After more reading it states that the pulseIn() requires interrupts, this is a bit strange. I would not expect to see an "improvement" doing what I am doing. Perhaps the tiny85 implementation is different than the standard one. If timing is available I would expect pulseIn to use it, as the description implies, and therefore require interrupts to be enabled. What you describe makes a lot of sense, I will recheck my findings.

pulseIn() function has got a very high accuracy, to the level of us (microseconds), which millis() function has obviously not. This is why pulseIn does not use it. Note that even micros() does not offer high precision, despite its name.

Which interrupts are running?

It depends on your code which you haven't shown. The Timer 0 overflow interrupt is usually active, as that lets the library count when a millisecond is up (roughly).
If you have done a Serial.begin then serial interrupts would be active. If you have used the I2C library (Wire) then I2C interrupts would be active.
(Disclaimer: That really refers to the Atmega328P. I'm not quite so sure on the ATtiny, it would depend on what the libraries do).

Can I disable them?

If you want to. Doing noInterrupts() is the simplest way. Note that if you disable interrupts for more than a millisecond (approximately) then the time returned by millis and micros will be wrong. Plus delay won't work. Plus you won't be able to serial print properly or at all.

I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

That is exactly what it does. Once activated the hardware timers can generate a PWM signal purely in hardware.

There are other ways of timing intervals (than pulseIn). One method is to use one of the other timers, configured with a small, or no prescaler. Then you can measure up to very high accuracy. I have examples of that on my page about timers.
(The ATtiny85 only has two timers, so you couldn't use the second timer for measuring and do PWM output with it, however you can use Timer 0 for the PWM output). That limits the PWM frequency to its default, however you could still alter the duty cycle)


text:
Where is Arduino.h on a Mac? Can I download a copy if missing?
I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.
If it is built in to the tools can I download a copy of this file(s)?

On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.
You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.
You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under hardware/arduino/avr
On your Mac you may find them as /Applications/Arduino.app/Contents/Resources/hardware/arduino/avr or somewhere similar (not entirely sure where it puts it within the app).

I found them in Contents/Java/Hardware/arduino/avr/cores/arduino. I was able browse them in finder as I think I have MAC dev tools installed.

I copied all the files with Android.h. As suggested I then needed the tools file too. stdlib.h etc. I rummaged around and found these too. I want them for syntax checking only so not 100% bothered if they are the correct ones. I'm building for AVR platforms.

Generally, if you need to find a file you can open a terminal and type
locate myfile.dat

This looks in a database (rather than searching the disk), which you may need to update by typing
sudo updatedb                       // on linux
sudo /usr/libexec/locate.updatedb   // on Mac

There simply is no "Arduino.h" file. Basically there are multiple platforms (the most common in Arduino world is the Arduino AVR platform). Each platform can contain multiple cores (but mostly only contains 1) and each core contains a "Arduino.h" file.
So to find the Arduino.h file you need to identify the board. The board gives you the platform and the core. Based on those the Arduino.h file is in the folder [platform installation folder]/cores/[core].
The [platform installation folder] is dependent on how the platform was installed on your system. For instance arduino avr comes with the Arduino IDE and as such it is installed in the app like majenko explained.
If it is installed by the boards manager on Linux, the Arduino IDE uses ~/.arduino15/packages/[provider]/hardware/[architecture]/[version] and if I'm not mistaken the same location is used on Mac.
You can also point to a folder location where additional hardware is installed.
A word on Eclipse and Arduino. There are quite a few options to run compile Arduino sketches in Eclipse. Depending on the tool it goes from easy to pretty complex.
I personally advise to use Sloeber from sloeber.io as I am the developer.

I've don't have a Mac, so I can't test this, but on the Arduino Forum they say find the file Wiring.h and create an empty file called Arduino.h in the same folder.
I don't know if that's the right approach, but it should get you to the next error, which may well be some system constant is not defined. If it does work you could go to github for the IDE (don't know exactly where that is) and download Arduino.h from there and stick it alongside Wiring.h.


text:
Explanation of the formula of the map funtion
Can someone please explain (mathematically) how the formula for the map function actually came to light?
I have given the code of the map function below. You can see that it uses a formula to "map" values in a given range from a certain range. I don't quite understand how it came (not good at maths) :| So, I would like an explanation to how this formula came to light.
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

X is your value. in_min is the minimum value of X. If you subtract that minimum value from X you re-map X into the range it can be.
For instance if X can be between 10 and 20 the in_min would be 10 and in the in_max would be 20. X will be somewhere between the two. Say X is 14. So X is 4 more than the minimum, or X - in_min = 4.
That gives you how far (in quanta of X) into the range you are.
out_max - out_min gives you the range of the output in the same way. If you want to map to 200 to 300, say, the range between the two is 100.
The same with in_max and in_min - it gives the size of the input range - 10 in this case (20 - 10 = 10).
So you now have some values:

4 is how far through the input range you are
100 is how big the output range is
10 is how big the input range is

Multiply the first two together and divide by the third and you get how far through the output range the input is. You could also do it the other way around - divide the input offset (4) by the input size (10) to get the percentage (in the range 0 to 1) that you are through the input. Multiply that percentage by the size of the output range to get how far through the output you are. The way it is done avoids the use of any floating point values which makes it faster.
So 4 * 100 = 400. 400 / 10 = 40.  Or, 4 / 10 = 0.4, 0.4 * 100 = 40.
Then you just add to that the output minimum values which just gives it an offset.  40 + 200 = 240.
Thus:
map(14, 10, 20, 200, 300) == 240.

To reiterate the steps:

14 - 10 = 4 (input offset)
20 - 10 = 10 (input range)
300 - 200 = 100 (output range)
4 * 100 = 400 (percentage of input range
400 / 10 = 40 applied to output range)
200 + 40 = 240 (add output offset)

map() implements linear interpolation.

In mathematics, linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points.


text:
NRF24L01+ unable to receive data
I have 2 Arduino UNO R3 nodes communicating using NRF24L01+ transceivers with the TMRh20 library.
Setup I have original as well as cheaper but 'compatible' arduinos. One of the nodes uses an original arduino Uno whereas the other uses the cheaper one.
Observation

The node with the cheaper Uno can transmit data (sucessfully received by the other node) but is unable to receive data.
I have a number of Rf modules and UNo boards. The observation is similar across.
Using the same configuration (rf module, connection and code) , the original uno board receives data but noot the other types.
Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem?

This article mentions something that I could not get but am suspicious of it being a possible direction to the solution to the problem, only if someone could help.

On Arduino UNO boards SPI pins are connected with some digital pins. While using modem you most remember that these digital pins won't be available.

The code was taken from here http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-ExampleSketches#bm1

Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem? - Big silver can? That's for the USB interface only. 16MHz for an ATMega16U2 (or whatever, I can never remember the silly numbers) and 12MHz for a CH340.

Although having read that somewhere already, not quiet sure if that wouldn't affect the SPI or anything to do with my setup, hence brought it out again. Thanks

No, that crystal has no connection to the main MCU at all.

@Majenko: Thanks. any insight on anything other that might help me with my problem.

Are you using the one of the library examples? Which one? No changes made to it at all? You're using hardware SPI i.e. pins 10, 11, 12, 13?

Yes, did use the library examples with pins 7, 8, 11, 12, 13. Pins 7, 8 (CE,CSN) are user configurable.

As it turns out, the culprit was the power supply on the board.
The clone came with AMS1117 based regulator for the 3.3V which it did indeed generate (3.27 measured). Using it, the reception of the RF device failed (although it could transmit data). Also had 10uF and a 0.1uF capacitor hooked up in parallel to Vdd and Gnd of the NRF24L01+, as recommended. I therefore suspected something to do with the SPI configuration.
Finally, having powered the 3.3V to the Rf device from another genuine Arduino solved the problem. Not sure if it was the 3.3V rail from the clone possibly having excessive noise which may be causing the issue, as I did not see a reasonable drop in 3.3V output of the clone while in operation.


text:
Help! Interfacing LCD with Arduino using 8255A Intel peripherals
I'm new to all this stuff and for the past two days, I have been trying to interface a 16x2 LCD to an Arduino Uno using an Intel 8255A component without any luck. The problem is, how can I attach or set the LCD's pins <> to the unknown pins of the 8255A.
Is it even possible?
Thanks for any kind of help.

8255!!!! Where did you find it?!?!

haha from this https://www.google.com/search?q=8255A+intel&biw=1366&bih=640&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjLp5aD3qLMAhXsJZoKHRJrBUMQ_AUICSgD#imgrc=KVpfZFZBqOuJlM%3A

What are unknowing pins?

i'm talking about the i/o of 8255 component, they are unknowing for Arduino IDE, how can i make them as inputs for LiquidCrystal lcd(12, 11, 5, 4, 3, 2),  this is my problem :/

@HamzaTST i meant where you found the actual component. I haven't seen one, much less used one, since 1985!

also, why are you bothering with the 8255 and not driving the display directly with the arduino pins? Do you plan to connect it on some other system, such as an intel 8085? :)

yes this is why, because i have much less pins to connect such LCD and some others component, you have an idea @JayEye ;)

I'd use something like a Teensy 3.2, it has 30+ gpio pins, and much easier to come by than the 8055 (again, unless you want to attach this to some retrocomputing project).

Thanks @JayEye for your advice, this is what im gonna do :)

You will not be able to use 8255 pins as parameters to the the LiquidCrystal library without making substantial changes to either the library or the Arduino core.
The reason is that to configure or change a pin on the 8255, you will need to go through a series of operations manipulating the ATmega pins to which the 8255's microprocessor bus interface is connected.  You can learn about the necessary operations by reading the 8255 data sheet.  Also keep in mind that the 8255 does not have per-pin configuration - rather, the first two ports must each be either entirely inputs or entirely outputs, while there third port can be split in half.
Once you know how to set a pin, you will need to have the liquid crystal functionality trigger these operations.
One approach would be to create a heavily modified version of the library which knows how to work through the 8255.
Another would be to create a modified version of the Arduino core which has additional pin numbers corresponding to the 8255's pins, and generates code which does the necessary intermediate bus operations to access them.  However this will be quite challenging - you have to make sure the intermediate code gets in there in all paths, and figure out how it will handle cases where code tries to set pins that must have the same mode to conflicting modes.
As others have said, you would practically be better off using a different MCU with more I/Os - either an Arduino Mega, or one of the ARM-based boards.

Thanks @Chris Stratton for your advice, this is what im gonna do :)


text:
Combining code for multiple sensors in one program
I need to operate 2 different sensors (gas and temp) simultaneously.
I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.
Here are the sketches:
Thermistor code:
void setup() {
  //This function gets called when the Arduino starts
  Serial.begin(9600);
  //This code sets up the Serial port at 9600 baud rate
}

void loop() {
  //This function loops while the arduino is powered
  int val; //Create an integer variable
  val=analogRead(0);
  //Read the analog port 0 and store the value in val
  Serial.println(val);
  //Print the value to the serial port
  delay(1000);
  //Wait one second before we do it again
}

This is the gas detector code:
/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int sensorPin = A0;
// select the input pin for the potentiometer
int DOPin = 2;
// select the pin for the LED
int sensorValue = 0;
// variable to store the value coming from the sensor
int ledPin =13;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(DOPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.print("Analog Output = ");
  Serial.println(sensorValue);
  // turn the ledPin on if triggered
  if (digitalRead(DOPin) ==HIGH) {
    digitalWrite(ledPin, LOW);
    Serial.println("Digital Output = OFF");
  } else {
    digitalWrite(ledPin, HIGH);
    Serial.println("Digital Output = ON");
  }
  delay(1000);
}

I want the arduino code for display this
"AutomatedCar Parking With Empty Slot Detection"

You just need to assign the sensors different pins.
/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int gasSensorPin= A0; // GAS sensor pin
int DOpin= 2; // select the pin for the LED
int gasSensorValue= 0; // variable to store the value coming from the sensor
int ledPin = 13;

int tempSensorPin = A1;  //Temperature sensor pin
int tempSensorValue;

void setup() {
 // declare the ledPin as an OUTPUT:
 pinMode(DOPin, INPUT);
 pinMode(ledPin, OUTPUT);
 Serial.begin(9600);
 }

void loop() {
 // read the value from the sensor:
 gasSensorValue= analogRead(gasSensorPin);
 Serial.print("Analog Output = ");
 Serial.println(gasSensorValue);
 // turn the ledPin on if triggered
 //
 if (digitalRead(DOpin) == HIGH){
 digitalWrite(ledPin, LOW);
 Serial.println("Digital Output = OFF");
 }
   else {
     digitalWrite(ledPin, HIGH);
     Serial.println("Digital Output = ON");
  }

Serial.print("Temperture: ");
tempSensorValue = analogRead(tempSensorPin));
Serial.println(tempSensorPin);  //Print the value of pin A4

delay(1000);
}

This is your combined sketch.

I know that, and I did that. My problem is how can I put both in one program, upload it to the device and run it together.

Upload the code from my answer and attach your temperature sensor to pin "A1"


text:
How to restart USB subsystem?
I'm developing on the Arduino platform (ESP8266 with USB -> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.
As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.
I'm using Mac OS X Sierra.

Is that the same problem that was being reported here?

I'm using a USB to serial converter, not an Arduino board. Also, the device disappears from /dev/cu.SLAB_USBtoUART and not even a USB drive can be connected from that point on.

I see you asked the question here: https://apple.stackexchange.com/questions/295993/how-to-restart-usb-subsystem and they sent you to Arduino.SE. Did you try the USB Prober.app?

You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.
If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.
What can you do? Well, two things:

Use an adaptor that requests enough current for your needs (may be hard to find)
Power your circuit separately using another power source.

Of the two I would suggest external power.

Thanks, I'll try your suggestion and come back with the result.

You're probably thinking of kext[un]load.
sudo kextunload /Library/Extensions/SiLabsUSBDriver.kext
sudo kextload /Library/Extensions/SiLabsUSBDriver.kext