text:
How do I control arduino uno multiplexed digital pin (using HC74595)
Edit:
I moved the whole initial post to avoid misunderstanding and confusing everyone, sorry
after all the reading i came up with this:
this is my code for ultrasonic sensor that going into digital pins in my arduino:
int trigPin1=2;
int echoPin1=3;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

  Serial.print (distance1);
  Serial.print (",");
  delay(100);
}

and this is the idea i wrote to set the "extra digital outputs" on the 595 chip:
int DS_pin = 8;
int STCP_pin = 9;
int SHCP_pin = 10;

void setup()
{ // put your setup code here, to run once:
  pinMode(DS_pin, OUTPUT);
  pinMode(STCP_pin, OUTPUT);
  pinMode(SHCP_pin, OUTPUT);
  writereg();
}

bool registers[8];

void writereg()
{
  digitalWrite(SHCP_pin, LOW);

  for (int i = 0; i<=7; i++)
  {
    digitalWrite(STCP_pin, LOW);
    digitalWrite(DS_pin,registers[1]);
    digitalWrite(STCP_pin, HIGH);
  }
    digitalWrite(SHCP_pin, HIGH);
}

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

}

now if you guys have a little time to check it, and tell me what should i wrote so the ultrasonic sensor will be working with the 595 chip's outputs?
Let say im going to put the Trigger pin into Q0 and Echo pin into Q1
thanks in advance

Can you clarify what you mean by "the extra slot"? What extra slot?

by extra slot i mean extra digital input, because im running out of digital input on the actual board, so i've been searching and found out that you can pull "extra" digital input with multiplexing it using IC - HC74595

You mean outputs, right?  As in "extra digital output" as the 74HC595 has 8 digital outputs.

Yes sir, output, my bad

i want to use the extra slot from HC74595 - what extra slot on the HC74595? im running out of digital input on the actual board - what "actual board"? Can you post a schematic?

@Nick Gammon, sorry for the confusing words nick, simply saying is i want to use the extra output from the 74HC595, but i dont know how to abstract them to the code. - Actual board means the arduino uno.

See my post about the 595 chip

Let say im going to put the Trigger pin into Q0 and Echo pin into Q1 -- The echo pin connects to an INPUT on the Arduino. Q1 (and all the pins on the 595) are OUTPUT pins. That can never work. Ever. Time to rethink your requirements.

It is good that you are thinking of abstraction in order to simplify programming.  Simplifying programming by using familiar names makes it easier to understand the code.
In your example:
int triggerPin=2
pinMode(triggerPin, OUTPUT)

..you are abstracting the actual pin used to trigger the ultrasound by calling it by a familiar name "triggerPin".  You could have just as easily wrote the same code as:
pinMode(2, OUTPUT)

Now you are asking how to abstract the pins when connecting the Arduino to the 74HC595.  The truth is, you don't have to.  But to make it easier to write & read the code you can use what ever names make sense to you.  In this example of connecting an Arduino to a 74HC595 there are 3 Arduino pins connected to the 74HC595.  They called them "dataPin", "latchPin" and "clockPin".  If these make sense to you use these names.

Add: can i address the output like this?
 #define LED_PIN     Q1

No, nothing knows what "Q1" is.  Remember, you are adding this hardware to the Arduino.  So nothing, not the compiler nor a library, knows about the hardware you added let alone a pin called Q1 on the added hardware.
First you need to understand how to set Q1 through Q8.  Refer to the 74HC595 Arduino tutorial linked to above.  Inspect the example programs.  Once you understand how to set / un-set Q1 through Q8, you can decide if you what to simply shift out a number or if you want to use abstraction giving names to the shift register output pins.
If I were only writing patterns, for example lighting up 8 LEDs, I would stick to numbers. However, if I were controlling different things, for example a light, a motor & a buzzer, I would assign each a unique name and build my program around the names.

@Mahardika, if this is what you were asking about great.  If you want to go further and ask about the output pins of the 74HC595, re-word or add-to your question to make it clear what you want.

this is all making more sense to me, and for others who viewed this question haha.. thank you!

This all makes a lot of sense. But I don't see where "extra slot" comes into it.

Yes, I think Mahardika meant to say "extra output".  It did occur to me to edit the Question to make things clearer.


text:
ESP8266 doesn't respond to Serial.println("AT")
If I don't declare Serial.begin(115200), I can send AT commands over serial monitor and it replies me.

But when I declare Serial.begin(115200) and send AT commands inside program or serial monitor there is nothing happens.

Did I miss something?

Just copy-paste the code/output. Don't post screenshots.

But I'm not answer to someone. You don't need the codes.

You have connected the tx of the Arduino to the tx of the ESP8266 and the rx of the Arduino to the rx of the ESP8266.
What is happening when you type AT in the Serial Monitor is that you are communicating directly with the ESP8266, and not with the Arduino.
You need to connect the rx of the Arduino to the tx of the ESP8266 and the tx of the Arduino to the rx of the ESP8266.
This has asked and answered a number of times, such as:
Arduino Uno and ESP8266 serial monitor issue
Arduino & ESP8266
Arduino Nano v3.0 with ESP8266
ESP 8266 does not respond at all
Your ESP8266 definitely uses a baud rate of 115200 (as confirmed by your first screen shot), so you don't need to change that when experimenting.

Thank you for the answer @Holmez, third link was very helpful.
I was just change the code and the RX, TX pins like below and it works perfect now.
I can send commands to the ESP both in program and over the serial monitor.

#include <SoftwareSerial.h>

SoftwareSerial wifi(10, 11);

void setup() {
  Serial.begin(115200);
  wifi.begin(115200);
  Serial.println("Test");
  wifi.println("AT+CIFSR");
}

void loop() {
  if (Serial.available()) {
    wifi.write(Serial.read());
  }
  if (wifi.available()) {
    Serial.write(wifi.read());
  }
}

source: Stack Exchange

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

sort: votes


text:
OLED display wrong (using SPI )
I can't figure out where I doing wrong
https://www.youtube.com/watch?v=35NqOANmgUE
This is my question in videos

The both of two connect the same pin
(so the right display result is the correct  OLED)
My connecting table  (using SPI )
GND              gnd
VCC              5V
D0(OLED_CLK)     10
D(OLED_MOSI)     9
RES(OLED_RESET)  13
D/C(OLED_DC)     11
CS（OLED_CS）    12
but the left OLED doesn't have the "RES" pin
(so I didn't connect it)
the left OLED just display the upper part
(and its the position of display picture is also wired ,too)
this is my code
/*********************************************************************
This is an example for our Monochrome OLEDs based on SSD1306 drivers
This example is for a 128x64 size display using SPI to communicate
4 or 5 pins are required to interface

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Written by Limor Fried/Ladyada  for Adafruit Industries.
BSD license, check license.txt for more information
All text above, and the splash screen must be included in any redistribution
*********************************************************************/

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2

#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH  16
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
  B00000001, B11000000,
  B00000001, B11000000,
  B00000011, B11100000,
  B11110011, B11100000,
  B11111110, B11111000,
  B01111110, B11111111,
  B00110011, B10011111,
  B00011111, B11111100,
  B00001101, B01110000,
  B00011011, B10100000,
  B00111111, B11100000,
  B00111111, B11110000,
  B01111100, B11110000,
  B01110000, B01110000,
  B00000000, B00110000 };

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

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

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC);
  // init done

  // Show image buffer on the display hardware.
  // Since the buffer is intialized with an Adafruit splashscreen
  // internally, this will display the splashscreen.
  display.display();
  delay(2000);

  // Clear the buffer.
  display.clearDisplay();

  // draw a single pixel
  display.drawPixel(10, 10, WHITE);
  // Show the display buffer on the hardware.
  // NOTE: You _must_ call display after making any drawing commands
  // to make them visible on the display hardware!
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw many lines
  testdrawline();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw rectangles
  testdrawrect();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw multiple rectangles
  testfillrect();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw mulitple circles
  testdrawcircle();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw a white circle, 10 pixel radius
  display.fillCircle(display.width()/2, display.height()/2, 10, WHITE);
  display.display();
  delay(2000);
  display.clearDisplay();

  testdrawroundrect();
  delay(2000);
  display.clearDisplay();

  testfillroundrect();
  delay(2000);
  display.clearDisplay();

  testdrawtriangle();
  delay(2000);
  display.clearDisplay();

  testfilltriangle();
  delay(2000);
  display.clearDisplay();

  // draw the first ~12 characters in the font
  testdrawchar();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw scrolling text
  testscrolltext();
  delay(2000);
  display.clearDisplay();

  // text display tests
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Hello, world!");
  display.setTextColor(BLACK, WHITE); // 'inverted' text
  display.println(3.141592);
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.print("0x"); display.println(0xDEADBEEF, HEX);
  display.display();
  delay(2000);

  // miniature bitmap display
  display.clearDisplay();
  display.drawBitmap(30, 16,  logo16_glcd_bmp, 16, 16, 1);
  display.display();

  // invert the display
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  // draw a bitmap icon and 'animate' movement
  testdrawbitmap(logo16_glcd_bmp, LOGO16_GLCD_HEIGHT, LOGO16_GLCD_WIDTH);
}

void loop() {

}

