text:
Why am I only seeing white screen in TFT 1.44 ST7735?
I just bought the 3rd TFT and in all my attempts I get the white screen I don't know what I'm doing wrong!
This time I bought it and followed their instruction's guide
I created this schematic using Fritzing which is the one I'm using but still I am getting the white screen again

Here are some Photos of what is the TFT displaying.
Finally, I did also used the recommended testing code which is listed in:
File > Examples > Adafruit ST7735 and ST7789 library > graphicstest
Also, I have did commented the slightly changed. So this is the code I'm using:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  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.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#ifdef ADAFRUIT_HALLOWING
  #define TFT_CS        39 // Hallowing display control pins: chip select
  #define TFT_RST       37 // Display reset
  #define TFT_DC        38 // Display data/command select
  #define TFT_BACKLIGHT  7 // Display backlight pin
#elif defined(ESP8266)
  #define TFT_CS         4
  #define TFT_RST        16
  #define TFT_DC         5
#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8
#endif

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  Serial.print(F("Hello! ST77xx TFT Test"));

#ifdef ADAFRUIT_HALLOWING
  // HalloWing is a special case. It uses a ST7735R display just like the
  // breakout board, but the orientation and backlight control are different.
  tft.initR(INITR_HALLOWING);        // Initialize HalloWing-oriented screen
  pinMode(TFT_BACKLIGHT, OUTPUT);
  digitalWrite(TFT_BACKLIGHT, HIGH); // Backlight on
#else
  // Use this initializer if using a 1.8" TFT screen:
 // tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

  // OR use this initializer (uncomment) if using a 1.44" TFT:
  tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 0.96" 180x60 TFT:
  //tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

  // OR use this initializer (uncomment) if using a 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240
#endif

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
  delay(1000);

  // tft print function!
  tftPrintTest();
  delay(4000);

  // a single pixel
  tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
  delay(500);

  // line draw test
  testlines(ST77XX_YELLOW);
  delay(500);

  // optimized lines
  testfastlines(ST77XX_RED, ST77XX_BLUE);
  delay(500);

  testdrawrects(ST77XX_GREEN);
  delay(500);

  testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
  delay(500);

  tft.fillScreen(ST77XX_BLACK);
  testfillcircles(10, ST77XX_BLUE);
  testdrawcircles(10, ST77XX_WHITE);
  delay(500);

  testroundrects();
  delay(500);

  testtriangles();
  delay(500);

  mediabuttons();
  delay(500);

  Serial.println("done");
  delay(1000);
}

void loop() {
  tft.invertDisplay(true);
  delay(500);
  tft.invertDisplay(false);
  delay(500);
}

void testlines(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, 0, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, 0, 0, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
    delay(0);
  }
}

void testdrawtext(char *text, uint16_t color) {
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);
}

void testfastlines(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t y=0; y < tft.height(); y+=5) {
    tft.drawFastHLine(0, y, tft.width(), color1);
  }
  for (int16_t x=0; x < tft.width(); x+=5) {
    tft.drawFastVLine(x, 0, tft.height(), color2);
  }
}

void testdrawrects(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
  }
}

void testfillrects(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=tft.width()-1; x > 6; x-=6) {
    tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
  }
}

void testfillcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=radius; x < tft.width(); x+=radius*2) {
    for (int16_t y=radius; y < tft.height(); y+=radius*2) {
      tft.fillCircle(x, y, radius, color);
    }
  }
}

void testdrawcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
    for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
      tft.drawCircle(x, y, radius, color);
    }
  }
}

void testtriangles() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 0xF800;
  int t;
  int w = tft.width()/2;
  int x = tft.height()-1;
  int y = 0;
  int z = tft.width();
  for(t = 0 ; t <= 15; t++) {
    tft.drawTriangle(w, y, y, x, z, x, color);
    x-=4;
    y+=4;
    z-=4;
    color+=100;
  }
}

void testroundrects() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 100;
  int i;
  int t;
  for(t = 0 ; t <= 4; t+=1) {
    int x = 0;
    int y = 0;
    int w = tft.width()-2;
    int h = tft.height()-2;
    for(i = 0 ; i <= 16; i+=1) {
      tft.drawRoundRect(x, y, w, h, 5, color);
      x+=2;
      y+=3;
      w-=4;
      h-=6;
      color+=1100;
    }
    color+=100;
  }
}

void tftPrintTest() {
  tft.setTextWrap(false);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 30);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_YELLOW);
  tft.setTextSize(2);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(3);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_BLUE);
  tft.setTextSize(4);
  tft.print(1234.567);
  delay(1500);
  tft.setCursor(0, 0);
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(0);
  tft.println("Hello World!");
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(p, 6);
  tft.println(" Want pi?");
  tft.println(" ");
  tft.print(8675309, HEX); // print 8,675,309 out in HEX!
  tft.println(" Print HEX!");
  tft.println(" ");
  tft.setTextColor(ST77XX_WHITE);
  tft.println("Sketch has been");
  tft.println("running for: ");
  tft.setTextColor(ST77XX_MAGENTA);
  tft.print(millis() / 1000);
  tft.setTextColor(ST77XX_WHITE);
  tft.print(" seconds.");
}

void mediabuttons() {
  // play
  tft.fillScreen(ST77XX_BLACK);
  tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
  delay(500);
  // pause
  tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
  delay(500);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
  delay(50);
  // pause color
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}

Please don't mark this question as duplicated because I looked at the other guy he/she was using different guide.. the one I'm using is posted by the company I purchased the TFT from.

White screen = display not being initialized. Triple check your wiring and code.

did you insert SD card? if yes, remove it

Juraj - Yes I did it with and without but the output still same. I don't know very frustrating.

Majenko - Thank you for the comment but I'm not expert and I did same as I should be followed  by the guide multiple times and I did upload some photos of what the wiring... I'm sorry I'm not sure what to do next

is your Arduino here the Arduino Micro too as in the next question?

@Glorfindel Hey if you still looking for questions to edit, then go to my recent question asked, I'm sure you will find a common or period missing to fix. I guess that is your job! Way to go!

@Juraj Yes same one

I would like to suggest some changes in your code i.e.
Your Code:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  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.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#ifdef ADAFRUIT_HALLOWING
  #define TFT_CS        39 // Hallowing display control pins: chip select
  #define TFT_RST       37 // Display reset
  #define TFT_DC        38 // Display data/command select
  #define TFT_BACKLIGHT  7 // Display backlight pin
#elif defined(ESP8266)
  #define TFT_CS         4
  #define TFT_RST        16
  #define TFT_DC         5
#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8
#endif

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

changes suggested:
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  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.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 (including HalloWing) use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

// For 1.54" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
#define TFT_MOSI 11  // Data out
#define TFT_SCLK 13  // Clock out
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

Replace your that part with one I suggested as You commented tha SCK and MISO pins in your code so no data transfer is happening on those pins. Secondly I made changes according to your hardware configuration as well.

You are a genius ... haha No more stupid white screen ... I see a colorful screen

I hope I will not be a bother. I just had a request and not sure if it could work. I was going to use MicroSD but since this has one, can I use it externally? like can I put .wav sound and play it in a speaker? Since you know the wiring I was hoping you could provide me with code which doses load sound file from that sd card and output to a speaker at maybe pin 3? This will help me a lot and make the project smaller so it can be wearable. Thank you

we don't provide code here, we can help you with you problem and provide solution for the problems but not the code.

alright I understand. Thank you anyway!

Maybe I guess I should ask this,  can I still use the built-in MicroSD externally or only it will be for loading images to the TFT?

I don't understand this still use the built-in MicroSD externally, please be clear about what are you looking for.

That TFT 1.44 has a chip for Micro card and they told me it is for loading images .bmp to the screen.. so I was wondering if I can store sound files .wav there and output it to a speaker in different pin  instead of buying this Micro SD Card Breakout Board   - hopefully I explained right sorry for my English.

Do you have exposed pins for Micro SD? If yes you can try.

I'm really not good with this stuff but anyway that is okay ha ha

Sorry, forgot to mark it as the answer!

@Vaibhav, you solved this by switching to bit-banged SPI. you could not know this but a photo in next question revealed an Arduino Micro, not Nano

@Juraj what you guys talking about... you guys are way smart I don't understand these terms. It blacks me out!