void testdrawbitmap(const uint8_t *bitmap, uint8_t w, uint8_t h) {
  uint8_t icons[NUMFLAKES][3];

  // initialize
  for (uint8_t f=0; f< NUMFLAKES; f++) {
    icons[f][XPOS] = random(display.width());
    icons[f][YPOS] = 0;
    icons[f][DELTAY] = random(5) + 1;

    Serial.print("x: ");
    Serial.print(icons[f][XPOS], DEC);
    Serial.print(" y: ");
    Serial.print(icons[f][YPOS], DEC);
    Serial.print(" dy: ");
    Serial.println(icons[f][DELTAY], DEC);
  }

  while (1) {
    // draw each icon
    for (uint8_t f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS], logo16_glcd_bmp, w, h, WHITE);
    }
    display.display();
    delay(200);

    // then erase it + move it
    for (uint8_t f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS],  logo16_glcd_bmp, w, h, BLACK);
      // move it
      icons[f][YPOS] += icons[f][DELTAY];
      // if its gone, reinit
      if (icons[f][YPOS] > display.height()) {
    icons[f][XPOS] = random(display.width());
    icons[f][YPOS] = 0;
    icons[f][DELTAY] = random(5) + 1;
      }
    }
   }
}

void testdrawchar(void) {
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);

  for (uint8_t i=0; i < 168; i++) {
    if (i == '\n') continue;
    display.write(i);
    if ((i > 0) && (i % 21 == 0))
      display.println();
  }
  display.display();
}

void testdrawcircle(void) {
  for (int16_t i=0; i<display.height(); i+=2) {
    display.drawCircle(display.width()/2, display.height()/2, i, WHITE);
    display.display();
  }
}

void testfillrect(void) {
  uint8_t color = 1;
  for (int16_t i=0; i<display.height()/2; i+=3) {
    // alternate colors
    display.fillRect(i, i, display.width()-i*2, display.height()-i*2, color%2);
    display.display();
    color++;
  }
}

void testdrawtriangle(void) {
  for (int16_t i=0; i<min(display.width(),display.height())/2; i+=5) {
    display.drawTriangle(display.width()/2, display.height()/2-i,
                     display.width()/2-i, display.height()/2+i,
                     display.width()/2+i, display.height()/2+i, WHITE);
    display.display();
  }
}

void testfilltriangle(void) {
  uint8_t color = WHITE;
  for (int16_t i=min(display.width(),display.height())/2; i>0; i-=5) {
    display.fillTriangle(display.width()/2, display.height()/2-i,
                     display.width()/2-i, display.height()/2+i,
                     display.width()/2+i, display.height()/2+i, WHITE);
    if (color == WHITE) color = BLACK;
    else color = WHITE;
    display.display();
  }
}

void testdrawroundrect(void) {
  for (int16_t i=0; i<display.height()/2-2; i+=2) {
    display.drawRoundRect(i, i, display.width()-2*i, display.height()-2*i, display.height()/4, WHITE);
    display.display();
  }
}

void testfillroundrect(void) {
  uint8_t color = WHITE;
  for (int16_t i=0; i<display.height()/2-2; i+=2) {
    display.fillRoundRect(i, i, display.width()-2*i, display.height()-2*i, display.height()/4, color);
    if (color == WHITE) color = BLACK;
    else color = WHITE;
    display.display();
  }
}

void testdrawrect(void) {
  for (int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, WHITE);
    display.display();
  }
}

void testdrawline() {
  for (int16_t i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, WHITE);
    display.display();
  }
  for (int16_t i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, WHITE);
    display.display();
  }
  delay(250);

  display.clearDisplay();
  for (int16_t i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, WHITE);
    display.display();
  }
  for (int16_t i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, WHITE);
    display.display();
  }
  delay(250);

  display.clearDisplay();
  for (int16_t i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, WHITE);
    display.display();
  }
  for (int16_t i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, WHITE);
    display.display();
  }
  delay(250);

  display.clearDisplay();
  for (int16_t i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, WHITE);
    display.display();
  }
  for (int16_t i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, WHITE);
    display.display();
  }
  delay(250);
}

void testscrolltext(void) {
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(10,0);
  display.clearDisplay();
  display.println("scroll");
  display.display();

  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
}

I think I have the same problem like this link
http://www.electroschematics.com/11150/cheap-oled-displays-arduino/
but the case is using I2P
and I didn't understand how it resolve the bug

Nobody wants to watch videos. Clearly type and post exactly what the problem is, as well as, your code so far, if any.

Check the connection. That does not look like SPI.

@WillyLotus -  This question doesn't clearly ask a question.  You have an issue, but its not clear which display has the fault, you say left, but from what perspective.  There is no indication of any make or model numbers of the faulty unit.  You imply that the two displays are not the same or one has a pin missing.  Please can you try and improve the question and keep all the information on this site as external links may not be trust worthy.  Sorry, I'm not trying to be horrible, I'm actually trying to help you get a better answer faster.

Are they both the same model? Both the same resolution? Both the same driver chip?

Check the connections with that required by the software/library. If you intend to use SPI the pins on Arduino Uno are:
SS   10
MOSI 11
MISO 12
SCK  13

You connections above are:
VCC             => 5V
D0(OLED_CLK)    => 10 (SPI SS ??)
D(OLED_MOSI)    => 9
RES(OLED_RESET) => 13 (SPI SCK ??)
D/C(OLED_DC)    => 11 (SPI MOSI ??)
CS（OLED_CS）     => 12 (SPI MISO ??)
GND             => GND (??)

That is not correct for SPI. Post link to library, oled hardware, and snippet of your code for more help.
It is more than the video that is out of focus :)
Cheers!

For the OP, slave select can be whatever pin one defines while writing the library, that means if the library supports it you can use multiple SPI slaves (multiple, different screens at one for example) but it's usually not that easy (depends of the frame of reference) unless someone has done it already and uploaded the code.

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


text:
Problem up loading to board
I'm a newbee to Arduino programming and hoping someone can help me with this. These are the errors when uploading the proceeding sketch. Thanks in advance!
avrdude: stk500_rcv() : programmer is not
responding
avrdude: stk500_getsync() attempt 10 of 10:not in sync:
Problem uploading to board.
//www.RobotLinking.com
//2015.5.7
/************************************************/
#include <Servo.h>
/************************************************/
Servo myservo;//create servo object to control a servo
/************************************************/
void setup()
{
  myservo.attach(9);//attachs the servo on pin 9 to servo object
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
}
/*************************************************/
void loop()
{
  myservo.write(15);//goes to 15 degrees
  delay(1000);//wait for a second
  myservo.write(30);//goes to 30 degrees
  delay(1000);//wait for a second.33
  myservo.write(45);//goes to 45 degrees
  delay(1000);//wait for a second.33
  myservo.write(60);//goes to 60 degrees
  delay(1000);//wait for a second.33
  myservo.write(75);//goes to 75 degrees
  delay(1000);//wait for a second.33
  myservo.write(90);//goes to 90 degrees
  delay(1000);//wait for a second
  myservo.write(75);//back to 75 degrees
  delay(1000);//wait for a second.33
  myservo.write(60);//back to 60 degrees
  delay(1000);//wait for a second.33
  myservo.write(45);//back to 45 degrees
  delay(1000);//wait for a second.33
  myservo.write(30);//back to 30 degrees
  delay(1000);//wait for a second.33
  myservo.write(15);//back to 15 degrees
  delay(1000);//wait for a second
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
}
/**************************************************/

if you google for avrdude: stk500_getsync() attempt 10 of 10:not in sync: there is a lot of topics and possible answers that could suit your needs.

Which board? Which OS? What is wired to the board? Is it a genuine one or a clone?

Oh, the formatting -.- anyway... Can you upload another sketch on the board? Usually people use the blink example...

Code formatting is fubared. You need to put four spaces in front of each line...

One of the first things to know about Arduinos is that that there are a lot of them – and a lot of tools for programming them. For your problem this means that the most likely reason for the problem you are having is a mismatch between the board your are using and the board your tools are set to upload to. Since you've said you're new to the Arduino I'm assuming that you're using the "official" IDE.
So, here are some things to try:

From the IDE main menu, choose Tools > Board and select your board, then
Choose Tools > Programmer and select an appropriate programmer for your board. Without knowing what board you're using and how you're connecting to it I can't offer more specific advice. However, if you Google for something like "beginner tutorial " you're likely to find an answer. Or more likely three answers. You'll need to look at the one that matches the OS you're using on your development machine.
You may also need to select the port that the Arduino is connected to.

If you've gotten this far and haven't solved the problem, here's what I'd do next:

Do a search on the exact error message you're getting – copy it out of the IDE and the paste it into your favorite search engine. Put quotes around the message so that you don't get a bunch of unrelated hits for your search.
Search for tutorials on the board and/or IDE vendor site.
Work through a tutorial from a good beginner's site. I like the materials the Adafruit folks have developed, but there are lots of good resources out there.
Post a question. When you do be sure to:

Describe your environment: the board you're using, the IDE you're using, the OS you're working on, how the board is connected to the development machine, and the basic settings of the IDE.
Explain what you've tried.
Describe, or better, include a screen shot or the actual text of the problem that you're seeing (like you did here).
For some problems it will also be useful to include the code. If you include the complete code then it is possible that somebody could try to actually reproduce your problem.

I think I may have found the answer to my problem. Like I mentioned I am new to the Arduino world. I did not burn the 432 on the UNO. How come the 432 isn't burned at the factory. I'm I proceeding in the right direction to burn the 432? Excuse my ignorance!


text:
Board and library updates required caused an error
I compiled my code several times today,
I would quit and restart randomly through the day.
each time I started I get a error box board and libraries need updates.
I did an AVR board up date, then compiled and now I get this every time.....

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