the TFT library can work on any pins if you specify them. It will use software SPI. That is why it worked on 'wrong' pins.

Alright, I have made a lot of improvement and added stuff.. and now I don't understand why this line USE_ARDUINO_INTERRUPTS true case my TFT half-working. don't think you need my code but here is it https://github.com/WorldFamousElectronics/PulseSensorPlayground/issues/101

@Juraj I have another problem with the last question I asked in my profile


text:
ESP8266 webserver does not return latest HTTP response
I tried getting a HTTP response from an ESP8266 which is in HTTP server mode, I am getting a response but not the latest one, response is always one command previous to that of my request to the ESP.
Also first time I don't get any response, from the nd request response start coming but previous.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>   //ESP Web Server Library to host a web page

const char* ssid = "SpruceRND";
const char* password = "sprucernd1234";

ESP8266WebServer server(80);   // server at port 80 (http port)

//Variable to store the HTTP request
String inputString ="";
boolean stringComplete = false;
String Clientquery ="";  //for store all query params
char query_array[30];    //for store all query character
int LEDPin = 4;

void ESPserialEvent()
{
  boolean x=0;
  Serial.println("Working ESPserialevent....");
  while (Serial.available())
  {
    char inChar = (char)Serial.read();    // get the new byte:
    if (inChar == 2)   //check if 1st byte is 2
    {
      x=1;
    }
    if (x == 1);
    {
    inputString += inChar;   // add it to the inputString:
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    }
    if (inChar == 3) //check if 1ast byte is 3
    {
      stringComplete = true;
      x=0;
    }
  }
}

void  handleNew()
{
  server.send(200, "text/plain", "Hello! SPRUCE"); //200=http status code,text/plain=content type,message
}

void handleMstring()
{
  Clientquery = server.arg("tx");    //Gets the value of the query parameter
//  Clientquery.toCharArray(query_array, sizeof(Clientquery)); // convert to chararry (buffer,length)
//  if (query_array[0] == 2 )
//  {
    Serial.println(Clientquery);
//  }
//  else
//  {
//     Serial.println("Incorrect string....");
//  }
  Clientquery="";
  ESPserialEvent();
  if (stringComplete == true)
  {
    server.send(200, "text/plain",inputString);
    //Serial.println("Response from Mcu=" +inputString);
    //Serial.println("");
    inputString ="";
    stringComplete = false;
    //Serial.println("Buffer clear...");
  }
}

void setup(void)
{
  pinMode(LEDPin, OUTPUT);
  digitalWrite(LEDPin, LOW);
  delay(1000);
  Serial.begin(9600);
  WiFi.begin(ssid, password); //begin WiFi connection
  Serial.println("Connecting to....");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/test", handleNew);
  server.on("/senddata", handleMstring);
  server.begin();
  Serial.println("Web server started!");
}

void loop(void){
  server.handleClient();
}

AT commands or esp8266 sketch? show the sketch

i don't know.How to post code

the cause of your problem is if (stringComplete == true) in handleMstring

I don't  what is the problem can you please help me. I am beginner.

It is a coding logic problem, not an Arduino problem.

one thing that produces a delay between an input and an output in any program is EOL (end of line) not being sent at the end of the command .... check that complete commands are being sent

source: Stack Exchange

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

sort: votes


text:
Error: "undefined reference to ..." when calling non-void class' functions from within class
I haven't used an Arduino for anything as complicated as this project before (single sketch projects so far), and am struggling getting my code to compile now that I'm creating my own libraries for the project.
I can see that it's the class' methods that return something that cause an issue, those that directly edit the classes variables instead don't appear to cause issues when compiling (i.e. void functions).
I can't share the actual code, but here's an altered and stripped down version that shows the same issue.
The sketch:
//Issues.ino

#include "CmdLib.cpp"

void setup() {
  //Setup USB
  Serial.begin(19200);
  Serial.flush();

  //Setup Bluetooth
  Serial0.begin(9600);
  Serial0.flush();
}

void loop(){
  CheckForPCMessages();       //Parses any messages from USB and Bluetooth
  //All the other things we need to do
}

void CheckForPCMessages(){
  CheckForMessages(&Serial);  //Check USB first
  CheckForMessages(&Serial0); //Then check Bluetooth
}

template <class T> void CheckForMessages(T *port){
  //Using function template so that works for USB and Hardware Serial
  if(port->available() != 0){
    String received_string = port->readStringUntil('\n');
    port->flush();
    Serial.print(received_string);
    Serial.println(" was received.");
    Command received_cmd(received_string);
    //Do stuff with the command (add it to a Q, etc, etc)
  }
}

The Header:
//CmdLib.h

#ifndef CmdLib_h
#define CmdLib_h

#include "Arduino.h"

enum CommandLabel{
  //Not a command
  NO_COMMAND = 0,

  //...
  //A whole bunch of other options that I can't share
  //...
};

enum CommandType{
  NA = 0,
  //...
  //A whole bunch of other options that I can't share
  //...
};

class Command{
  public:
    Command(String msg);
    String GetCmdStringFromMessageString(String full_string);
    CommandLabel GetLabelFromString(String labelstr);
    void SetLabelAndType(String labelstr);
    void SetLabel(CommandLabel label);
    void SetType(CommandLabel label);

  private:
    String _x = "";
    String _y = "";
    String _z = "";
    CommandLabel _label = NO_COMMAND;
    CommandType _type = NA;
};

#endif

The cpp file:
//CmdLib.cpp

#include "CmdLib.h"

Command::Command(String msg){
  String labelstr = Command::GetCmdStringFromMessageString(msg); //Separates label from msg
  Command::SetLabelAndType(labelstr); //Sets _label & _type vars
}

String GetCmdStringFromMessageString(String full_string){
  //Pulls out everything before first comma
  int first_comma = full_string.indexOf(',');
  String output;
  if(first_comma != -1){
    output = full_string.substring(0,first_comma);
  }
  else{
    output = full_string;
  }
  return output;
}

void Command::SetLabelAndType(String labelstr){
  CommandLabel label = GetLabelFromString(labelstr);  //Get label from string
  Command::SetLabel(label);                           //Set label
  Command::SetType(label);                            //Set type based on label
}

CommandLabel GetLabelFromString(String labelstr){
  //...
  //Cleverness to determine which to return...
  //...
  return NO_COMMAND;
}

void Command::SetLabel(CommandLabel label = NO_COMMAND){
  _label = label;
}

void Command::SetType(CommandLabel label){    //Set _type to appropriate type based upon label
  //...
  //Cleverness to determine which to return...
  //...
  _type = NA;
  return;
}

And here's the Error:

sketch\CmdLib.cpp.o: In function `Command::SetLabelAndType(String)':
[REDACTED]/temp/arduino_build_557572/sketch/cmdlib.cpp:24: undefined reference to `Command::GetLabelFromString(String)'
sketch\CmdLib.cpp.o: In function `Command::Command(String)':
[REDACTED]/temp/arduino_build_557572/sketch/cmdlib.cpp:6: undefined reference to `Command::GetCmdStringFromMessageString(String)'
collect2.exe: error: ld returned 255 exit status
exit status 255
  Error compiling for board Fubarino Mini.

I've found previous answers where the same compile error occurred with class variables that were called to without being given an initial value, but can't find similar solutions for the error when created by a call to a function.
Any help would be greatly appreciated.

You forgot to put the function in the class:
CommandLabel GetLabelFromString(String labelstr){

should be:
CommandLabel Command::GetLabelFromString(String labelstr) {

Also, on a side note, if you must use String objects (ugh!) then please pass them as reference so as to avoid needless heap allocation and data copying:
CommandLabel Command::GetLabelFromString(String &labelstr) {

... Damn it. Well, thank you for saving me from myself!
Edit: Good point on the String referencing - in this case I do need to use them, as I won't know the length of the char array being sent in advance

The simplest mistakes are often the hardest to spot. It's called going "code blind".

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


text:
I'm trying to make a program which you choose an angle
I'm trying to make a program which you choose an angle, and it tells you it's respective Sin, Cos and Tan. But, I can't figure out why all of the angles I use have the same answer (Sin 0, Cos 1 and Tan 0. Can someone help me out?
#include <math.h>
double angulo;
double seno;
double cosseno;
double tangente;
double rad;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {

 Serial.println("Programa para calcular sen, cos e tg");
 delay(1000);
 Serial.println("Digite o angulo");
 angulo = Serial.parseInt();
 rad = angulo*0,0174533;
 seno = sin(rad);
 Serial.println("Seno");
 Serial.println(seno);
 cosseno = cos(rad);
 Serial.println("Cosseno");
 Serial.println(cosseno);
 tangente = tan(rad);
 Serial.println("Tangente");
 Serial.println(tangente);

}

You have written
rad = angulo*0,0174533;

But, C++ uses the american decimal notation:
rad = angulo*0.0174533;

Thus, you have been multiplying angulo by zero every time.

I guess this is a language thing, where some cultures use a comma as a decimal indicator, and a full-stop as a thousands separator... I.e., they are backwards.

Saying it is backwards implies there is a correct (forward) and wrong (backwards) way, but of course they are merely different ways of denoting the same concept.

My way is right and every one else's is wrong ;) "Right" is whatever the majority of people use....

Doesn't the C++ comma operator calculate and discard the first expression and then use the following expression for the assignment?

https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work

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


text:
Switch Statement Alternative
I am working on a project where I've mapped an IR remote control to certain functions. I am currently using a massive switch statement to control the program based on the IR remote button pressed.
Is there a an alternative to using a switch statement, or is a switch the best way to go?
decode_results results; // Initialize the results

IRrecv irrecv(irPin); // Initialize the IR sensor

int buttonPressed;

void setup()
{
  Serial.begin(115200);
  Serial.println("Tile Controller");
  analogReference(DEFAULT);
  irrecv.enableIRIn(); // Start the receiver

  Wire.begin(); // Join the I2C network
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if(results.value != buttonHeld)
    {
      buttonPressed = results.value;
      Serial.println(buttonPressed,HEX);
    }

    switch(buttonPressed)
    {
      case 0x3AC5: // 11 - Brightness Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Brightness Up Held");
          brightnessUpHeld();
        }
        else
        {
          Serial.println("Brightness Up Pressed");
          brightnessUpPressed();
        }
        break;
      }

      case 0xFFFFBA45: // 12 - Brightness Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Brightness Down Held");
          brightnessDownHeld();
        }
        else
        {
          Serial.println("Brightness Down Pressed");
          brightnessDownPressed();
        }
        break;
      }

      case 0xFFFF827D: // 13 - Pause
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Pause Held");
          pauseHeld();
        }
        else
        {
          Serial.println("Pause Pressed");
          pausePressed();
        }
        break;
      }

      case 0x2FD: // 14 - Power
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Power Held");
          powerHeld();
        }
        else
        {
          Serial.println("Pause Pressed");
          powerPressed();
        }
        break;
      }

      case 0x1AE5: // 21 - Red
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red Held");
          redHeld();
        }
        else
        {
          Serial.println("Red Pressed");
          redPressed();
        }
        break;
      }

      case 0xFFFF9A65: // 22 - Green
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green Held");
          greenHeld();
        }
        else
        {
          Serial.println("Green Pressed");
          greenPressed();
        }
        break;
      }

      case 0xFFFFA25D: // 23 - Blue
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue Held");
          blueHeld();
        }
        else
        {
          Serial.println("Blue Pressed");
          bluePressed();
        }
        break;
      }

      case 0x22DD: // 24 - White
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White Held");
          whiteHeld();
        }
        else
        {
          Serial.println("White Pressed");
          whitePressed();
        }
        break;
      }

      case 0x2AD5: // 31 - Red 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red One Held");
          redOneHeld();
        }
        else
        {
          Serial.println("Red One Pressed");
          redOnePressed();
        }
        break;
      }

      case 0xFFFFAA55: // 32 - Green 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green One Held");
          greenOneHeld();
        }
        else
        {
          Serial.println("Green One Pressed");
          greenOnePressed();
        }
        break;
      }

      case 0xFFFF926D: // 33 - Blue 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue One Held");
          blueOneHeld();
        }
        else
        {
          Serial.println("Blue One Pressed");
          blueOnePressed();
        }
        break;
      }

      case 0x12ED: // 34 - White 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White One Held");
          whiteOneHeld();
        }
        else
        {
          Serial.println("White One Pressed");
          whiteOnePressed();
        }
      }

      case 0xAF5: // 41 - Red 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 2 Held");
          redTwoHeld();
        }
        else
        {
          Serial.println("Red 2 Pressed");
          redTwoPressed();
        }
        break;
      }

      case 0xFFFF8A75: // 42 - Green 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 2 Held");
          greenTwoHeld();
        }
        else
        {
          Serial.println("Green 2 Pressed");
          greenTwoPressed();
        }
        break;
      }

      case 0xFFFFB24D: // 43 - Blue 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 2 Held");
          blueTwoHeld();
        }
        else
        {
          Serial.println("Blue 2 Pressed");
          blueTwoPressed();
        }
        break;
      }

      case 0x32CD: // 44 - White 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 2 Held");
          whiteTwoHeld();
        }
        else
        {
          Serial.println("White 2 Pressed");
          whiteTwoPressed();
        }
        break;
      }

      case 0x38C7: // 51 - Red 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 3 Held");
          redThreeHeld();
        }
        else
        {
          Serial.println("Red 3 Pressed");
          redThreePressed();
        }
        break;
      }

      case 0xFFFFB847: // 52 -  Green 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 3 Held");
          greenThreeHeld();
        }
        else
        {
          Serial.println("Green 3 Pressed");
          greenThreePressed();
        }
        break;
      }

      case 0x7887: // 53 - Blue 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 3 Held");
          blueThreeHeld();
        }
        else
        {
          Serial.println("Blue 3 Pressed");
          blueThreePressed();
        }
        break;
      }

      case 0xFFFFF807: // 54 - White 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 3 Held");
          whiteThreeHeld();
        }
        else
        {
          Serial.println("White 3 Pressed");
          whiteThreePressed();
        }
        break;
      }

      case 0x18E7: // 61 - Red 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 4 Held");
          redFourHeld();
        }
        else
        {
          Serial.println("Red 4 Pressed");
          redFourPressed();
        }
        break;
      }

      case 0xFFFF9867: // 62 - Green 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 4 Held");
          greenFourHeld();
        }
        else
        {
          Serial.println("Green 4 Pressed");
          greenFourPressed();
        }
        break;
      }

      case 0x58A7: // 63 - Blue 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 4 Held");
          blueFourHeld();
        }
        else
        {
          Serial.println("Blue 4 Pressed");
          blueFourPressed();
        }
        break;
      }

      case 0xFFFFD827: // 64 - White 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 4 Held");
          whiteFourHeld();
        }
        else
        {
          Serial.println("White 4 Pressed");
          whiteFourPressed();
        }
        break;
      }

      case 0x28D7: // 71 - Red DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red DIY Up Held");
          redDIYUpHeld();
        }
        else
        {
          Serial.println("Red DIY Up Pressed");
          redDIYUpPressed();
        }
        break;
      }

      case 0xFFFFA857: // 72 - Green DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green DIY Up Held");
          greenDIYUpHeld();
        }
        else
        {
          Serial.println("Green DIY Up Pressed");
          greenDIYUpPressed();
        }
        break;
      }

      case 0x6897: // 73 - Blue DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue DIY Up Held");
          blueDIYUpHeld();
        }
        else
        {
          Serial.println("Blue DIY Up Pressed");
          blueDIYUpPressed();
        }
        break;
      }

      case 0xFFFFE817: // 74 - Quick
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Quick Held");
          quickHeld();
        }
        else
        {
          Serial.println("Quick Pressed");
          quickPressed();
        }
        break;
      }

      case 0x8F7: // 81 - Red DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red DIY Down Held");
          redDIYDownHeld();
        }
        else
        {
          Serial.println("Red DIY Down Pressed");
          redDIYDownPressed();
        }
        break;
      }

      case 0xFFFF8877: // 72 - Green DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green DIY Down Held");
          greenDIYDownHeld();
        }
        else
        {
          Serial.println("Green DIY Down Pressed");
          greenDIYDownPressed();
        }
        break;
      }

      case 0x48B7: // 73 - Blue DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue DIY Down Held");
          blueDIYDownHeld();
        }
        else
        {
          Serial.println("Blue DIY Down Pressed");
          blueDIYDownPressed();
        }
        break;
      }

      case 0xFFFFC837: // 84 - Slow
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Slow Held");
          slowHeld();
        }
        else
        {
          Serial.println("Slow Pressed");
          slowPressed();
        }
        break;
      }

      case 0x30CF: // 84 - DIY 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 1 Held");
          diyOneHeld();
        }
        else
        {
          Serial.println("DIY 1 Pressed");
          diyOnePressed();
        }
        break;
      }

      case 0xFFFFB04F: // 84 - DIY 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 2 Held");
          diyTwoHeld();
        }
        else
        {
          Serial.println("DIY 2 Pressed");
          diyTwoPressed();
        }
        break;
      }

      case 0x708F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 3 Held");
          diyThreeHeld();
        }
        else
        {
          Serial.println("DIY 3 Pressed");
          diyThreePressed();
        }
        break;
      }

      case 0x708F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 3 Held");
          diyThreeHeld();
        }
        else
        {
          Serial.println("DIY 3 Pressed");
          diyThreePressed();
        }
        break;
      }

      case 0xFFFFF00F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Auto Held");
          autoHeld();
        }
        else
        {
          Serial.println("Auto Pressed");
          autoPressed();
        }
        break;
      }

    }
    irrecv.resume(); // Receive the next IR value
  }
}