Yes I have tried rebooting my Windows 7 64 bit AMD machine.
this is on IDE "Arduino 1.6.8"
Of course I made the mistake of not backing up my IDE folders in the belief that an update would not screw my IDE up.
Nothing will upload, not even any of the examples.
I turned on Show Verbose output during Compilation, and upload
I pasted the full output and it was 4500 char to many for this so I turned of the compilation check and left just the upload check on show verbose errors
I loaded in the example blink,
the file followed by the IDE lower window text.
/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the Uno and
  Leonardo, it is attached to digital pin 13. If you're unsure what
  pin the on-board LED is connected to on your Arduino model, check
  the documentation at http://www.arduino.cc

  This example code is in the public domain.

  modified 8 May 2014
  by Scott Fitzgerald
 */

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

END OF FILE
Copy and paste of the lower IDE window  last lines the same as above

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/bin/avrdude -CC:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf -v true -patmega328p -carduino -PCOM10 -b115200 -D -Uflash:w:C:\Users\Lee\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jun 22 2016 at 16:05:21
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf"

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

There is that line again   What do I do to fix this?
besides deleting everything and starting all over again?
I do not want to delete and start over

try to check your setting in Tools->Board and Tools->Programmer.

Possible duplicate of Uploading Error: no programmer has been specified

This sounds very much like the problem I had when I updated my ARV version,I was also getting "no programmer has been specified error", I run Windows 7 32bit, the way i got out of it was to go back to the update screen when it pops up and in Arduino ARV Boards area....select versions....I went back to version 1.6.10...now it all works again.....at this point I am no longer updating my ARV, but I will after a few more version updates come out, there is obviously something that conflicts at this stage, if you google the problem you will find other of ways to fix this.


text:
Arduino documentation on PCIFR and PINC
I was reading this thread:
Read RC receiver channels using Interrupt instead of PulseIn
and I have been trying to understand the code provided within.
While I was able to udnerstand most of it, I am still unable to find proper documentation on Arduino PCIFR and PINC?
Could someone please point me in the right direction?
Thanks in advance.

Welcome to Arduino.SE. The documentation that you seek on PCIFR and PINC would not be documented under Arduino, this is as these are directly related to the ATMega328 (AVR Atmel micrcontroller) which is on the Arduino, they are registers which are inside the microcontroller and PCIFR and PINC are mnemonics.
For the ATMega328 you will find the documentation to these registers in the datasheet (a good read with coffee), or in tutorials written by others explaining this information in an easy to grasp way.
The PCIFR register is the Pin Change interrupt flag register(description on pg 73 of linked datasheet), this holds the flag bit to tell the microcontroller that there was an interrupt and runs the ISR() routine that one has set out. Read this post by Nick Gammon on Pin Change Interrupts, and then read all of the post to get a better idea of interrupts in general.
The register PINC is for the inputs to the microcontroller, when one uses staus = digitalRead(A0); they are in effect using a wrapped up version of bitwise math and bit manipulation when simplified to status = PINC & (1 << PC0); thus PINx (x is for the register name ABCD) represents the state of the pin, either HIGH(1, 5V, true) or LOW(0, 0V, False). Borrowing from the below linked tutorial:

Another nice description of the input ports in this tutorial.
From the image you see that moving a bit to a position and then bitwise & that with PINx you will have a value returned if there is a 1 in that position.
 PINC      0b00001001
(1 << PC0) 0b00000001
         & __________
status  =  0b00000001

The above shows how you only get the state of the first input and how the 4th input is ignored as it was not needed. Also worth noting PIN is the register description and is not the same as a physical pin that sticks out the IC's body.


text:
Measure different Vcc using 1.1V bandgap
When I power my ATmega328P chip from 5.16V and 3.3V, there doesn't seem to be a single bandgap voltage compensation figure that works for both.
I'm using the following sketch, and I need the following InternalReferenceVoltage values to read the correct voltage from A0:

1255L to correctly output 5.16V.
1358L to correctly output 3.3V.

I have a couple of questions:

Should I be able to use a single InternalReferenceVoltage compensation value whe powering the ATmega328P from different voltages?
Aren't both of these values outside the specced 1.0 to 1.2 range?

The code is from, http://forum.arduino.cc/index.php?topic=56750.msg407897#msg407897, retolefty post @ Mar 28, 2011, 02:27 pm.
#include <SPI.h>

void setup()
{
  delay(5000);

  Serial.begin(115200);
}

void loop(void)
{
  // Determines what actual Vcc is, (X 100), based on known bandgap voltage
  int battVolts = readVcc1();

  Serial.print("Battery Vcc volts =  ");
  Serial.println(battVolts);
  Serial.print("Analog pin 0 voltage = ");
  Serial.println(map(analogRead(0), 0, 1023, 0, battVolts));
  Serial.println();

  delay(1000);
}

// Returns actual value of Vcc (x 100)
int readVcc1()
{
  uint8_t oldADMUX = ADMUX;

  const long InternalReferenceVoltage = 1255L; // Adjust this value to your boards specific internal BG voltage x1000

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // For mega boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc reference
  // MUX4 MUX3 MUX2 MUX1 MUX0  --> 11110 1.1V (VBG)         -Selects channel 30, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (0 << MUX5) | (1 << MUX4) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#else
  // For 168/328 boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#endif
  delay(50); // Let mux settle a little to get a more stable A/D conversion
  // Start a conversion
  ADCSRA |= _BV(ADSC);
  // Wait for it to complete
  while (((ADCSRA & (1 << ADSC)) != 0));

  // Scale the value
  int results = (((InternalReferenceVoltage * 1023L) / ADC) + 5L) / 10L; // calculates for straight line value

  ADMUX = oldADMUX;

  return results;
}

I have read these other references to try and find a solution:

Measure Vcc using 1.1V bandgap
https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/
http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/

I don't get the question. The idea is not to measure the 3.3v or 5v using the internal reference voltage as a reference, but the other way around. You measure the internal reference voltage in relation to Vcc.

Thanks. Do you know how I should change the code or the measurements then? I thought measuring Vcc using the internal reference would allow me to calculate how my particular internal reference varies from 1.1V.

After reading your question one more time, I finally get it. Forget what I said, as it's not related.

The internal reference won't change much. That's why it's a reference.
Running this code on my Atmega328P:
void setup ()
{
  ADMUX = bit (REFS0) | bit (REFS1);  // Internal 1.1V reference
}
void loop () { }

That outputs the reference voltage on Aref. I measured it as follows with different values for Vcc:
Vcc     Aref
------------
5.00   1.085
4.00   1.081
3.30   1.080
3.00   1.079

So you can see that it retains, more or less, the same voltage regardless of Vcc. In any case, there is no way of measuring Aref, unless you have another reference voltage around to compare it to.

Thanks. So do I measure the voltage on the AREF pin with a multimeter to calibrate an individual chip? I'm sure I read somewhere that the internal voltage reference was never made physically available externally. I'm still not clear on how to fine tune an individual chip to get more accurate voltage readings of the battery powering the chip.

What I posted above was done by measuring with a multimeter after running that code which puts the internal voltage reference onto the Aref pin. And yes, it varies from chip to chip. As you can see, mine is slightly under 1.1V.

Thanks. I measure 1.078V on AREF (using multimeter) following your sketch, but when I use that value as the InternalReferenceVoltage value (from your "Internal Voltage Sensor" code - http://www.gammon.com.au/adc) I get 4.35V printed, when my voltage is 5.16V. I measure Vcc continuously in the loop. Confused.

What raw ADC reading do you get? Mine reads low (4.95V - raw reading: 226) but not that low. See this thread on AVR Freaks - it appears that there are some inconsistencies between theory and practice.

The difference between 4.95V and 5V (that I got) is only 1%, so that is probably acceptable for checking input voltage. Your results of 4.35V sounds like some sort of error. I tried a different approach using an external reference voltage (TL431 chip) and got better results. I can amend my answer if you want to see that. However that may have other drawbacks (depending on whether you are using the analog inputs for other purposes as well).

A bit of testing with an external reference still gives readings that fluctuate a bit. I suggest an error of a percent or two is probably normal for the ADC.

Thanks for your suggestions and the AVR Freaks link.  I've tried another 328P and get 1.08V for bandgap, 255 raw ADC, and the 2nd code prints 4.32V for the 5.16V source.  I can measure the battery V using 'standard' ADC relative to my boost converter's 3.3V [1], but the 'native on-chip' way seems more portable so I'd prefer to do it that way unless I've missed something.  I am new to this after all!  I do have an old and cheap multimeter, so I probably ought to buy a second to verify my measurements.  [1] the boost converter is not involved in my testing, my 3.3V is from a LD33V chip.


text:
Using NodeJS, socket.io and Adafruit HUZZAH CC3000 breakout board to control Arduino wirelessly?
I'm looking to build my a wirelessly controlled lamp and have a few questions. Would I be able to use the Adafruit HUZZAH CC3000 breakout board to receive commands from a website and control a connected lamp?
I just set up a NodeJS server with webpage on my PC and using socket.io and Firmata I was able to communicate with the Arduino using the webpage over a serial connection. Could I set up similar implementation except instead of communicating over serial I'd communicate using Wifi? Would I need to host a web server on the Wifi board itself to communicate with the Arduino or is there some way to just use the wifi board as a communication between external site and Firmata?

A good source would be Adafruit's website. They detail many projects involving this board, here is one that lights up a tree: https://learn.adafruit.com/wifi-controlled-led-christmahanukwanzaa-tree?view=all

I happen to have received the CC3000 shield yesterday and have been playing with it today...
What do you mean by "receive commands from a website"?
If you mean "can it serve a simple website and act upon HTTP requests" (e.g. requests to http://arduino.local/on would turn a lamp off and http://arduino.local/off would turn if off), then yes it can. You make the HTTP requests using javascript's XMLHTTPRequest if you want to be able to communicate from within a web page without having to re-render a page.
There is an example sketch of an HTTP server included in the CC3000 library that would get you started. Note that the example HTTP server sketch can only handle one HTTP request/response at a time.
You will obviously also need some way of controlling a relay of you want to control a lamp.
Update: Since you updated your question to include how you are currently communicating:
I'm not familiar with socket.io or Firmata, but I'm guessing socket.io is a way of getting your web client (browser) to talk directly Firmata which talks to your Arduino over the USB-Serial connection? If so, then I'm not sure if it's possible to use the Firmata protocol over wireless, but it is possible for the CC3000 to act as a generic TCP server and act on data that it receives wirelessly, so it might be possible to communicate between socket.io and the TCP server. The EchoServer sketch shows how to set up a TCP server to receive raw data.
If you're only turning a lamp on/off you basically only need to control 1 pin. Isn't Firmata a bit overkill for that? Be careful about sketch size. I'm not sure how big Firmata compiles to, but the wireless library with some kind or server is over 22,000 byes (of a possible 32,000) on an Uno, so you might struggle to fit both on.

Added some detail to my question about sockets specifically.

@VianEsterhuizen: Updated my answer now you put more detail in your question, but I'm not sure how much help it will be now as I'm not familiar with some of the technology that you are using.

Have you heard of aREST.io? There is a wifi library that supports the CC3000 (http://arest.io/wifi/) that sounds like it might do a similar thing to Firmata

That looks interesting but I'm really hoping to get this working with sockets. This is really good backup plan though.


text:
Arduino Uno + Wifi Shield + PS2 Keyboard + LCD Display
I'm new in the Arduino Community and I'm facing a problem when I try to use a PS2 Keyboard and an LCD Display (16x2) on an Arduino Uno with a Wifi shield.
I would like to write something with the keyboard and display it in the LCD before sending it to a webservice.
Here is my problem:

When I use the keyboard and the display on my Arduino WITHOUT the wifi shield --> All is OK. I can write on the display the key that has been pressed.
When I use the keyboard and the display on my Arduino WITH the wifi shield --> All is OK until I write something on the display. As soon as I write on the display with the function lcd.print(), the keyboard does not work anymore (it detect the character '2' every time I press a key).

It's very surprisingly because if I dont use lcd.print(), the keybord works without any problem.
Here is a part of my code:
#include <LiquidCrystal.h>
#include <PS2Keyboard.h>

LiquidCrystal lcd(12, 11, 2, 5, 6, 8);
PS2Keyboard keyboard;

const int DataPin = 9;
const int IRQpin = 3;

void setup(){
  keyboard.begin(DataPin, IRQpin);
  lcd.begin(16, 2);
}

void loop(){
  checkKeyboard();
}

void checkKeyboard(){
  if (keyboard.available()) {

    char c = keyboard.read();

    // check for some of the special keys
    if (c == PS2_ENTER) {
      Serial.println();
    } else if (c == PS2_TAB) {
      Serial.print("[Tab]");
    } else if (c == PS2_ESC) {
      Serial.print("[ESC]");
    } else if (c == PS2_PAGEDOWN) {
      Serial.print("[PgDn]");
    } else if (c == PS2_PAGEUP) {
      Serial.print("[PgUp]");
    } else if (c == PS2_LEFTARROW) {
      Serial.print("[Left]");
    } else if (c == PS2_RIGHTARROW) {
      Serial.print("[Right]");
    } else if (c == PS2_UPARROW) {
      Serial.print("[Up]");
    } else if (c == PS2_DOWNARROW) {
      Serial.print("[Down]");
    } else if (c == PS2_DELETE) {
      Serial.print("[Del]");
    } else {
      Serial.print(c);
      displayText(c);
    }
  }
}

void displayText(char c){
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Pressed key:");
  lcd.setCursor(0,1);
  lcd.print(c);
}

Does somebody know how to solve this problem?
Thank you very much in advance :)
Edit: Here are the pins that I use on the board :

Arduino pin 2 -> LCD pin 11
Arduino pin 5 -> LCD pin 12
Arduino pin 6 -> LCD pin 13
Arduino pin 8 -> LCD pin 14
Arduino pin 11 -> LCD pin 6
Arduino pin 12 -> LCD pin 4
Arduino pin 3 -> Keyboard IRQ
Arduino pin 9 -> Keyboard Data

As you say, I can't use pins 10, 11, 12, 13 because they are used for the SPI.
-> So, I tried to use the pins 4 and 7 instead of 11 and 12.
The problem is that the pin 7 is used by the Wifi shield (Handshake) and I have no other free digital pin.
-> So, I tried to use an analog pin instead of the pin 7 and ..... it works very well.
Here is my final solution :

Arduino Pin 2 -> LCD Pin 4 (RS)
Arduino Pin 3 -> Keyboard IRQ
Arduino Pin 4 -> LCD Pin 11 (D4)
Arduino Pin 5 -> LCD Pin 12 (D5)
Arduino Pin 6 -> LCD Pin 13 (D6)
Arduino Pin 7 ->
Arduino Pin 8 -> LCD Pin 14 (D7)
Arduino Pin 9 -> Keyboard Data
Arduino Pin 10 ->
Arduino Pin 11 ->
Arduino Pin 12 ->
Arduino Pin 13 ->
Arduino Pin 14 (= Analog 1) -> LCD Pin 6 (E)

Sorry I do not have enough reputation to place a comment.
@Valentin from the link, you provided, to the wifi shield it states that it uses pins 11 ,12 and 13 on the UNO which will give you a conflict on pins 11 and 12 with the LCD. Not sure why that manifests as an apparent keyboard error though:
From the linked page:

Arduino communicates with both the Wifi shield's processor and SD card using the SPI bus (through the ICSP header). This is on digital pins 11, 12, and 13 on the Uno and pins 50, >51, and 52 on the Mega. On both boards, pin 10 is used to select the HDG204 and pin 4 for >the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, >53, is not used to select either the HDG204 or the SD card, but it must be kept as an output or the SPI interface won't work.

Again sorry this is not a full answer but thought it may help.

You must verify which pins the wifi shield is using and see if they aren't used also by the LCD.
Can you provide further details on the wifi shield ?

I put the keyboard on the pins 3 (IRQ) and 9 (Data). The LCD use the pins 12, 11, 2, 5, 6 and 8. I know the Wifi shield use some pins. If I correctly read the documentation (http://arduino.cc/en/Main/ArduinoWiFiShield), the pins 4, 7 and 10 are reserved for the Wifi shield.


text:
LCD from Arduino Starter Kit not displaying text
I've been tinkering with my new Arduino a bit and I was adding an LCD from the starter kit, using information from the eleventh project in the project book, "Crystal Ball." When I connect the Arduino to my computer, the LCD lights up, but no text is displayed on the screen.
Here are some screenshots of my connections:

Finally, here's the code that I uploaded to the Arduino:
#include <LiquidCrystal.h>

// Create this display with the pins that I wired
LiquidCrystal lcd(12, 11, 2, 3, 4, 5);

void setup()
{
    // This is a 16x2 display
    lcd.begin(16, 2);

    lcd.print("hello!");
}

void loop()
{
}

edit: Additionally, I tried adding a potentiometer to control the display, but to no avail. Below is the wiring for this (back pin goes to the third to last pin for the LCD).

Those photos don't show the circuit adequately.  Please edit your question and add a schematic diagram of the circuit.  If you don't have a schematic diagram drawing program or some other drawing program click the icon (in the edit tool bar) that looks like a pencil pointed at a circuit diagram.

In the end, it turned out being a combination of what Andre's Answer suggested, as well as the "brightness" of the LCD. My potentiometer seems to have kind of a "stick" to it, meaning that to get the LCD to move to the value necessary, I had to crank the thing harder than normal, then it started displaying my text.

Looking at your first picture it looks like you are wired on 12 and 13 not to 11 and 12 like your sketch specifies.
Double check your wiring against this : https://www.arduino.cc/en/Tutorial/HelloWorld
Also take your multi-meter out and buzz your connections.


text:
How to verify that my FTDI bridge for ESP8266 is communicating with my PC?
As I couldn't make my ESP8266 be programmed using an Arduino board as FTDI bridge, I decided to buy an FTDI232 board to upload code directly to ESP module via USB. However, when new I connected it to my PC and nothing happened, no new device's notification, not listed on Device Manager; then I downloaded the chip and VCP drivers, installed them, and it keeps not communicating and not even showing its port as busy at Arduino IDE. Actually, I just disabled driver signature enforcement, repeated the process but communication between FTDI and PC keeps dead.
By testing uploading code to an Arduino Micro via FTDI (no USB connected to Micro), I checked Tx/Rx signals with an oscilloscope and both were not responding.
May it be a problem of communication PC<--->FTDI board? Or could it be that FTDI's chip is fried?
Thanks.

did you connect the ardunio's reset to ground to use it as an "ftdi"? that's the only way i could connect to my ESP-01s before i got a handy usb socket...

Which Arduino board did you use? I tried with connecting reset to ground on Micro, Uno and Leonardo, but any of them seemed to work. Of course I followed the tips of grounding GPIO0 while uploading code and that stuff, but no one worked (everybody in the internet who use it has success since the first attempt, that's confusing and sad)

a cheap fake uno worked fine for me; no level shifting or anything. might try uncrossing the pins.


text:
Serial.parseInt value always goes back to 0
I am trying to read a value between 1000 and 2000 from my Serial Monitor and use it to drive some motors through ESC.
The code works when I use a potentiometer mapped for 1000-2000. I am now trying to use a Serial Monitor, but the "val" keeps going from the value I enter (between 1000 and 2000) and quickly returns to 0.
Why is this?
Here is the code for reference:

#include <Servo.h>//Using servo library to control ESC
Servo esc1; //Creating a servo class with name as esc1
Servo esc2; //Creating a servo class with name as esc2
Servo esc3; //Creating a servo class with name as esc3
Servo esc4; //Creating a servo class with name as esc4
void setup()
{
  esc1.attach(7); //Specify the esc signal pin,Here as D10
  esc2.attach(6); //Specify the esc signal pin,Here as D9
  esc3.attach(5); //Specify the esc signal pin,Here as D8
  esc4.attach(4); //Specify the esc signal pin,Here as D7
  esc1.writeMicroseconds(1000); //initialize the signal to 1000
  esc2.writeMicroseconds(1000); //initialize the signal to 1000
  esc3.writeMicroseconds(1000); //initialize the signal to 1000
  esc4.writeMicroseconds(1000); //initialize the signal to 1000
  Serial.begin(9600);
}
void loop()
{
  int val; //Creating a variable val
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while (Serial.available() > 0) {
    val = Serial.parseInt();
    Serial.println(val);
  }//Checks for a character in the serial monitor
  Serial.println(val);
  esc1.writeMicroseconds(val); //using val as the signal to esc
  esc2.writeMicroseconds(val); //using val as the signal to esc
  esc3.writeMicroseconds(val); //using val as the signal to esc
  esc4.writeMicroseconds(val); //using val as the signal to esc
}

you use very annoying comment style in  your code. repeating the same thing over and over only makes the code less readable.

quickly returns to 0  ... how long does it take to return to zero?

jsotola it takes about a second

its almost as if Serial.parseInt is not going to my val integer...

This code will work IF you set the Serial Monitor to "No Line Ending" (OSX 10.6.8. IDE Version 1.0.6.2). parseInt() doesn't like the NL + CR chars.
unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){
    val = Serial.parseInt();
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

There is another way to get the integer value using this code:
char inputBuffer[16];
unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){

    // A function that reads characters from the serial port into a buffer.
    Serial.readBytes(inputBuffer, sizeof(inputBuffer));

    // Convert string to integer
    // cplusplus.com/reference/cstdlib/atoi/
    val = atoi(inputBuffer);

    // memset clears buffer and updates string length so strlen(inputBuffer) is accurate.
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

The Binary sketch size is 94 bytes less than the first example using parseInt. The second sketch will work with ANY Serial Monitor Line Ending settings.

Thank you very much  VE7JRO, care to explain the second one? This one works, the first one not so much...even with the serial monitor set to "No Line Ending"
I think i understand my mistake now, i had int val; in my main program, resetting its value each loop around!!

Which O/S are you using? I'm wondering if the Serial Monitor behaves differently on different O/Ses. I'm using a very old version of OSX, 10.6.8.

I've add some comments to the while loop section of the second sketch.

i am using Windows 7 x64. thanks so much for the comments, very helpful!


text:
Arduino USB Host Shield with joystick
I'm building my own quadcopter and going to use an Arduino for this. An Arduino Micro for the quadcopter and an Arduino UNO for the controller. I want to use an USB host shield with a Logitech Extreme 3D Pro to control the quadcopter.
I have the joystick already working with de example from the USB host shield example, but I can't get the values to my void loop(). There is not much information on the internet about this.
The link to the library and example I'm using: https://github.com/felis/USB_Host_Shield_2.0/tree/master/examples/HID/le3dp
.INO file:
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>

#include "le3dp_rptparser.h"

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
}

void loop()
{
    Usb.Task();
}

.cpp file:
#include "le3dp_rptparser.h"

JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt)
{}

void JoystickReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
    bool match = true;

    // Checking if there are changes in report since the method was last called
    for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
        if( buf[i] != oldPad[i] ) {
            match = false;
            break;
        }
  }
    // Calling Game Pad event handler
    if (!match && joyEvents) {
        joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

        for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    PrintHex<uint16_t>(evt->x, 0x80);
    Serial.print(" Y: ");
    PrintHex<uint16_t>(evt->y, 0x80);
    Serial.print(" Hat Switch: ");
    PrintHex<uint8_t>(evt->hat, 0x80);
    Serial.print(" Twist: ");
    PrintHex<uint8_t>(evt->twist, 0x80);
    Serial.print(" Slider: ");
    PrintHex<uint8_t>(evt->slider, 0x80);
    Serial.print(" Buttons A: ");
    PrintHex<uint8_t>(evt->buttons_a, 0x80);
    Serial.print(" Buttons B: ");
    PrintHex<uint8_t>(evt->buttons_b, 0x80);
    Serial.println("");
}

.h file:
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__

#include <hid.h>

struct GamePadEventData
{
  union { //axes and hut switch
    uint32_t axes;
    struct {
      uint32_t x : 10;
      uint32_t y : 10;
      uint32_t hat : 4;
      uint32_t twist : 8;
    };
  };
  uint8_t buttons_a;
  uint8_t slider;
  uint8_t buttons_b;
};

class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
};