Can we have a glimpse at the portion of your code in question? This helps us to better understand how the decisions in your program are made and will lead to better answers.

You could have an array of structs, with each struct containing the key code, a name, a "pressed" function pointer and a "held" function pointer.

The array of structs sounds like a good idea. I've never used a function pointer before so I guess I've got some learning to do :)

Your switch statement isn't that big - I've seen bigger.
However, as @MarkSmith says, using an array of structs with key codes and function pointers would be a way to go.  For instance, you may have the struct:
struct button {
    uint32_t keycode;
    void (*press)();
    void (*hold)();
};

Populated with data it would look like:
const struct button buttons[] = {
    { 0x3AC5, brightnessUpPressed, brightnessUpHeld },
    { 0xFFFFBA45, brightnessDownPressed, brightnessDownHeld },
    ... etc ...
    { 0xFFFFF00F, autoPressed, autoHeld },
    { 0, 0, 0 }
};

Note the last entry of { 0, 0, 0 } - this is being used as an "end of list" marker. An alternative is to keep track of how many entries are in the list, but this makes adding / removing entries easier.
Then you can iterate through the list until you find a keycode that matches or the special keycode 0:
for (int i = 0; buttons[i].keycode != 0; i++) {
    if (buttons[i].keycode == buttonPressed) {
        if (results.value == buttonHeld) {
            buttons[i].held();
        } else {
            buttons[i].press();
        }
        break; // We found the button, no need to continue
    }
}

This method decreases the amount of code you have, but has the adverse effect of increasing the amount of RAM you use. It's a tradeoff between making the code simpler and using more RAM. If you can afford the RAM usage it can make things so much easier to read, since you have a simple table for the commands and a simple loop for finding the right entry in the table.

Wow, thanks for that reply & code examples. I'm definitely going to give it a try.

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


text:
how to make led fade on and blink while wav file plays
To clarify I'm extremely new to this and I'm using an Arduino Uno with a wave shield. My circuit works as intended but I haven't learned enough of the code to know what to do to make it do exactly what I want.
Right now the following code makes the sound play on button press but the led sequence doesn't at all. If I move root.rewind(); play(root); to after the last digitalWrite then the led sequence runs but the audio doesn't play until the led sequence ends. I'm out to make the audio play while the led sequence runs. Any suggestions?
if (state == 1) {
    root.rewind();
    play(root);
    for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
        analogWrite(LED,i);     // set the LED brightness
        delay(15);              // wait 15ms because analogWrite
                                // is instantaneous and we would
                                // not see any change
    }
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second
    analogWrite(LED, HIGH);     // turns the LED on
    delay(300);                 // waits for a second
    analogWrite(LED, LOW);      // turns the LED off
    delay(100);                 // waits for a second

    digitalWrite(RESET, LOW);
}

analogWrite(LED, HIGH); is equivalent to analogWrite(LED, 1);

@gre_gor in the code I provided its an i not a one if that's what your referring to.

As this can not be your entire sketch we can only guess that you are using some sort of SDCard music playing Arduino shield and library.
An application can not call the delay() function if the application is trying to accomplish more than one task.  Calls to delay() block the processor from doing anything other than waiting for the delay to time out.
In order to (appear to) do multiple tasks, run a loop with no calls to the delay() function.  Instead call the millis() function checking if enough time has elapsed to call the LED function or the sound function.  In neither function should you call the delay() function!  If you did not write the function (for example you are using a library) you may need to edit the code in the library to ensure it is following the no-calls-to-delay()-function rule!
In general terms, this is referred to as a state machine.  In this case, the state machine is driven by the amount of elapsed time as reported by the call to the millis() function.

Thanks, that works perfectly. Still learning the vocab with this thing, which is why I was blissfully unaware of the millis function. And yes I'm using an adafruit wave shield to play audio from an sd card. I didn't include all that code because the majority of it is one of adafruit example codes to get it working. Thanks again, cheers


text:
A question about resistance measurement with arduino
Lately I was asking myself about the possibility of measuring a potentiometer resistance with Arduino.
My questions are:

Is it possible?
If it's possible, what kind of restriction does the Arduino have with the resistance value measured?

This simple example will show you how to measure the position. It uses a potentiometer with its ends connected to +5V and 0V, and you read the analog voltage at the "wiper" connection which is the centre on most potentiomenters. (To clarify - this method does not directly measure the resistance, a different arrangement would be used for that. But most potentiometer applications really just need the position.)

@Andy You can always just add a quick equation into your code to turn the voltage back into resistance, as long as you know the value of the pot you're using

@Hayman you're correct, if the overall resistance of the pot is known. But it's not entirely clear to me if the questioner wants to use a known pot in a circuit, or is trying to measure "resistance" of something in general. That's why I was being cautious :)

If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.
Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).
R = V/I

To find one unknown value (in your case R) you need to know the other two values.  That is, the current flowing through the resistor, and the voltage dropped across the resistor.
We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.
So we need to then provide a known resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

Current flows the same through all resistances connected in series
The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.
If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.
Here's the circuit I just described:

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.
Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:
Vout = 681 / 1024.0 * 5.0
     = 3.325V

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.
So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).
Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.
That's the long-hand version from a current-based perspective. However there is a short-cut.
Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.
From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly.  So we can use a simple ratio calculation to give us the resistor.
For instance, the ratio formula:
Vout = R2 / (R1 + R2) * Vin

(that's R2 as a proportion of the total resistance multiplied by the input voltage)
When rearranged to get R2 gives us:
R2 = R1 * (1 / ((Vin / Vout) - 1))

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:
R2 = 10,000 * (1 / ((5 / 3.325) - 1))
   = 10,000 * (1 / (1.504) - 1)
   = 10,000 * (1 / 0.504)
   = 10,000 * 1.984
   = 19840

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).
You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.
Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a voltage follower with a very high (tens or hundreds of tera-ohms) impedance input.

Actually, the conversion factor is 1024, not 1023, according to the ATmega328P datasheet. Not that it makes a big difference though...

Put 5v into the ADC and you read 1023. 1023/10245 is not 5. 1023/10235 is 5.

@EdgarBonet If we're really 'nitpicking' then you could argue that the 5V isn't truly 5.0000, so you could say that using 5 is also incorrect. The way I've always known it is there are 1024 levels, as 0 is the first number that makes 1023 full scale does it not?

@Hayman You mean like I discuss on my blog?

That was an interesting read, I was trying to think how to accurately measure Vcc on board, didn't know you could do it that way. Now all my analog reads will be a bit more accurate

Put 5.01 V on the ADC and you read 1023. It's called saturation. @Hayman: I have no better alternative for the 5 V. It could be more or it could be less, but it is nominally 5 V, so I would write 5 V until I know better. But the Vcc has no influence on the resistance measurement anyway. And the conversion factor is nominally 1024: it could be 1023 like it could be 1025. The discrepancy between the real factor and 1024 is called gain error, and there is some tolerance on it. C.f. the datasheet.