#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

class JoystickReportParser : public HIDReportParser
{
    JoystickEvents      *joyEvents;

  uint8_t oldPad[RPT_GAMEPAD_LEN];

public:
    JoystickReportParser(JoystickEvents *evt);

    virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

#endif // __HIDJOYSTICKRPTPARSER_H__

So I hope that someone can give me a solution how I can get the value out of the code below (I changed the code a bit, so that I get decimal values) into the void loop().
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    Serial.print(evt->x);
    Serial.print("\t Y: ");
    Serial.print(evt->y);
    Serial.print("\t Hat Switch: ");
    Serial.print(evt->hat);
    Serial.print("\t Twist: ");
    Serial.print(evt->twist);
    Serial.print("\t Slider: ");
    Serial.print(evt->slider);
    Serial.print("\t Buttons A: ");
    Serial.print(evt->buttons_a);
    Serial.print("\t Buttons B: ");
    Serial.print(evt->buttons_b);
    Serial.println("");
}

I've some experience with Arduino programming but not much.
Please ask me if you need more information.

The following assumes you are seeing OnGamePadChanged being called.
One way you could get the values you want (GamePadEventData *evt) into the loop() would be to add a member variable to the JoystickEvents class, so that class would become something like
class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
    static GamePadEventData mostRecentEvent;
};

In OnGamePadChanged, make a copy of evt:
GamePadEventData JoystickEvents::mostRecentEvent;
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    mostReventEvent = *evt;
}

Now you can read it from loop() using something like
Serial.print("X: ");
Serial.print(JoystickEvents::mostReventEvent.x);

A significant limitation of this method is that it will only keep the most recent event.  Maybe that's OK for your purpose.
It's probably not quite what the author of that code had in mind: he probably expected you to do the work in OnGamePadChanged: his implementation of that method looks like an example so you can see how it works.

I got it working a few minutes ago in a bit different way. I will post my way as an anwer so other people can find and use it. I'm also going to try it your way so I can learn from it. Thank you!

I've tried it but I get an error which says: base operand of ' ->' has non-pointer type 'GamePadEventData'. Do you know what I did wrong?

My typo, now fixed. I used -> instead of .. The former is used if you have a pointer to an object, the latter is you have the object itself. (In future it would be useful to indicate the line where the error occurred.)

Sorry, my bad. I got it working right now. Thank you very much!

After trying some other things I came up with the following idea:
I moved this piece of code from the .cpp file to the .INO file:
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    PrintHex<uint16_t>(evt->x, 0x80);
    Serial.print(" Y: ");
    PrintHex<uint16_t>(evt->y, 0x80);
    Serial.print(" Hat Switch: ");
    PrintHex<uint8_t>(evt->hat, 0x80);
    Serial.print(" Twist: ");
    PrintHex<uint8_t>(evt->twist, 0x80);
    Serial.print(" Slider: ");
    PrintHex<uint8_t>(evt->slider, 0x80);
    Serial.print(" Buttons A: ");
    PrintHex<uint8_t>(evt->buttons_a, 0x80);
    Serial.print(" Buttons B: ");
    PrintHex<uint8_t>(evt->buttons_b, 0x80);
    Serial.println("");
}

After I changed some of the code in the .INO file the code looks like this:
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>

#include "le3dp_rptparser.h"

int joyX = 512;       // min: 0 | max: 1023 | center: 512
int joyY = 512;       // min: 0 | max: 1023 | center: 512
int joyHat = 8;       // up: 0 | right-up: 1 | right: 2 | right-down: 3 | down: 4 | left-down: 5 | left: 6 | left-up: 7 | center: 8
int joyTwist = 128;   // min: 0 | max: 255 | center: 128
int joySlider = 0;    // min: 0 | max: 255
int joyButtonsA = 0;
int joyButtonsB = 0;

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
}

void loop()
{
    //Print all the values into the serial monitor:
    Usb.Task();
    Serial.print("X: ");
    Serial.print(joyX);
    Serial.print("\t Y: ");
    Serial.print(joyY);
    Serial.print("\t Hat: ");
    Serial.print(joyHat);
    Serial.print("\t Twist: ");
    Serial.print(joyTwist);
    Serial.print("\t Slider: ");
    Serial.print(joySlider);
    Serial.print("\t Buttons A: ");
    Serial.print(joyButtonsA);
    Serial.print("\t Buttons B: ");
    Serial.println(joyButtonsB);
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  //Put the values from the joystick in another variable:
  joyX = evt->x;
  joyY = evt->y;
  joyHat = evt->hat;
  joyTwist = evt->twist;
  joySlider = evt->slider;
  joyButtonsA = evt->buttons_a;
  joyButtonsB = evt->buttons_b;
}

It works very good for me and I'm now able to send the values to another Arduino with the nRF24L01+.


text:
Arduino with two (or more) push buttons
I am trying modify this setup for two push buttons https://www.arduino.cc/en/Tutorial/Button.
The code seems rather trivial
int yellowButtonPin = 2;
int blueButtonPin = 4;

int yellowButtonState = 0;
int blueButtonState = 0;

void setup(){
  Serial.begin(9600);
  pinMode(yellowButtonPin,INPUT);
  pinMode(blueButtonPin,INPUT);
}

void loop(){
  yellowButtonState = digitalRead(yellowButtonPin);
  blueButtonState = digitalRead(blueButtonPin);
  if (yellowButtonState == HIGH && blueButtonState == HIGH){
    Serial.write(3);
  }
  else if (yellowButtonState == HIGH && blueButtonState == LOW){
    Serial.write(2);
  }
   else if (yellowButtonState == LOW && blueButtonState == HIGH){
    Serial.write(1);
  }
  else {
    Serial.write(0);
  }
}

My problem is that there are several ground pins on the Arduino, but only one 5V pin, so I can't just simple double the circuits. Connecting the two circuits to different grounds but the same 5V didn't work out, although it seemed to be a good idea. How should I do this properly? To be honest, I actually would want to have three buttons, but I guess going from two to three will be trivial after going from one to two.

Chances are there is something wrong with how you built your circuit. Using the same 5V pin for both buttons is perfectly acceptable.

All the ground connections are identical and connected together. It makes no difference which ground pin your use.

There is only one ground. It may have multiple pins on it, but there is only one. Use whatever ground pin(s) you fancy, they are all the same.

@Majenko I edited the question with a circuit diagram, should that be ok?

I hope you don't expect characters '0' .. '3' in the Serial Monitor as you are sending characters: NUL, SOH, STX and ETX (ASCII values from 0 to 3) and they might not be visible.

I'm getting bytes \x00 through \x03 in python so that seems ok at the moment for my purposes.

Most people use a breadboard to easily spit the 5v into multiple wires.

Learn about:
Built-in pullup resistors in Arduino
Debouncing
and checks this code: https://blog.adafruit.com/2009/10/20/example-code-for-multi-button-checker-with-debouncing/


text:
Multiple arduino Wireless communication
I would like to know what device and model to use for an application where I will have 1 arduino as a master micro controller waiting to receive data from 5 slave arduino microcontrollers.
The Master arduino will be connected to local network via Ethernet cable so once it receive data from a Slave controller it needs to post to server the information, get a response back and in case the response is a "true" value then the Master need to talk back to the Slave in order to turn a LED on.
There will be cases when maybe 3 of the Slaves will send data at the same time, this doesn't mean at exactly the same millisecond. So I don't know if there will be data lost.
I was reading that Xbee maybe is the best device because it has a feature that will hold the data until there is a success communication with slave.

Is this a doable and "easy" task using Xbee? Anyone that already try to do something like this that can guide me?

I was reading that there is a device nRF24l01 that is very cheap and can do exactly what I need. Just that I don't really know how to start.

Appreciate any advice or help.

i would just use ESP8266s to combine the receiver hardware and the MCU into one cheap unit, capable of hundreds of peers and easily portable w/o interference concerns.

Also with the ESP8266 there is no "master" to send the data to first. Each one is its own master and just does the POST itself.

So what you recommend me is just to use ESP8266 directly posting to my network? I have to check that with my customer because they dont have WIFI in the area where we have the arduinos.

@dandavis ESP8266 allows you to have other ESP8266s as clients and have as the master?

yes, you can have one ESP act as a "wifi router" (AP) and the others as "clients" (STATION). The AP one can even perform a dual-role and iteself talk to a wifi router while accepting input from all the clients.

It really depends on the communication range and context required.
If your slaves are within 10-20 meters from the master device and the environment is not polluted (in terms of magnetic field) you can achieve good results with very inexpensive nRF24L01+ modules which operate in the 2.4GHz.
If you need to cover greater distances (in the order of 100 meters) or a polluted environment then you have to resort to shorter wavelengths or more powerful devices, but that brings in the question on how are you powering your slaves: on battery power those ranges get pretty power hungry.
Generally speaking I would say this question should be rejected as it's going to start a debate rather than provide a solution.
You can get some introductions on how to use nRF24L01+ modules simply searching online:

some posts on my blog
the Arduino library I always advice
a pretty valid guide

nRF24L01+ with power amp and SMA antenna I achieve 300m+ reliable communication in quite a polluted area (many WiFi access points around - housing estate with lots of internet users).