Looks like the AVR's ADC uses lower-bound quantisation, so the highest value (1023) represents Vref - 1 LSB. Ergo 5V can never be measured unless you connect the VRef pin to more than 5V. For the AVR 1024 is then the correct value to use (calculations updated) though that may not be the case for other ADCs.

The question isn't explicitly clear, this answer is based on having a single known value pot and wishing to know its resistance at any one point rather than trying to find an unknown resistance entirely
You can't measure resistance directly. What you can do however is measure the voltage across a potentiometer.
There is a really good example provided by arduino which can be found here.
Now, it is possible to turn this into a resistance value with a little bit of editing to the code
int potPin = A0;    // Select the input pin for the potentiometer
int potR = 1000;    // This is your max potentiometer resistance in Ohms
int val = 0;        // Variable to store the value coming from the sensor
float voltage;      // This is the voltage from the wiper of the pot
float resistance;   // This is the resistance of the pot at the wiper

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

void loop() {
  val = analogRead(potPin);                      // Read the value from the pot wiper
  voltage = val * (5.0 / 1023.0);                // Convert the value into a voltage
  resistance = (voltage / 5.0) * potR;           // Convert the voltage into a resistance
  Serial.print("Voltage = ");
  Serial.print(voltage);                         // Print the voltage
  Serial.println("V");
  Serial.print("Resistance = ");
  Serial.print(resistance);                      // Print the resistance
  Serial.println("R");
  delay(1000);                                   // Add a little delay
}

As for your second question, it can do as high a resistance as you want. As long as you update the potR value in the code with the resistance of your pot (e.g. 1000000 for a 1MOhm pot)
I'm an electronics engineer by trade so my code could probably be cleaned up and made more efficient, this is just a starting point

Actually you can measure the resistance if and only if you have a reference resistor. Then you can measure the voltage between the reference resistor and the unknown resistor and then calculate the value of the unknown resistor.

Just nitpicking: the scale factor is 1024, not 1023.


text:
The exact time for functions or CPU cycles for any function
I'm trying to read input data from the parallel port of a PC and send it to another device. For this purpose the input data is saved, when it's available and is sent if a flag is set.
The whole procedure should be done in less than 10 ms. I need to know the running time. How can I compute the CPU cycles for ReadParallel and WriteParallel functions (digitalRead, digitalWrite, bitRead,bitWrite) in my code or any other instructions?
Here is the code for the Arduino Uno:
#define InterruptInputPin 2 // For checking if the input data is available
#define InterruptSensorPin 3 // For checking when to send data

#define IN0 A0
#define IN1 A1
#define IN2 A2
#define IN3 A3

#define OUT0 5
#define OUT1 6
#define OUT2 7
#define OUT3 8

volatile int ParallelInput; // The input data

//*************************************
void ReadParallel() //Reads input and saves it in parallelInput.
{
  if (digitalRead(IN0) == HIGH)
    bitWrite(ParallelInput,0,1);
    else
      bitWrite(ParallelInput,0,0);

  if (digitalRead(IN1) == HIGH)
    bitWrite(ParallelInput,1,1);
    else
      bitWrite(ParallelInput,1,0);

  if (digitalRead(IN2) == HIGH)
    bitWrite(ParallelInput,2,1);
    else
      bitWrite(ParallelInput,2,0);

  if (digitalRead(IN3) == HIGH)
    bitWrite(ParallelInput,3,1);
    else
      bitWrite(ParallelInput,3,0);

}
//***************************************

void WriteParallel() //Writes ParallelInput to output.
{
  detachInterrupt(digitalPinToInterrupt(InterruptInputPin));
  digitalWrite(OUT0,bitRead(ParallelInput,0));
  digitalWrite(OUT1,bitRead(ParallelInput,1));
  digitalWrite(OUT2,bitRead(ParallelInput,2));
  digitalWrite(OUT3,bitRead(ParallelInput,3));
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

}

void setup() {

  pinMode(IN0,INPUT);
  pinMode(IN1,INPUT);
  pinMode(IN2,INPUT);
  pinMode(IN3,INPUT);

  pinMode(OUT0,OUTPUT);
  pinMode(OUT1,OUTPUT);
  pinMode(OUT2,OUTPUT);
  pinMode(OUT3,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

attachInterrupt(digitalPinToInterrupt(InterruptSensorPin),WriteParallel,RISING);

}

void loop() {

}

Note that, in this particular instance, you can get much faster I/O (like 100 × faster or so) by using direct port access. For example: void ReadParallel() { ParallelInput = PORTC & 0x0f; } should compile to not much more than 6 instructions. Or even 4 if you declare ParallelInput as a byte rather than an int.

Method summary
(section added on 2018-01-28)
There are several methods available for timing code. I am adding this
preliminary section to my answer in order to provide comparative data on
several methods. The methods covered in the table below are those
proposed as answers to both this question and a duplicate question of
this. As this question has been tagged “arduino-uno”, all
this data assumes an AVR-based board clocked at 16 MHz.
Method comparison:
| method         | resolution    | max. time       | typ. overhead  |
|----------------|---------------|-----------------|----------------|
| `millis()`     | 1 – 2 ms      | 49.7 days       | 0.69 – 1.3 µs  |
| `micros()`     | 4 µs          | 71.6 min        | 2.8 – 2.9 µs   |
| Timer 1        | 0.0625 µs     | 4.096 ms        | 0.25 – 0.5 µs  |
| pin toggling   | scope-limited | ∞               | 0.125 µs       |
| cycle counting | 0.0625 µs     | boredom-limited | 0              |
| looping        | N.A.          | N.A.            | 0.25 µs        |

The methods are characterized by the following criteria:

Resolution is the granularity of the measurement, the smaller the
better.
Maximum measurable time: any method that does timing arithmetics
on the Arduino is prone to overflows if measuring too long times. Note
that a timer rolling over to zero during the measurement is not a
problem, as long as the period being measured is less than
the rollover period.
Typical measurement overhead: the code used to measure the timings
takes itself a finite time to execute, thus one ends up measuring the
execution time of the “instrumented” code, which is slightly larger
than the time taken by the code one is trying to profile. This
overhead should in principle be subtracted from the result, but it is
often not known exactly, as it depends on how the compiler optimizes
both the instrumented and the non-instrumented code.

The methods listed in the table are:

millis(), which may be the most obvious choice, as it is so well
known. Its low resolution, however, makes it ill-suited for timing
code execution. It should be noted that the millis() counter is
incremented every 1024 µs. Most of the time it is incremented by
1 but, every 43 ms (roughly) it is incremented by 2 in order to
avoid creeping drift. This is why its resolution is stated as
“1 – 2 ms” in the table.
micros(), as proposed in ratchet freak's answer, is usually
a good choice, the main caveat being the 4 µs resolution, when
one could naively expect 1 µs. It also has a significant
overhead.
Timer 1, which is discussed in the second part of this answer, is
my favorite: it has single cycle resolution and low overhead. However,
it is incompatible with other uses of the timer (PWM, Servo
library...). It is also limited to measuring small delays.
Pin toggling, as proposed by 4ilo, and by myself in the third
part of this answer, is ideal if you have an oscilloscope handy. Any
half-decent scope should provide single-cycle resolution. It is also
minimally invasive on the code being measured and has minimal
overhead.
Cycle counting, as proposed in Majenko's answer, is arguably
the “perfect” method: it is cycle-accurate, does not modify the code
and has zero overhead. However, for anything beyond a handful
instructions, it quickly becomes tedious. And it requires some
understanding of the AVR assembly.
Looping, as proposed in Michel Keijzers' answer, is not a
measurement technique per se. It is meant to be used in conjunction
with another technique in order to improve the resolution and dilute
the overhead. However, lopping carries it's own overhead, which is
typically 4 CPU cycles per iteration, assuming a 16-bit loop
counter.

Using Timer 1
(original answer of 2017-10-23)
One technique I often use is to make Timer 1 count at the full CPU speed
and use it to time the code I want to profile. For example:
volatile uint8_t pin = 2;
volatile uint8_t value = HIGH;

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

    // Set Timer 1 to normal mode at F_CPU.
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    cli();
    uint16_t start = TCNT1;
    digitalWrite(pin, value);
    uint16_t finish = TCNT1;
    sei();
    uint16_t overhead = 8;
    uint16_t cycles = finish - start - overhead;
    Serial.print("digitalWrite() took ");
    Serial.print(cycles);
    Serial.println(" CPU cycles.");
}