yup Majenko, in my tests I managed to achieve 900m, but I was in open space (no walls) even if pretty polluted (residential area with plenty of WiFi routers) using an SMA antenna, noise attenuation circuit and power amplification, but it was also drawing 400mA when transmitting (yes, just a short burst, but it's almost half an amp!). And anyway I wouldn't personally consider those reliable comm, but, as I said, it's a matter of context: IR could be better than radio depending on the context.... underwater you might want to go ultrasonic, as an example :-D

Really appreciate the feedback, i think thats the way I have to go, and also I will consider as the other people said using ESP8266 posting directly to server I guess.


text:
Arduino SDFat Libray overwrites last value
I'm trying to create a comma delimited file using this SDFat library
Calling this code creates my file
const char Header[24]="Desired RPM,Output RPM\n";
...
foo()
{
  SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
  SpeedCache.write(Header);
  SpeedCache.sync();
}
...

After running, I have a file containing

Desired RPM,Output RPM'\n'

When I call the following function, I want it to add int target and int reference to the bottom of the file.
bool SDClass::SetLine(SdFile Cache,int target, int reference)
{
  bool good = false;
  char NewLine[32];
  Cache.seekEnd();
  sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
  Serial.println(good=Cache.write(NewLine));
  Cache.sync();
  return good;
}

On the first call, this works so for an input of SpeedCache,50,100 I get

Desired RPM,Output RPM'\n'
50,100'\n'

However, if I then write an input of SpeedCache,5,10 I get

Desired RPM,Output RPM'\n'
5,10'\n'

How do I adjust my function so that I will get:

Desired RPM,Output RPM'\n'
50,100'\n'
5,10'\n'

You just need to open the file in APPEND mode:
SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

O_APPEND
The  file  is  opened  in append mode.  Before each write, the file offset is positioned at the end of  the  file,  as  if  with               lseek.

You should also pass your file around by reference so it doesn't keep creating new copies of the internal structure:
bool SDClass::SetLine(SdFile &Cache,int target, int reference)

Adding | O_APPEND had no effect

Ok, passing the file by reference was the last thing needed for it to work.

How do you pass the file by reference?
SdFat sd;
SdFile DataFile;

isSD = DataFile.open(FileName, O_WRITE | O_CREAT | O_AT_END);

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


text:
Include Adafruit_RGB LCD Shield library in class
I'm trying to make a class to expand on the functionality of the Adafruit-RGB-LCD-Shield-Library I'm creating this based on what I see from this post.
class LcdMenu
{
 #include <Adafruit_MCP23017.h>
 #include <Adafruit_RGBLCDShield.h>
 public:
 Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu *LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM->Setup();
  LcdM->lcd.setBacklight(VIOLET);
}

However, I'm getting the following error:

C:\Users\jschere2\AppData\Local\Temp\ccUzvCmX.ltrans0.ltrans.o: In function `main':
ccUzvCmX.ltrans0.o:(.text.startup+0xf0): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::begin(unsigned char, unsigned char, unsigned char)'
ccUzvCmX.ltrans0.o:(.text.startup+0xf8): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::setBacklight(unsigned char)'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Move your #include statements outside the class definition.
You declare a pointer, but never allocate space for it with new. I see no need for a pointer.
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu
{
 public:
     // default ctor will be called here.
     Adafruit_RGBLCDShield lcd;

     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.lcd.setBacklight(VIOLET);
}

Also note: you are not extending the Adafruit_RGBLCDShield class as in the example you linked. To do that:
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu : public Adafruit_RGBLCDShield
{
 public:
     void Setup()
     {
      begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.setBacklight(VIOLET);
}

Ok, in my larger program should I allocate space for the pointer? What is the advantage of having a pointer in a larger program?

The advantage to using pointers is to create objects on-the-fly. For example, create an object, use it, then free the memory associated with it. (There are other uses for pointer.  This is just one example). If the object exists for the life of the program, a pointer is not needed.

Ok, What metric should I use to determine if I should extend the class or keep it separate?

You could use the "has-a/is-a" concept. Is your class an LCD ("is a") or does it just use one ("has a")? Here's an SO question that discusses it: HAS-A, IS-A terminology in object oriented language

Ok and I should extend the class if LcdMenu is a(n) Adafruit_RGBLCDShield?

In this case, it looks like extending it would make sense.


text:
Arduino/Arduino clone board suggestions
I am planning to buy a Arduino board. I am also considering Arduino clones, too. My requirements are that the board should inbuilt communication modes like Ethernet, WiFi and a SD card slot, too. Also the board should have a decent amount of memory and the processor must be a a little more powerful than the Uno. The board must be capable of running a OS if possible!
I was looking at the Yun and Due. The Yun has all the communication modes but runs on a low end processor. The Due on the other hand runs on a ARM processor but has none of the communication modes. So now I am in a fix.
Which board should I choose?

Wait... the Uno can run Linux!!! Also, it's not a clone (and probably not on topic for this site) if it's not a replica of an official Arduino board.

I would go with a Yun. Despite having a low end CPU, it runs at 400MHz and the disk space can be expanded using the uSD card (see this blog post).
If you don't plan to make CPU intensive tasks (such as real time video streaming and manipulation), the Yun is a nice tool. Otherwise, the Tre fits better (however, at the time of writing, it still has to be released).

Can the YUN do multitaking ? Also do you have any ideas about arduino clones ?

@cache No, no Arduino board can do hardware multithreading AFAIK... You can do software multithreading... Also, it's not a clone if it's not a replica of an official Arduino board. Therefore, asking for a clone is the same thing as asking for a board.

The Yun can do multitasking on the Linux side only.

@FedericoFissore - untrue.  Multitasking is a software feature.  Things like having lots of memory, protection modes, or virtual cores etc certainly make it easier, but it's ultimately a function of the software, not the hardware.

@ChrisStratton agree. I thought cache was actually talking about multithreading (executing two different codes at the same time)

@all : My apologies. I wanted to do multithreading. So to execute that one would need the hardware capable to perform the task.

@AnnonomusPenguin : Yes i do understand what a clone means and i do have some clones too. These clones have the same architecture as the original but with added features.
Coming to the part where a UNO running linux , really ? It says here that "it takes two hours to boot up to a bash prompt, and four more to load up Ubuntu and login" If starting itself takes this much time, then when will i run my programs ?

@cache No, you're talking about a derivative. A clone is pretty much an exact duplicate (with a few minor changes). As far as the Linux computer, I wasn't saying it is viable, only that it is possible.

So as of now my best bet would be to get a YUN , right ?


text:
for() loop doesn't seem to break?
So I'm quite new to the whole Arduino coding but constructed a sketch that does work, but I think it doesn't work properly. So I'd love to get some advice on how to improve it.
This script is currently running on a Wemos ESP8266 chip attached to a 1 meter WS2812 144 LED strip.
My questions:

The loop is set to break when fadein is higher then 254.
When I try to break it at fadein == 255 the loop doesn't work anymore as it the fadein value directly jumps to 255. Why?

When I set the delay to zero the led flicker due to too fast updating. however, this flickering continues even after the for loop is broken, which makes me conclude that the for loop is still running even when the break is applied.
Of course this is no longer an issue when the delay is set higher (as it is supposed to be) but it still seems a waste of processing power to keep the for loop active while it's not doing anything new anymore
how can i completely stop the loop from being executed?

How can this be done differently / more effective?

The code
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fade in counter
int led = 0;                                                          //init led counter

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }
}

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255

    }

}

+1 for properly formatted code .... if i could, i'd give you another +1 for the comments being out of the way of the code

Consider the sequence of values of "fadeIn". It starts at 8 and in incremented by 16.  So: 8, 24, ... 248, 264, ... .  It is never exactly 255.  So you never break out of your "for" loop.
There is only 1 delay in your example code.  It is difficult to associate the described behavior in your question and the location of the delay.
Arduino programming is actually C and C++ programming.  Developed at Bell Labs, this language has been around for decades and there are countless books on the subject.  Rather than rewriting your program (someone might yet still do this) I would recommend leaning C programming and if you want to write Arduino library software then C++ programming as well.

correct, i wanted to be flexible with the increment value. therefor this if was added at the end:
if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
fadeIn = 255;                                                     //clamp fadeIn value to 255
}

As you are new to stack exchange I would recommend the following: Ask one question at a time.  And do not hesitate editing your question to make the question better.   This is not a forum.  The questions should stand on their own and not depend on the discussion.  Be careful not to ask open ended questions nor opinions.   These types of questions usually get flagged and people will not answer them.  When writing your questions keep in mind others will search for your question and the answers posted.  So make the question concise and easy to understand.

thanks for the suggestions. I'll keep them in mind with future posting
I know there are books and I'm reading as much as I can online, but to do a full course on programming to get 1 led function to run would be a bit unbalanced for me (plus i'm a graphics man, not a heavy coder).
so I was hoping to get some advice on this 'simple' function that looks to be constructed properly from all references I found but somehow doesn't seem to work like it should

This is doing an assignment, not the comparison  you are expecting
if (led = 144

Need == for the comparison

I believed so too originally, but when I try this the function breaks and the fadeIn never increases.. so I left the led = 0 in it as led == 0 doesn't work

okay.. figured this one out.. it's never 144 as I have 144 leds but it start counting at 0 thus never reached 144 but only 143 as max

Ok, thanks for all your help, found the solution to make it stable.
I think I got thrown off by the fact the led = 144 did (magically) seem to work outside the loop but led == 144 didn't work at all.
turns out i was counting the leds wrong (it's from 0-143 instead of 1-144) and that made all the other pieces fall into place.
tnx
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fadein value
int fadeIncr = 16;                                                    //init fadein increments

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(1);
    if (led == 143) {                                                  //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=(fadeIncr);                                              //increase fadeIn value with 16
      fadeIn=constrain(fadeIn, 0, 255);                                // clip value range
        Serial.println(led);                                           //print led counter value
        Serial.println(fadeIn);                                        //print fadein
    }
    if (fadeIn == 255) {                                               //if the fadeIn value exceed 255
      break;                                                           //stop led animation
    }
  }
}

You close your for() loop right after the if statement that contains the break. No where in that for() loop do you change fadeIn, so there is nothing to break out of.
If you move the } that closes the for loop to below the code that changes fadeIn, then the break has an opportunity to be executed:
void loop() {
  for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255
    }
  }
}

well, that the funny thing.. when i tried this before (or use your code) the loop doesn't run at all somehow.
I thought i needed to keep those last 3 if's out of the loop

There are other bugs, pointed out in the other answers, such as the assignment operator used in place of a comparison operator. I was only noting the bug of a loop break condition not able to be met if the condition doesn’t change within the loop.

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


text:
Arduino Driver can I use only PNP?
is it possible to use a normal PNP transistor to drive a motor?
I'm kinda new to this stuff so I want to be on the safe side, so I don't damage my Arduino Uno because of the motor.
I have made a motor driver? https://circuits.io/circuits/2493784-test-1
But I'm not sure if i have done right and I wont break any components.
So does this work without any problems and have I done it right?
I'm not trying to make a H-bridge because I need both PNP and NPN?
EDIT:Picture

That diode in the circuit is doing nothing. And it's not a good idea to put a resistor in series with a motor as the motor will draw a lot of current, thus the resistor producing heat. Get a motor that matches (by being above) the battery's voltage.

@Bradman175 Why do you think the diode is doing nothing? IMO it is absolutely vital for this circuit to protect it from overvoltage.

Look again at the way he wired it. I know diodes in reverse are used to prevent the inductance from creating too much voltage. Forgot to say that.

You can upload images as part of your post. That is preferable to including a link that some people can't open.

In addition to your circuit being seriously mixed up, you should really avoid using 9v "transistor radio" batteries for motors - they won't last long, and while they are working the motor performance will be reduced  by the internal impedance of these weak batteries.

You need an NPN transistor to run a motor like that off of an arduino. Take a look at this article: https://learn.sparkfun.com/tutorials/transistors

Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because Vb would always be less than Ve.

Using an NPN transistor is the way to go here. Keep in mind that you can't control the direction of a motor with just one transistor, however.

When connecting together several circuits that have different supply
voltages, common practice is to make them all have a common negative
supply rail. This is called “common ground”. As explained in Majenko’s
answer, you would need an NPN transistor for that.
If you want to use a PNP instead, then you could forget the common
practice and do everything “backwads”: if you connect together the positive
ends of the power supplies, you will have a “common VCC”
instead of a common ground. Relative to the Arduino ground, your
9 V battery will have one pole at +5 V and the other at
−4 V.
The wiring is the following:

connect the emitter to +5 V (Arduino +5 and battery +)
connect the base to an Arduino output through a resistor
connect the collector to the motor
connect the other end of the motor to the battery −
put a free wheeling diode in parallel with the motor.

Edit: Below is an ASCII art rendering of the circuit. Beware that
the motor is ON when the Arduino output is LOW.
+-----------+
|         5V|-----------------+-------------------+
|           |                 |                   |
|  Arduino  |                 |                   |
|           |    ,-----.  B |< E                 ___ +
|        D13|----|     |----|    PNP              _
+-----------+    `-----'    |\                   ___
                              |C                  _
                              |                  ___
                              +---------+         _
                              |         |        ___ 9 V batt.
                              |         |         _
                             ---        |        ___
                              ^       motor       _
                             / \        |        ___
                             ---        |         _  −
                              |         |         |
                              |         |         |
                              +---------+---------+

Is this method safe or so-so? I have a lot of PNPs that can carry 80 volts, and always use NPNs for driving voltages higher than 5.

@user400344: We all use NPNs: it's the standard practice, and it feels kind of weird to have the + side of the supplies as a common reference. As always, it's safe as long as you are within the component's specs.

Despite the fact that the circuit you have is completely wrong, there is one fundamental thing that is stopping you using a PNP transistor.
With an NPN transistor you have to raise the voltage on the base above the ground voltage (this voltage is called V_BE, the Voltage between Base and Emitter). Typically that voltage is around 0.7V.
With an PNP, because the emitter is wired to your 9V rail, V_BE must therefore be relative to 9V, not ground, so the voltage on the base must be less than 0.7V below 9V to turn on. Which in itself is fine - a LOW will be around 0V, which is about 9V less than 9V. So it will turn on. The problem comes when you want to turn it off. You need to get the base voltage above 8.3V (9V - 0.7V), and that is impossible for an Arduino to do.
So normally a PNP transistor is switched by using an NPN transistor to switch the base of the PNP between 9V (pulled up through a resistor) and 0V (switched through the NPN).
And that then becomes pretty much pointless, since you are then adding a second, NPN, transistor, and you could just as well use the NPN alone to switch the motor, making the PNP completely redundant.

I don't know what you are trying to do, because the link fails to display in my browser.
In general there is no reason why you can not use a PNP transistor, providing you use appropriate polarities, and assuming common-emitter mode, reference to the +5V rail rather than Gnd.
Having said that, you would need some specific reason. In general NPN devices are cheaper and/or outperform PNP, all other things being equal.

Link works on my iPad. You just got to wait for the image for a while. It should at least have a loading animation.


text:
multiple relays not triggering correctly
quick description of the sketch: its a clap on/off relay that turns on only when it's dark.
Cannot seem to get the relays to stay off. What happens is they are off by default then when I do the double clap to turn them on that works, after this I double clap to turn them off and then go off then immediately go on again. I can get a single relay to work perfectly but when I uncomment the rest there seems to be a problem.
I am assuming it has something to do with the delay for the clap sensor, but I am not entirely sure-- I have tried quite a few things to try to resolve it but am really lost as to why this might be happening. ideas?
int soundSensor = A2;
int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;

//Light sensor
int photocellPin = A1;
int photocellReading;
int LEDbrightness;

//int delayValue = 100;
int photoSensor = 0;

void setup() {
  pinMode(soundSensor, INPUT);
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  /////////////
  // photo sensor
  ////////////////////
  photocellReading = analogRead(photocellPin);
  photocellReading = 1023 - photocellReading;
  LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

  if(photocellReading > 500){
      photoSensor = 0;
  }
  if(photocellReading < 500){
    photoSensor = 1;
  }

  /////////////
  // clap sensor
  /////////////////////
  int sensorState = digitalRead(soundSensor);
  //erial.println(sensorState);
  if (sensorState == 1)
  {
    if (claps == 0)
    {
      detectionSpanInitial = detectionSpan = millis();
      claps++;
    }
    else if (claps > 0 && millis()-detectionSpan >= 50)
    {
      detectionSpan = millis();
      claps++;
    }
  }

  if (millis()-detectionSpanInitial >= 500)
  {
    if (claps == 2)
    {
      if (doubleClap == 0)
        {
          doubleClap = 1;
        }
        else if (doubleClap == 1)
        {
          doubleClap = 0;
        }
    }
    claps = 0;
  }

  if(doubleClap == 1 && photoSensor == 0){
    digitalWrite(relay, LOW);
    digitalWrite(relay2, LOW);
    digitalWrite(relay3, LOW);
    digitalWrite(relay4, LOW);
    Serial.println("off");

  }
  else{
    digitalWrite(relay, HIGH);
    digitalWrite(relay2, HIGH);
    digitalWrite(relay3, HIGH);
    digitalWrite(relay4, HIGH);
    Serial.println("on");
  };

}

I suggest some debugging displays. After a clap is registered, print the value of doubleClap and claps. I suspect they won't be exactly what you expect. Maybe also print the current value of millis() which will probably help you debug.

It may be the fact that the photosensor is floating around 500 value and causing "false" triggers. Try to add a threashold or create a hysteresis cycle.

As it happens, you are debugging in the dark.  You have half a dozen devices attached to (presumably) some Arduino, driven by some hard-to-read code that might not work properly even if all the devices work ok, and definitely won't work properly if any of them fail or are incorrectly attached.
For example, you can't tell from that code whether your photoSensor works, whether your clap sensor works, or whether your relays work.  Before messing around further trying to test all at once, run some definitive tests on each device individually.  For example, run the following sketch and see if your system is able to turn on all of the relays at the same time.
// Test if relays work ok: First individually for a second each,
// then all together for 2.5 seconds
enum {relay=A0, relay2=A3, relay3=A4, relay4=A5, nRelays=4};
byte rePins[] = { relay, relay2, relay3, relay4};

void setup() {
  for (int r=0; r<nRelays; ++r) {
    pinMode(rePins[r], OUTPUT);    // Set pin to outputs
    digitalWrite(rePins[r], LOW);  // Turn off relay
  }
  Serial.begin(115200);
}

void loop() {
  byte r;
  // Turn relays on individually for a second each, with half-second gaps
  for (r=0; r<nRelays; ++r) {
    delay(500);         // Wait half a second
    Serial.print("Turning on relay #");
    Serial.print(r+1);
    Serial.print(" at ");
    Serial.println(millis());
    digitalWrite(rePins[r], HIGH); // Turn on relay
    delay(1000);           // One on for a second
    digitalWrite(rePins[r], LOW);  // Turn off relay
  }

  // Turn all the relays on
  Serial.print("Turning all relays on at ");
  Serial.println(millis());
  for (r=0; r<nRelays; ++r)
    digitalWrite(rePins[r], HIGH); // Turn on relay

  delay(2500);          // Wait 2.5 seconds

  // Turn all the relays off
  Serial.print("Turning all relays off at ");
  Serial.println(millis());
  for (r=0; r<nRelays; ++r)
    digitalWrite(rePins[r], LOW); // Turn off relay
}

Next, write a sketch to report results from photosensor and clap sensor readings.  Once you know if your hardware is working, try to get your double-clap logic to work without involving the photosensor, or vice versa.  Also, try to make the double-clap logic work just using a button in place of the clap sensor.
Note, to shorten your code and to get rid of some of the features that make it hard to read, do some of the following changes.  With the code slightly shorter, it may be easier to comprehend and debug.
(a) Instead of introducing program constants as integer variables, introduce them as program constants.  For example, instead of the verbose
int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;

say something like
enum {relay=A0, relay2=A3, relay3=A4, relay4=A5};

which tells the compiler that relay is a constant with the value A0, etc.
(b) Since you don't use variable LEDbrightness for anything, take it out.  With that gone, change the verbose
photocellReading = analogRead(photocellPin);
photocellReading = 1023 - photocellReading;
LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

if(photocellReading > 500){
    photoSensor = 0;
}
if(photocellReading < 500){
  photoSensor = 1;
}

to
photoSensor = analogRead(photocellPin) > 523;

which will set photoSensor to 0 or 1 much as before.  (It is slightly different: It handles a photocellReading==500 case that your code ignores.)
(c) Change the verbose and badly formatted
  if (doubleClap == 0)
    {
      doubleClap = 1;
    }
    else if (doubleClap == 1)
    {
      doubleClap = 0;
    }

to
 doubleClap = 1 - doubleClap;

(d) Refactor to cut about half the code involving detectionSpan.


text:
Set pins to LOW over time
I've written a simple sketch that adds threshold to an PIR sensor. If the PIR sensor sends 3 HIGH ex. HIGH...LOW...HIGH...LOW...HIGH (The LOW == no movement) it will trigger and alarm.
I want to reset the counter of HIGHs if there's no movement detected. The problem is the loop will get delayed if I put it inline. My code: (Don't mind my code, I'm pretty newbie)
int calibrationTime = 30;
int pirPin = 5;
int ledPin = 6;
int sensorState;
int stateCount = 0; //How much movement is detected
int stateThreshold = 3; //THRESHOLD
bool isSensorHigh;

void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  digitalWrite(pirPin, LOW);
  Serial.print("calibrating sensor ");
  for (calibrationTime; calibrationTime > 0; calibrationTime--) {
    Serial.print(calibrationTime);
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}
void loop() {
  sensorState = digitalRead(pirPin);
  //Serial.println(sensorState);
  if (sensorState == 1) {
    isSensorHigh = true;
  }
  if (sensorState == 0 && isSensorHigh == true) {
    isSensorHigh = false;
    stateCount++;
  }
  //Set pins 2,3,4 here to LOW if there's no movement detected over time
  if (stateThreshold == 3) {
    switch (stateCount) {
      case 1:
        digitalWrite(2, HIGH);
        break;
      case 2:
        digitalWrite(3, HIGH);
        break;
      case 3:
        digitalWrite(4, HIGH);
        break;
    }
  }
  if (stateCount == stateThreshold) {
    blinkLeds();
    delay(3000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(ledPin, LOW);
    stateCount = 0;
  }
  Serial.println(stateCount);
  delay(150);
}

void blinkLeds() {
  for (int x = 4; x > 0; x--) {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    delay(1000);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    delay(1000);
  }
}

Use millis() instead on delay.
Ref: https://www.arduino.cc/en/reference/millis

I could get the span between the millis() and use that value. Pretty much all I need. Thanks