void loop(){}

Note the volatile variables used to prevent the compiler from
optimizing them as constants.
Note also that when you profile some code you are inevitably slowing it
down, because of the time taken by the profiling operations themselves.
This is what the overhead variable above accounts for. In order to
know the exact overhead, I start with a guess, compile and disassemble,
and then count the number of clock cycles spent in profiling that will
be counted by the timer. Then I adjust the overhead value, compile and
disassemble again, and make sure the overhead has not changed. This is
also when you have to ask yourself what exactly you want to count. Here
I am counting the time needed to execute call digitalWrite, but not
the time needed to get the arguments in the proper registers, as I am
artificially slowing this down by making them volatile.
This method is good for anything that takes more than roughly a dozen,
and less that 65,536 clock cycles. Less than that, clock counting would
be simpler, since you still have to clock-count the overhead. More than
that, the count would overflow, and you could instead just use
micros(), and live with its inherent inaccuracy.

Toggling a pin
(section added on 2017-10-23)
If you have a scope, there is another method that is minimally
invasive on your code: toggle a pin just before and just after the thing
you want to time. E.g., assuming you have previously
pinMode(13, OUTPUT):
// Set pin 13 HIGH.
PORTB |= _BV(PB5);

// The thing we want to time.
...

// Set pin 13 LOW.
PORTB &= ~_BV(PB5);

This will create a pulse that you can measure on the scope. Note that
using direct port access, like here, the overhead is only two CPU cycles,
or 125 ns. Also, direct port access won't use any CPU register, so
chances are the compiler will not generate less efficient code than when
not including the timing part.

And without a 'scope, I/O pin timing can be done with some DMMs. If it can measure pulse frequency and duty-cycle, you can calculate the interval (puse-width). Tekpower TP4000ZC is one such DMM and an inexpensive one, at that.

Thanks for answer. I haven't worked with registers and direct port access,  can you send me a document or link for more details?

@Mehran: The link I already sent you about direct port manipulation is a good introduction. You may then want to take a look at the description of the avr-libc macros commonly used for that task (mostly _BV() which is the avr-libc's equivalent of Arduino's bit()). Then, the ultimate reference is the microcontroller's datasheet.

There's two methods:

Profiling.
Clock counting.

The first method involves recording timestamps at different points in your program and calculating the time difference between them. That's the simplest, but not always the most accurate.
The second method is far harder and involves disassembling the program after you have compiled it (or obtaining the assembly language from part way through the compilation sequence) and examining all the assembly instructions, looking them up in the instruction list, and totalling how many clock cycles are used for each instruction. That gets very complex, especially when you have loops. However it will tell you precisely how many clock cycles, and thus how long, a block of code will take to execute (not including interrupts, which always throw a big spanned in the works).

To efficiently measure the time a block of code takes, run it for like 1,000 or 1,000,000 times and divide the time by the amount of iterations.
In some cases initialization/variables can be cached but in principle the times are quite accurate. You can easily check this by doing the test for e.g. 1,000 and 2,000 times and see that the time difference also is a factor 2.
For the time counter, use an unsigned long type to accommodate more than 65,535 (ms/us whatever the unit is used).

Keep in mind that managing the loop carries some overhead, typically about 4 CPU cycles per iteration for a 16-bit loop counter. You will have to subtract this from your result if you want sub-µs accuracy.


text:
CAN communication with Arduino
I'm a member of a Formula SAE team and we use the Performance Electronics ECU which uses the CAN protocol with a speed of 250 kbit/s and works fine with our 2D Recording Systems Data logger, but we're trying to build a telemetry system which gathers the same data from the CAN bus using an Arduino Uno and CAN shield provided by SparkFun Electronics.
However the CAN shield we're trying to use has failed to initialise the communication with the bus. Kindly help me out on what can be done or are there any alternatives of communicating using CAN with Arduino?
P.S. The link for the CAN shield: CAN-Bus Shield Hookup Guide

Have you shecked the shield pins match the ECU connector pins? The shield is configured to match the pins on their OBDII->DB9 cable and may not match the "vanilla" CAN pinout. This will require desoldering jumpers

You may also try to add termination to the BUS

Hi Crasic, according to the schematic of the shield already has termination resistance to the bus, and regarding the connections, yes the ECU Connector pins match with the shield pins. Our data logger works fine but the shield isn't working. Also could you provide me with the info on ODBII-> DB9 cable and the "Vanilla" CAN Pinout. Thanks

I also forgot to tell that the communication protocol is SAEJ1939 and the Baud rate is 250KBPS

Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

pin 3/5 CAN bus shield schematic
pin 2/7 (Vector tools for example).

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?

I found this wiki particularly useful: CAN-Bus Shield Wiki
And yes, like CQuinson said, you have to pay attention to the pins used. I know Sparkfun is known for having an issue with which pin the CS pin is assigned to (D9 or D10).


text:
Code to control servo with shield
I recently bought an Arduino MEGA2560 and a SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control.
I understand how to control a servo in the method described in Sweep. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?
Please help me I am a beginner in robotics and I need this for a project.

Add more info about this shield.

I got the shield at this link: http://www.sainsmart.com/sainsmart-instabots-robot-controller-shield-for-arduino-mega2560-r3-robot-arm-control.html?gclid=CKDOq-7Mh8sCFVZbhgodfeUBWQ

However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

With the limited amount of info you have provided about the shield this will have to be a wild guess. I am assuming that the pins are S(ignal), V(cc) and G(nd) for pins 8-13. On an Arduino Mega these can be used for PWM and therefore Servo control.
Include the Servo library, attach the pin and set the angle.
#include <Servo.h>

Servo servo[6];

void setup()
{
  ...
  for (int i = 0; i < 6; i++)
    servo[i].attach(8 + i);
  ...
}

void loop()
{
   ...
   servo[i].write(pos);
   ...
}

Cheers!
NB: Do not forget to provide the correct power supply. If USB Port is left, then the upper pin is positive and the lower pin negative.

Wouldn't the servo.attach() number refer to the pin area near the green light?

@samuelli97 - Yes, you could use the output pins (near the green light), but for ease of use, the servos are (usually) connected to controller shields via a three pin plug, which plugs straight into the 6 sets of SVG pins, on your board. You will first need to solder 6 sets of 3 pin headers (which should have come with the board) to the PCB holes, that you have outlined in red, in order to be able to plug the servos in. As Mikael also states, you will also need to attach an external power supply to the green terminals as the Arduino can not supply enough power to the servos by itself.

Sainsmart STILL refuses to supply documentation for this board.Supposedly, it can control 6 servos and two motors, up to 4 Amps, with digital encoder inputs. There is NO documentation on the hardware or the software for the mega to drive this.

The SVG connectors on your board appear to be lacking header pins:

These should have been supplied with the board. If not you will need to source some. Either way, you will need to solder them on. I don't understand why they are not already attached.
If you look at the other images of the board on the SainSmart web page, the header pins are clearly visible:

The S pin of each SVG is the same as the output pins, near the green light, but for ease of use, they are replicated in the SVG pins, so that a servo plug can be easily, and conveniently plugged in, with out the user having to wire up power and ground separately.  If you look at the plug attached to the end of the cable coming from your servo, you will see the servo connector, like so:

As the board has arranged the pins in the SVG order, that means that it will support the Futaba J type connectors (but not the Airtronics, as the power and ground pins are reversed):

Also, Hitec and JR Radio connectors are supported by your board, as they have the same pin out:
.
For more information, take a look at Choosing RC Servos.
In addition, as Mikael says, you will also need to attach an external power supply to the green terminals

as the on board power regulator of the Arduino can not supply enough power to the servos, via the shield, by itself, neither with the USB, nor an external wall wart PSU, supplying power to the Arduino. So, use a bench power supply, battery pack, or otherwise and supply that power directly to the board via the Green power terminals at the end of the board.
Once you have done all of that, and got the hardware out of the way, then the software provided in Mikael's answer will work perfectly.

I have the header pins I can solder them without a problem. Do I need to connect my battery to the shield, or can I attach it to the Arduino?

Sorry you said that it has to be directly to the shield. Thank you so much!


text:
DC Motor Speed Measurement using Rotary Encoder
I have written the following code to measure the speed of a unidirectional DC Motor.I have attempted to measure the time between successive interrupts in order to calculate speed.
boolean check;
boolean start;
unsigned int angle = 5;   //angle moved per encoder tick
unsigned long volatile time1;
unsigned long volatile time_11;
unsigned long interrupt_time;

void setup() {
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(21, INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
  attachInterrupt(digitalPinToInterrupt(2), speed, FALLING);
  time1 = 0;
  time_11 = 0;
  interrupt_time = 0;
  check = true;
  start = false;
  time_11 = millis(); //Start Clock
}

void loop() {
  if(time1 == interrupt_time && start) //Both times same , hence bool start.
  {
    if(check)
    {
      Serial.print(millis());  //Time taken to rise to steady speed.
      check = false;
    }
    Serial.println((angle/time1)*1000);   //Display Speed.
  }
  interrupt_time = time1;
  start = false;
  while(!start)
    {}
}

void speed(void) {
  start = true;
  time1 = millis()-time_11;
  time_11 = millis();
}

I want the code to be as efficient as possible.I have around 100 ticks per 360 degrees from my encoder.Is there any chance of "missing" an interrupt?

I think you'd be better of calculating the speed based on the number of pulses during a certain amount of time, instead of the time of a single pulse. Secondly, you have to use atomic operations on multi-byte variables that are changed by the interrupt-routine. As e.g. during the comparing of time1 in the loop the ISR might be called and the value of time1 would change. The if statement might have compared the first two bytes of the long, but then checks the last two bytes of the new value. I hope this makes sense.

millis() probably won't work for this, unless your motor is slow and your encoder low resolution there would typically be less than a millisecond between encoder events.  If you really want to time individual events, learn to use the hardware timer and wire the inputs accordingly.  Otherwise counting events per period of time is better.  Depending on wiring and details you may be able to count events with the hardware timer's counter mode.

The HW timer counter mode doesn't scale well, though. Taking a time stamp of the even and calculating the delta from the previous allows to use even the PCINT pins.

Serial.println((angle/time1)*1000);   Be careful to not divide by 0.  Also be aware that this is integer division and thus it will truncate (before multiplying by 1000).

How fast do you expect the motor to run?  And how fast do you want to report on the speed?

Just a couple of remarks:

start should be volatile, but you can remove it and simply check
that time1 != 0.
there is no point in calling millis() twice inside the interrupt
service routine:

void speed(void) {
  unsigned long now = millis();
  time1 = now - time_11;
  time_11 = now;
}

Thank you for the feedback!
This is my attempt at calculating speed using the averaging method.
unsigned long volatile encodercount;
unsigned long encodercount_previous;
unsigned long volatile timer;
unsigned int angle;
boolean first;
boolean firstencodertick;
void setup() {
      angle=3;
      encodercount=0;
      encodercount_previous=0;
      Serial.begin(9600);
      while (!Serial);
      pinMode(21,INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
      attachInterrupt(digitalPinToInterrupt(2),speed,FALLING);
      first=true;
      firstecnodertick=true;
        }

  void loop() {
     delay(100);

   if(encodercount==encodercount_previous&&encodercount!=0)
    {
   if(first)
     {
   Serial.println(millis()-timer);  //Steady State Time Taken
   first=false;
     }
  Serial.println((encodercount); //Angle Moved in 0.1second.
    }
  encodercount_previous=encodercount;
  encodercount=0;
   }

  void speed(void)
 {
 if(firstencodertick)
 {
 timer=millis();
 firstencodertick=false;
  }
 encodercount++;
}

authors: Альмир Мугутдинов


text:
calling a random function number
I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.
ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc
and would like to called them randomly in that fashion :
randNumber = random(1,11);
anim[randNumber]();

I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that..
I'm sure there must be a way ;)
thanks for your help

What you want is an array of function pointers.
void anim1() {
    // blah blah
}

void anim2() {
    // blah blah
}
// ... etc ...

typedef void (*animptr)();

animptr anims[10] = {
    anim1,
    anim2,
    anim3,
    // ... etc ...
    anim10
};

Then you can use:
anims[animNumber]();

You mean typedef void (*animptr)();.

I didn't know this was possible. But I think I would feel dirty when using it. It just seems wrong to do this.

Why so? Function pointers are one of the most powerful facilities of C. Imagine trying to implement callbacks without being able to use function pointers - and an array of them is just an extension of that. A function is, after all, just a location in memory...

thanks so much Majenko! exactly what i was looking for! :D

I end up using another way and just wanted to share it here for anybody that would want a bit less efficient but simpler way of doing that  ;) it's cleaner with Majenko's solution for sure but this gets the job done and is pretty easy to understand and troubleshoot. cheers!
int randNumber;

void loop(){
randNumber = random(1,14);

if (button is pressed or something){
callAnim(randNumber);
}
}

void callAnim(int randNumber){
if (randNumber==1){
anim1();
}
if (randNumber==2){
anim2();
}
}
// ... etc ...

void anim1() {
// blah blah
}

void anim2() {
// blah blah
}
// ... etc ...


text:
Arduino libraries development and Eclipse Soleber
I have a project on Arduino IDE. A .ino sketch with some extra .h/.cpp files and 2-3 libraries that I keep in ~/Arduino/libraries.
In addition to the IDE I do open the libraries as generic project in eclipse, of course this means no symbols resolution and no indexing which is bad for me.
So I wanted to give Solebera try. I can see that Soleber includes the directory above however when compiling, I can clearly see it doesn't include any of those libraries! Also trying to add them doesn't work as the preference screen doesn't allow it/lists it.
So you help please,

how can i make it even compile?
will eclipse index it? I mean if I press 'ctrl + shift + r' and start typing RH_RF95 (radiohead rf95 driver cpp file) will it let me open it? (it does for Platformio).

in Eclipse Arduino Preferences you can set if it adds the libraries automatically. If you choose not auto, then use "Add a library to selected project" in Arduino menu. 2) yes

I edit and debug libraries in a test project for the library. So the developed library is one of the libraries used by the project.

nop didn't work for me, "automatic is set for me but adding RHGeenricDriver.h doesn't cause the library to be added. adding "libraries" to the project adds ALL the libraries , i can see them in the makefile but they are excluded including radiohead which has an include in the main file. so it doesn't work. seems like it's not the way to go after all.

do you have the libraries folder configured in Preferences?

Yes i do.  Its configured correctly,  i checked.

try with a new project

It is a new project,  i ipened it just for the tseting...

Let us continue this discussion in chat.


text:
Communication between 2 Bluetooth modules
I successfully connected two Bluetooth modules, HC-05 and HC-06 like on this website:
http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/
I have an Arduino Nano that's the slave (HC-06) and an Arduino Mega that is the master (HC - 05) and there's is the code for both of them:
Reveiver - Master
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX | TX
String Data = "";
void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
}

void loop(){
    while (mySerial.available()){
        Serial.println(mySerial.read())
    }
}

Sender - Slave
#include <SoftwareSerial.h>
SoftwareSerial BTserial(11, 10); // RX | TX

int c = 100;

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

void loop(){
     BTserial.println(c);
}

I tried
BTserial.write(c)

and doesn't work either, I receive numbers like 245,255. And when I change the data that I'm sending the numbers are different, so I know that they are communicating, I think it's a variable problem, but I tried a bunch of codes of the internet that supposedly work, but it doesn't seem to work for this case.

use write() to write a byte to Bluetooth and to Serial Monitor

A Mega has 4 hardware serial interfaces. Why are you using software serial?

look at the bytes sent     int send=BTserial.write(c);    c is not a single byte, and I am not sure how it reacts to 4 byte int.   you could also change it to BTserial.write(100); and see if that changes anything

println prints the int variable c as string "100" with /r/n at the end. And you read it as bytes with read and print the bytes as numbers with new line at the end. So you get ascii values of 1, 0, 0, \r and \n.
use write() to write a byte to Bluetooth and to Serial Monitor

How could I solve the problem? If i use the write function do I have the same problem?

When forwarding serial traffic through the Arduino you have to use only the read() and write() functions, not the print() functions.


text:
Powering Arduino and L293D with the same Power Supply
I am relatively new to Arduino and plan to power an Arduino and an L293D Motor Driver with the same 9V power supply as in the diagram below.
I tried to simulate this with Tinkercad, but it seems like Tinkercad always powers the Arduino with an extra USB Cable, so I can't test it with only 1 power supply.
Would the 9V battery power both the Arduino and the L293D in this example?

Don't use one of the little rectangular 9V "transistor batteries". Those don't provide enough current to power a motor for very long at all (probably single-digit minutes) before they are discharged.

I don't see any problem. You used the Vin for 9V, and shared grounds.
I suggest using a bypass capacitor (typically 0.1 uF) for the L293D VCC, but I don't have experience with using a L293D.
Also, you need to check if the battery can deliver enough current for both motors and the Arduino.


text:
Arduino waits until button release to activate
I'm fairly new to arduino, and on my own I'm trying to move a servo to the left and right using 2 buttons.  I've got it working for the most part, however when I hold the button down nothing happens, and when I finally release the servo moves a certain amount based on how long I was holding the button down.  I would like the servo to move when the button is being held down though.  The servo also occasionally moves oddly and sporadically.  I'm thinking its most likely a logic error in the code, but I can't figure it out.  Could someone please tell me what they think I've done wrong?  Thank you.
code:
#include <Servo.h>
Servo servo;

#define right 9
#define left 8

int angle = 90;
int angStep = 5;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(right, INPUT_PULLUP);
  pinMode(left, INPUT_PULLUP);
  servo.attach(2);
  servo.write(angle);
  Serial.print("Begin");
  Serial.print('\n');
  Serial.print(angle);
  Serial.print(angle);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(left) == HIGH && angle < 180){
    angle += angStep;
    Serial.print(angle);
    Serial.print('\n');
    servo.write(angle);
    delay(50);
  }

  if (digitalRead(right) == HIGH && angle > 0){
    angle -= angStep;
    Serial.print(angle);
    Serial.print('\n');
    servo.write(angle);
    delay(50);
  }
}

check for the opposite signal level at the button pin

Connect the 'output' signals (that goes in the Arduino pin 8/9) instead to a resistor and a LED to see if it behaves like you expect. This rules out if there is a software or hardware problem.

I think it's because you are using a pullup resistor, so it's constantly HIGH instead of constantly LOW. Try changing HIGH and LOW to the opposite.

I tried swapping the HIGH and LOW and nothing happened, so I just switched back to high and changed input_pullup to just input.  Now the servo moves but just completely randomly and i don't know why it's so inconsistent.


text:
Arduino bluetooth HC-05 servo control
I am using HC-05 Bluetooth module to control two servos. I use Bluetooth terminal in my android phone to control them.
Problem is that myServo1 is moving like I want but I can't control myServo2. Code is reading the variable a but it can't read variable b.
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myServo1;
Servo myServo2;
int servo;
SoftwareSerial BT(2, 3);
void setup()
{
myServo1.attach(11);
myServo2.attach(10);
servo = 90;

Serial.begin(9600);
BT.begin(9600);
}
char a;
char b;
void loop()
{
 if (BT.available())
{
a=(BT.read());
b = (BT.read());
if (a=='1')
{
  myServo1.write(180);
  delay(50);

}
if (a=='2')
{
  myServo1.write(-180);
  delay(50);

 }
  if (b=='3')
{
  myServo2.write(90);
  delay(50);

}
  if (b=='4')
{
  myServo2.write(-90);
  delay(50);

}
}
}

Where is the problem?

your sketch has no debugging code .... why are you not printing the values of a and b to the serial monitor?

When using
if(BT.available())

that's doing the same as
if(BT.available() > 0)

But then you are reading 2 bytes, though you cannot be sure, that there are 2 bytes to read. The data is transmitted serially, so even when you send it on your phone in one bunch, it does not get transmitted as bunch.
Try to use
if(BT.available() >= 2)

Also makes sure, that nothing else gets send over serial besides the numbers (often there is a line ending send implicitly depending on the used app).

If I use the " if(BT.available() >= 2) " it will mix the whole system

What do you mean by that? @engineerstudent

It does not work properly. If I put "1", "2", "3" or "4" it turns one servo randomly. In some cases it doesn't work at all

Then you also have another problem. Have you confirmed, that the comminication with the HC-05 works correctly? You can do this by using a testsketch, where you forward the received data from bluetooth to the serial monitor. If everything is transmitted correctly, we can rule out that part

I don't think that there is problem in the connection because if I use "BT.available()>0" and I type "1" or "2" then it work properly and turns the myServo1 between 180 and -180.

My proposed solution should not result in the observed errating behavior. It just waits for 2 bytes to be actually available, before you read them. Thus I think, that there is something else wrong. Do you really don't send any line ending? That would explain the behavior

When it send the value then I press enter. Would that cause the error? If so how I fix that.

Let us continue this discussion in chat.


text:
Remove blocking delay() toneMelody function?
I would like to change the delay() into a nonblocking function in the code below. I've implemented it (a part of a tutorial from arduino.cc) in my code, but the delay() is blocking the rest of my code. Can anyone help me to change this?
void speelMelodie(int melodie){

if(melodie == 1){

      for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      tone(speaker, melody1[thisNote], noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes); // <-- this one has to be changed

      noTone(speaker);
      }
  }

else if (melodie == 2) {
      // the same part as previous part (for loop)
  }

else if (melodie == 3) {
      // the same part as previous part (for loop)
  }
}

Look at the Arduino example program, BlinkWithoutDelay (File | Examples | Digital | BlinkWithoutDelay). It uses millis() to time the length of the 'on' and 'off' periods of the LED - just what you want to do with the tone.

Have you looked into examples and tutorials about millis()? Did you understand them? What exactly prevents you from changing your code to millis()?

Yes I have, but I don't know how to implement this in my code. I've 5 different melodies like above fragments.

What are you trying to achieve? From your code, it looks like you play a tone and then you pause for some milliseconds (i.e. silence) and then play the next tone. If that is the case, how millis() will help or what delay is blocking?

@Fahad , I have a lot of other code, I call this function. but due to the delay in this function I can't do with the rest of my inputs outside of this function.

Define  global vars befor setup()
unsigned long timeStamp = 0;
bool pauseOn = false;

and use it
void speelMelodie(int melodie) {

  if (melodie == 1) {

    for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      if (millis() - timeStamp < noteDuration && pauseOn == false) {
         tone(speaker, melody1[thisNote], noteDuration);
      } else { // reset value and change pauseOn to true
        pauseOn = true;
        timeStamp = millis();
      }
      int pauseBetweenNotes = noteDuration * 1.30;

      //delay(pauseBetweenNotes); // <-- this one has to be changed
      if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
          noTone(speaker);
      } else {
         pauseOn = false;
         timeStamp = millis();
      }
    }
  }
}

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.A final tip Tutorials using delay() other than

for debuging or
in setup for initializing hardware

are of very low quality
-> Its like a blind person talking about color composition.

Thanks for this, but I get only two notes now.

Post your code completely by editing your question -its hard to find errors in fragments perhaps unrelated to the real problem

This is a part of a function that I call elsewhere, so it should be in this part. The whole code is very big.

Then you have to find it on your own. Now the function is non blocking and as we do not know the rest code it can be caused anywhere (check for other delay() and get rid of them) aso at least give the complete function if you want any further help (and the libs needed - just the include part and the global vars used in the function)

Allright. I will try it by myself first. Otherwise, when i'm stucking, I'll ask you for help.

There was still a delay () in it, so that was indeed a mistake. the rest of the function is a repeat of the given part.
I have edited my code above.

Now I have a constant stop start tone

You have to apply my changes in the same wy to all three parts first. Then ensure that your loop is not constantly calling the speelMelodie with new params. You can do this with a second bool changeMelodie = true/false; so the loop still goes into the function without everytime changing the params. Copy this part of the caller(loop) with some lines before and after and a rough structure what else is happening in the loop

Could you give me an example maybe? It isn't still totally clear for me.

Let us continue this discussion in chat.