text:
Ask for available ip on ethernet shield
Is there any way so an ethernet shield to ask the router for an available ip address? For example to ask for an ip an the router to return 192.168.1.2 if it is available. I am asking it because if we set the ip programmatically and it is attached to another device we gonna have problem.

Using the DHCP (Dynamic Host Configuration Protocol) you can obtain an IP address dynamically from a DHCP server (which a router usually also is), without having to hardcode it into the firmware of the Arduino, thus enabling it to work on different networks.
There is also a library for that: http://www.arduino.cc/en/Tutorial/DhcpAddressPrinter. It's an extension of the official Arduino Ethernet library, written for the Arduino Ethernet Shield, but you'll likely find implementations of DHCP in many Ethernet libraries (I am using the EtherCard library) because it's an important feature to be able to connect to a network without a statically assigned IP and "only" requires UDP (on top of IP).
For e.g. the Ethernet library you call the begin function either with only the MAC address of your device or with MAC and IP address:
Ethernet.begin(mac);
Ethernet.begin(mac, ip);

In the first case it will use DHCP to obtain an IP address dynamically, in the second case it will use the static IP address you provide. Be warned that the second case, due to the needed implementation of DHCP, will increase the size of the compiled binary significantly.


text:
Cannot receive and transmit at the same time
I have 2 arduinos I made some code and I managed to send from the first to the second and from the second to the first with two different pairs of code. What I want to do is to send from the first to the second and from the second to the first with no code change. I added in my current code some monitoring commands but what I can see in my Serial monitor is that not all characters are passed thru. I attach something like my code below only more simplified because it is a big project.
1st arduino:
radio.stopListening();
  for(int i=0; i<lnth; i++){
      chartosend=data.charAt(i);
      radio.write( &chartosend, sizeof(chartosend) );
  }
  radio.write(&endchar,1);
radio.startListening();
  if(radio.available()){
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    //Serial.println(inchar);
  }

2nd Arduino:
radio.startListening();
  if(radio.available()){
    radio.read( &data, sizeof(data) );
    inradio+=data;
  }
radio.stopListening();
  if(analogRead(0)>20){
     for(int i=0; i<6; i++){
      chartosend=pir1.charAt(i);
      radio.write( &chartosend, sizeof(chartosend) );
    }
    radio.write( &endchar, sizeof(endchar) );
  }

Where is the problem and how I could solve this?

Why do you only send one character at a time? (You can send 32 bytes per package, if I remember correctly.) This will create problems, because you are sending lnth packets per loop, but only read one packet per loop. So the buffer will never become empty. You might like to try while( radio.available() ){ instead of the if statement, to partially fix it.

Big part of the code is missing. What if the radios are misconfigured?  Also what if this is a hardware problem (missing cap to smooth the voltage on the nrf24l01+)?

I dunno know about the radio interface you are using. But I can see something which will break your code for sure.
The sections, where you read data from the interface on both Arduinos are passed without a delay, interrupt, polling loop or something else.
Which means: your "read" code section is in no way synchronised with the write code section on the other arduino and vice versa. At the point when you call the function "radio.available()" (which probably tests if there's any data available at the receiver fifo) there is possibly one or any number of bytes available, but not necessary the whole transmission from the other arduino. You have to make sure — somehow — that the transmission is finished, before you can call it a day and go on with processing the received data.
To do this you have to

synchronise the beginning and the end of your transmissions on both Arduinos
poll the data on the respective receiver side, until you are satisfied
or run into a timeout you have to apply in case there's a byte or more lost by chance.

I hope this gives you a little bit of orientation where to start.

source: Stack Exchange

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

sort: votes


text:
Arduino resets when I call network.begin()
I have included the RF24Network library in my project. I tried to use the Simple Transmit/Receive example from here but when it calls the network.begin() my arduino restarts. I placed some Serial.println() in order to understand where is the problem. This problem appears only in my Arduino Mega 1280. I tried the same code on my Arduino Pro mini and it works like a charm. What causes this? How to fix that? It is very important to use the specific library. Thanks in advance.

tmrh20.github.io/RF24 is the new and updated library that should fix the problem.

The problem was that the RF24Network library is not compatible with the version of Arduino IDE I have. I downloaded Arduino IDE v1.0 and now it works like a charm. I will send an email to maniacbug to tell him about the problem.

tmrh20.github.io/RF24 is the updated fork.

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


text:
Micro not detected, can't reset
I just picked up a new Arduino Micro for a project, but the first time I tried to upload to it, things went terribly wrong. The USB cable was loose, so the power light kept blinking on and off. When I did get it stable, I accidentally had 'Uno' selected under 'Tools->Board'. I think this was the source of the problem.
I'm aware that the solution for these kinds of problems is to try to upload some simple code while in bootloader mode, but pressing reset shortly after pressing the Upload button. But this board doesn't even respond when I press reset. I have tried it with both the on-board button and with an externally button linking RS to ground.
Furthermore, the board doesn't show up in my Device Manager, not even as an "Unknown Device". The device managed doesn't even refresh when I plug it in.
I know the connection is okay because the power light is on. And I know it's not a driver issue or an issue with the port, because I have no trouble getting a different Micro recognized.
The only thing I haven't tried is burning the bootloader through ICSP, since I don't have the right cable. Is there anything else I can try, or is this just bricked?
Thanks, everyone

That appears to be based on a 32u4, so if it isn't physically damaged you may be able to recover it using DFU mode - at least it's worth doing some research on the subject.

This certainly seems plausible, but it looks liek getting into DFU mode requires resetting the board via the ICSP headers. I have tried that, and just like when I reset with the pushbutton or by connecting the RS pin to ground, the board doesn't respond in any way. Or do you think I'll regain the ability to reset later on in the process?

You can use another arduino as ICSP programmer.

This is probably way to late, but with newer editions of the Micro you have to "double-press" the reset (input).
I have had some experiences today where playing with low-power modes that shuts down the usb interface, and the only way I got it back was activating the reset input twice fast, and then uploading a new scetch (this time with a 10sec delay before any usb-chaning stuff takes place!)
Richard


text:
Why doesn't this code work?
I'm having trouble programming an Arduino Uno with this sketch, the sketch compiles and I get full serial output and an IP address, but no web browser can connect to it.
I've tried this Arduino example (https://www.arduino.cc/en/Tutorial/WebServer) and it works right out of the box, I don't understand why my code therefore doesn't work.
My code is below:
#include <SPI.h>
#include <Ethernet.h>

// Bootup millisecond counter
const unsigned long started     = millis();

// Serial settings
const int SERIAL_BAUDRATE       = 9600;

// Non-DHCP ethernet settings:
// Device MAC address: DE:AD:BE:EF:FE:ED
const byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(
  192, 168, 1, 177
);

// Pins
const int P_RELAY               = 7;
const int P_ON_LED              = 8;
const int P_OFF_LED             = 9;
const int P_SW_MAN              = 10;

// Relay power states
const char B_RELAY_ON           = HIGH;
const char B_RELAY_OFF          = LOW;

// Relay switching state
boolean RELAY_STATE             = false;

// Network/web data
EthernetServer server(80);
String readString;
String localIp;

// Testing switches
const boolean connectToEthernet = true;
const boolean hostWebServer     = true;
const boolean useDHCP           = false;
const boolean testRelay         = false;

// Testing settings
const int testRelayDelay        = 500;

// Formats an IPAddress nicely as a string for printing
String displayAddress(IPAddress address) {
  return String(address[0]) + "." +
         String(address[1]) + "." +
         String(address[2]) + "." +
         String(address[3]);
}

void setup() {
  const unsigned long started = millis();
  delay(50); // allow some time (50 ms) after powerup and sketch start, for the Wiznet W5100 Reset IC to release and come out of reset.
  Serial.begin(SERIAL_BAUDRATE);
  Serial.println("HTTP Web Remote Power-Point Controller.");
  Serial.println();
  if (connectToEthernet) {
    Serial.println("Connecting to Ethernet...");
    if (useDHCP) {
      Ethernet.begin(mac);
      Serial.println("Obtaining IP address...");
      localIp = displayAddress(Ethernet.localIP());
    } else {
      Ethernet.begin(mac, ip);
      localIp = displayAddress(ip);
    }
    if (localIp != "0.0.0.0") {
      Serial.println("Connected. IP: " + localIp);
      if (hostWebServer) {
        Serial.println("Starting Ethernet server...");
        server.begin();
        Serial.println("Started.");
      }
    } else {
      Serial.println("Error: No address provided via DHCP.");
      Serial.println("Please check your network connection and settings, and try again.");
      while (1);
    }
  }
  Serial.println("Configuring pins...");
  pinMode(P_RELAY, OUTPUT);
  pinMode(P_ON_LED, OUTPUT);
  pinMode(P_OFF_LED, OUTPUT);
  pinMode(P_SW_MAN, INPUT_PULLUP);
  Serial.println("Pins configured.");
  Serial.println("Pin Information: \n            Relay: " + String(P_RELAY) +
                                  "\n           On LED: " + String(P_ON_LED) +
                                  "\n          Off LED: " + String(P_OFF_LED) +
                                  "\n    Manual Switch: " + String(P_SW_MAN));
  if (hostWebServer && connectToEthernet) {
    Serial.println("Remote controller interface is running at http://" + localIp + "/");
  }
  if (testRelay) {
    Serial.println("Testing relay mode enabled.");
    Serial.println("Toggling relay every " + String(testRelayDelay) + " milliseconds...");
  }
  const unsigned long starttime = (millis() - started);
  Serial.println("Startup took " + String(starttime) + " milliseconds.");
}

void loop() {
  if (testRelay) {
    delay(testRelayDelay);
    if (RELAY_STATE) {
      toggleRelay(false);
    } else {
      toggleRelay(true);
    }
  }
  if (useDHCP) {
    byte dhcpRenew = Ethernet.maintain();
    if (dhcpRenew == 1) {
      Serial.println("Dynamic DHCP lease renewal failed.");
    } else if (dhcpRenew == 2) {
      Serial.println("Dynamic DHCP lease was renewed.");
    } else if (dhcpRenew == 3) {
      Serial.println("Dynamic DHCP lease rebind failed.");
    } else if (dhcpRenew == 4) {
      Serial.println("Dynamic DHCP lease was rebound.");
    }
  }
  EthernetClient client = server.available();
  if (client) {
    Serial.println("Client connected to web server.");
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }

        if (String(c) == "\n") {
          Serial.println("Data received from HTTP client: " + String(readString));

          // HTTP header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          // HTTP body
          if (readString.indexOf("?state") > 0) {
            if (RELAY_STATE) {
              client.print("1");
            } else {
              client.print("0");
            }
          } else {
            client.println("<!DOCTYPE HTML>");
            client.println("");
            client.println("");
            client.println("<title>Power-Point Controller</title>");
            client.println("");
            client.println("");
            client.println("
hello world
");
            client.println("");
            client.println("");
          }

          delay(10);

          client.stop();
          Serial.println("Client disconnected from web server.");

          if (readString.indexOf("?relay=1") > 0) {
            toggleRelay(true);
          } else if (readString.indexOf("?relay=0") > 0) {
            toggleRelay(false);
          }

          readString = "";
        }
      }
    }
  }
}

void toggleRelay(bool state) {
  if (state == true) {
    digitalWrite(P_OFF_LED, LOW);
    digitalWrite(P_RELAY, B_RELAY_ON);
    digitalWrite(P_ON_LED, HIGH);
    RELAY_STATE = true;
    Serial.println("Relay State: ON");
  } else if (state == false) {
    digitalWrite(P_ON_LED, LOW);
    digitalWrite(P_RELAY, B_RELAY_OFF);
    digitalWrite(P_OFF_LED, HIGH);
    RELAY_STATE = false;
    Serial.println("Relay State: OFF");
  }
}

http://stackoverflow.com/help/mcve

When you say "my code therefore doesn't work", what serial output messages did you get ? Did the server IP address answers to a ping from client side ? (useDHCP and testRelay are false, so test your source without that superfluous code).

Everything looked like it worked as expected, except it didn't. Read my comment on the accepted answer as to the reason :)

I don't understand why my code therefore doesn't work.

Without any in-depth analysis of your code I would suspect that you have simply run out of memory. It is easy to forget that the Arduino Uno is a very small machine with limited resources.
Here are some steps forward:

Check memory status (compile and run-time).
Use the F() macro to force string literals to be stored in program memory.
Reduce String class operators especially on print statements. Simply replace with multiple print statements.

Cheers!

This was part of the answer, the other part which I discovered just now was me using pin 10 for something without realising Ethernet wanted it.
Thanks a lot!

authors: Vladimir F Героям слава


text:
Communication between Arduino and iOS device
How can I get weight that has been measured by an Arduino device to show up on an iOS mobile or tablet device as a number?
Thanks.
Warmly,
N.

There are cables that let you plug in to the 30 pin connector and get a connection.
You could also use a BLE shield and write code for both platforms that communicate via BLE, or a WiFi shield.

There are a couple apps for this application but first you need the Arduino connected to the internet. It's called Iarduino and the instructables can be found here. I don't believe that you can communicate with your ios device with blue tooth. The app should allow for serial communication but I am not an expert on serial.

You can connect Bluetooth to IOS.

iOS doesn't support Serial over BlueTooth. So those cheap bluetooth modules don't work. There are other types of Bluetooth profiles do work, but are a bit harder to implement.

The last several generations of iDevices have supported Bluetooth Low Energy (BLE) with arbitrary peripherals, and encapsulating a (low rate) serial stream is possible.  They also support legacy bluetooth, but are locked down to only talk to "approved" peripherals - a restriction which does not apply to BLE.


text:
How can I stop SoftwareSerial from receiving data and re-enable it at some other point?
My project involves and RFID reader connected to an Arduino Pro Mini (5V, 16MHz) and an Adafruit CC3000 breakout WiFi chip. The device reads RFID tags and sends them to my web service. I am using Software Serial to read the RFID device data.
After I scan something, the Arduino tries to send the value that was read to the web service. This obviously causes a delay and the program only continues execution (i.e. next iteration of the loop() function) after the data has been sent.
My problem is simple. While the value is being sent, the serial buffer is can still accept scans from the RFID reader and on subsequent iterations, because there is data in the buffer the device attempts to send data again.
My question is how can I stop the software serial port from receiving data while I am trying to send data to the web service? Then when the data is sent successfully, how can I re-enable the software serial port from accepting data?

Beware the when you re-enable receiving from an asynchronously transmitter source, you will have a high chance of seeing the tail end of a message which began while you were disabled, so you will probably need logic to discard incoming characters until you see the start of a new, valid message.

Call serial.end() to stop receiving.
Then call serial.begin(...) again when you want to start listening again.

According to the docs, SoftwareSerial doesn't support .end(), so Gerben's answer won't work here, I think.
It's hacky, but you could exploit the fact that only one SoftwareSerial can receive data at a time, and create a second one, activating it with SoftwareSerial.listen().  Then .listen() again on your original SoftwareSerial, when you want to resume listening.
Or, you could do as Marty Grogan says, and flush the read buffer before starting a new read.  Again, I don't think SoftwareSerial supports a flush method as such, so you'd need to just .read() until there's nothing .available().

SoftwareSerial doesn't support .end() - it does now, maybe it did not before. @Gerben linked to the source which shows the exact lines of code. They turn off the pin-change interrupts for that pin, thus (that instance of) SoftwareSerial will no longer react to incoming data.

Again, I don't think SoftwareSerial supports a flush method as such - again, it does now, as the source code shows. You may wish to edit your answer, to keep it up to date... :-)

Whether or not the serial data becomes available really does not matter.  If you flush the port before every read rather than consuming the data, let 'er rip.  If you are using interrupts, toggle interrupts on the serial pin.

Just a guess but I believe the current version of SoftSerial actually uses PCINT to detect the individual bits. I believe if that were disabled you would stop reception. It will take some work to get it to work without problems. This is just a guess.

The important parts are the GPS.end() which removes the interrupt routine and effectively stops listening to input although the data continues and the GPS.begin(baud) which reinstates the interrupt routine.  The other statements are program specific and could be anything that you want to do while the input data processing is off.
I am using it on a project where I smooth scroll time/date on an LED matrix but the SoftwareSerial interrupt routine makes the scrolling jerky.  I have reduced the NMEA sentences to just one but it still takes a noticeable amount of time to process it.  So the GPS is always on and sending but I only listen 4 times per hour by doing an ss.begin() for 5 second (or until valid data), save it then do the ss.end().  Problem solved.  I get mildly jerky scrolling for 5 seconds but it is rarely noticed and my time is always right.
I will post the routine on my web site, ILikeTheInternet.com, in a few days.

If you could post the routine in your answer that would be useful, as links tends to die after a period of time. Also Iliketheinternet.com doesn't appear to respond to http requests currently.

I have successfully used two Software Serial interfaces by using the .listen() method.
SoftwareSerial swSerial1(4,5);
SoftwareSerial swSerial2(6,8);

swSerial1.begin(9600);
swSerial2.begin(9600);

At this point the Arduino is listening to swSerial2 because it was defined last. If I wanted to use swSerial1 in the loop I would call
swSerial1.listen();

And switch back with
swSerial2.listen();

This avoids the significant overhead of ending and re-beginning software serial connections.

I had the same problem with reading GPS-Data on Port 11 while sending APRS-Data out. This code worked for me:
GPS.end();

aprs_send();
while (afsk_busy());

GPS.begin(GPS_BAUDRATE);

Should the two lines in the middle be ran right after GPS.end() or right before GPS.begin()? What do they do?

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


text:
How to wait for next n bytes in I2C exchange?
I'm trying to get data from a sensor, but don't see how I can get data back. I'm looking at the data on the I2C bus with a logic analyzer, and I'm sending what I expect, but I seem to cut off the slave before he can respond.  My understanding from the datasheet is that I need to send this command to wake it up and request a measurement:
0xD8 0x30 0x0A
and then I need to send this command to get the data:
0xD8 0x06 0xD9
#define HEARTBEAT_PIN            (13)

#define 7BIT_ADDR                (0x6C)
#define ADDR_WRITE               (0xD8)
#define ADDR_READ                (0xD9)

#define MAX_NUM_RX_BYTES         (8)
#define MAX_NUM_TX_BYTES         (8)

static uint8_t tx_buffer[MAX_NUM_TX_BYTES];
static uint8_t rx_buffer[MAX_NUM_RX_BYTES];
static uint8_t new_rx_data;

void setup(void) {
  // Clear any module memory
  memset(tx_buffer, 0, MAX_NUM_TX_BYTES);
  memset(rx_buffer, 0, MAX_NUM_RX_BYTES);
  new_rx_data = false;

  Wire.begin();
}

void loop(void) {
  RequestMeasurement();
  delay(10);
  GetData();
  delay(500);
}

void RequestMeasurement(void) {
  // MR: 0xD8 0x30 0x0A
  // Internal (to IC) register address?
  tx_buffer[0] = 0x30;
  // Request-measurement command
  tx_buffer[1] = 0x0A;
  Wire.beginTransmission(7BIT_ADDR);
  Wire.write(tx_buffer, 2);
  Wire.endTransmission(true);
}

void GetData(void) {
  // GD: 0xD8 0x06 0xD9 0x?? 0x?? 0x?? 0x?? 0x?? (0x?? => slave data)
  // Slave address + 'write' indication bit
  // Internal (to IC) register address?
  tx_buffer[0] = 0x06;
  // Slave address + 'read' indication bit
  tx_buffer[1] = ADDR_READ;

  Wire.beginTransmission(7BIT_ADDR);
  Wire.write(tx_buffer, 2);
  Wire.endTransmission(true);

  // HOW DO I LEAVE THE BUS OPEN LONG ENOUGH
  // FOR THE SLAVE DEVICE TO RESPOND WITH THE DATA?
  //Wire.requestFrom(7BIT_ADDR, 3, true);
}

Ensure pullups (see datasheet for min acceptable resistance) are on I2C lines.
What I didn't understand at first was where the Wire library would bit shift and add read/write indication bits.  And those start/stop booleans.  After some testing and a closer read of the docs, I got this to work:
#include "Wire.h"

#define BAR_7BIT_ADDR         (0x6C)
#define MAX_NUM_RX_BYTES      (5)
#define MAX_NUM_TX_BYTES      (3)
#define FIRST_TEMP_BYTE_INDEX (3)

uint8_t new_rx_data;
uint8_t tx_buffer[MAX_NUM_TX_BYTES];
uint8_t rx_buffer[MAX_NUM_RX_BYTES];

void setup(void) {
  Serial.begin(57600);
  Wire.begin();
}

void loop(void) {
  // If new data is available
  if (new_rx_data) {
    new_rx_data = false;

    // Process the data in the background
    PrintRxData();
  }

  BAR_RequestMeasurement();
  BAR_GetData();

  // This is a bit of a hack to get this function to execute.
  // After attempting to register this function as a callback with
  // the Wire.onReceive() method the function wouldn't execute.
  BAR_OnDataReceived(0);

  // Wait a tit, then do it again
  delay(500);
}

void RequestMeasurement(void) {
  // MR: 0xD8 0x30 0x0A
  // Internal (to IC) register address
  tx_buffer[0] = 0x30;
  // Request-measurement command
  tx_buffer[1] = 0x0A;
  Wire.beginTransmission(BAR_7BIT_ADDR);
  Wire.write(tx_buffer, 2);
  Wire.endTransmission(true);
}

void GetData(void) {
  // GD: 0xD8 0x06 0xD9 response from slave
  // Internal (to IC) register address
  tx_buffer[0] = 0x06;
  Wire.beginTransmission(BAR_7BIT_ADDR);
  Wire.write(tx_buffer, 1);
  Wire.endTransmission(false);
  Wire.requestFrom(BAR_7BIT_ADDR, 5, true);
}

void OnDataReceived(int num_bytes) {
  uint8_t i = 0;
  while (Wire.available() && i < MAX_NUM_RX_BYTES) {
    rx_buffer[i++] = Wire.read();
  }

  // Indicate to the background that there is new rx data
  new_rx_data = true;
}

void PrintRxData(void) {
  Serial.print("Pressure [kPa]: ");
  Serial.print(ToKpa(rx_buffer));
  Serial.print("\r\n");

  Serial.print("Temperature [C]: ");
  Serial.print(ToCelsius(&rx_buffer[FIRST_TEMP_BYTE_INDEX]));
  Serial.print("\r\n");
}

// Returns the pressure in kPa given raw binary data
float ToKpa(uint8_t* raw_data) {
  // example: raw_data[3] = {0x63, 0x6C, 0xBB}; => 101.81kPa
  // return ((float)((((uint32_t)raw_data[0]) * 65536) |
  //                  (((uint32_t)raw_data[1]) * 256)  |
  //                  (((uint32_t)raw_data[2]) * 1))) / 64.0 / 1000.0;
  return ((float)((
                  (((uint32_t)raw_data[0]) << 16) |
                  (((uint32_t)raw_data[1]) << 8)  |
                  (((uint32_t)raw_data[2]) << 0)
                  ) >> 6)) / 1000.0;
}

// Returns the temperature in Celsius given raw binary data
float ToCelsius(uint8_t* raw_data) {
  // example: raw_data[2] = {0x18, 0xE6}; => 24.90C
  // return ((float)(((uint32_t)raw_data[0]) * 256) + (((uint32_t)raw_data[1]) * 1)) / 256.0;
  return ((float)(
                 (((uint32_t)raw_data[0]) << 8) |
                 (((uint32_t)raw_data[1]) << 0)
                 )) / 256.0;
}

First off; when talking about I2C bus, an important point to clarify: did you connect pullup resistors to both SDA and SCL lines (A4 and A5 respectively)? Without those, the I2C bus will not work properly.
Next, I2C protocol is quite low-level and a bit complex; but fortunately, the Wire library that comes with Arduino helps a lot and hides some of this complexity.
When using Wire library, there is a first point to keep in mind:
The device address is 7 bits only, the 8th bit is used to define the direction of data (read or write). You don't need to care about this direction bit as Wire deals with it for you.
In your situation, the device address is 0x6C, ie 1101100 in binary.
The commands you mentioned that you want to send to the device, 0xD8 0x30 0x0A and 0xD8 0x06 0xD9 already include the device address and the write bit (0):
0xD8 is 1101 1000 ie 1101100 plus the 0 direction bit at the end.
Please note that 0xD8 0x06 0xD9 is made of 2 commands actually:

0xD8 0x06 is a write command to tell the device hich register we want to read
0xD9 is just the device address followed by the read bit (1): this is the way the I2C master tells a slave that the former will now wait for data sent from the latter.

It is important to split this command in 2 because each will use a specific API from Wire library.
Writing to your device with the Wire library will be done this way:
// First command: start measurement
Wire.beginTransmission(0x6C);
Wire.write(0x30);
Wire.write(0x0A);
Wire.endTransmission();

// Second command: tell the device what register we want to read
Wire.beginTransmission(0x6C);
Wire.write(0x0A);
Wire.endTransmission();

Then you can start reading from your device with a different API:
Wire.requestFrom(0x6C, 3);
byte b1 = Wire.read();
byte b2 = Wire.read();
byte b3 = Wire.read();
// Now rebuild value from the 3 bytes just read...

Note that Wire.requestFrom(0x6C, 3); will send the 0xD9 that is calculated from the device address 0x6C and the read bit. SO you don't have (and you should not) send 0xD9 yourself, Wire doesit for you.
Please note that I use Wire.endTransmission() without the stop argument. Not sure if this is mandatory, but it worked fine on my I2C experiments.

In the diagram there is a S after sending 0x60. You first write to the device, letting it you want to read, and then you start reading.
I think you need to do something like
void GetData(void) {
  Wire.beginTransmission(7BIT_ADDR);
  Wire.write(0x06);
  Wire.endTransmission(false);//don't terminate connection

  Wire.requestFrom(7BIT_ADDR, 3);//this will send the 0xD9
  pressure = ( (uint32_t) i2cread() << 16) | ( i2cread() << 8 ) | i2cread();//or something

}

But I've never used I2C.


text:
ATMega328P not running sketch in standalone (works in Uno R3 Board though)
I bought an ATMega328P-PU and burned OptiBoot onto it using a second Arduino Uno R3 with great success.
I then put the microcontroller back on the (empty) Uno R3 (DIP) Board for programming, connected USB and uploaded the blink sketch successfully.
Now to the weird stuff:
Blink works on the Arduino Board itself, but if I pull it out and stick it into my breadboard, the program seems to not start. Here are some facts:

happens with or without external crystal 16.000 (Pin 9-10)
happens with or without the 22pF capacitors from crystal to GND (9-GND, 10-GND)
happens with Fuses set to internal OSC or to external clock (Uno default)
happens with or without the ADC VCC (Pin 20) and REFERENCE (Pin 21) Pins @ 5V
happens on 5V and on 3V3
happens with or without external Pullup on RESET Pin (1)
Most of the output Pins sit at 0.8 V

Could you post a diagram of your circuit (the one on breadboard). Particularly useful would be power supply and its regulation. Also, do you use a decoupling capacitor, between 5V and GND, near the MCU?

I supplied either 5.1 V from my computer, or 5 V by using an LM7805 (without any capacitors, yet). I also use a 100 nF ceramic capacitor at the nearest point of the MCU between VCC and GND.

I would expect if you connect a scope to your +5 it is oscillating like crazy.  ALWAYS put the recommended capacitors as close as possible to the regulator (check manufacturer's data sheet they are not all the same). It is amazing how many designs I have seen with problems caused for this very reason and the variety of abnormalities displayed. Finding this problem without a scope is extremely hard so simply add them they are not expensive and the regulator will operate cooler.

I found the solution by accident.
While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.
What did I measure?
Actually I was just measuring one of the crystal pins (Pin 9 or 10). The sketch went running for a few seconds and very different speeds and then stopped.
This small change in voltage gave the ATMega the clock signal it needs to step through the program.
Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.
The perfect solution
As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.

This is not an answer to your question! You should rather edit your question to include the content of your answer, and then delete your answer.

@jfpoilpret - untrue, this is an answer as it solves the problem.  It may not satisfy all curiosity though.

Seems like you might have a resonator not designed for external caps rather than a crystal.  Or the substantial parasitic capacitance of your breadboard may add up to too much with the caps (ideal value takes layout into consideration!) Another possibility is misinterpreting capacitor value markings - they could be bigger than believed.

@Chris-Stratton You're right, actually I misread the answer and did not see upfront that it worked without the 22pF caps, I needed to read it a second time to see it as a solution! Maybe editing it would make that appear better?

Dear Sir @ChrisStratton. You were absolutely right. I just checked the printed numbers on the two capacitors under the magnifying glass. They are not 22pF, they are 220nF (Code 224). The 4 was on the side of the capacitor... Pure human failure. Thank you for the tip, I would not have checked it else.


text:
motor shield directly to PC? WITHOUT ARDUINO!
Is there a way to connect and control motor shield board WITHOUT Arduino at all.
can i connect it directly to my PC ?
i'm getting confused since i red lot of topics that people use existing pins on motherboard.

Is there a reason, why you would want to do this? Misusing a motherboard like that (if it is really possible) does only make sense, if you are doing it for the fun of hacking your motherboard. It would be way more complicated and would definitely don't cost much more, than the typical arduino/microcontroller solution. If an original Arduino costs too much, you can buy a china clone, which are way cheaper.

It's educational.
why can not we just use UBS output to control something like motor shield board,
can get's it's ones and zeroes from USB instead of arduino, since we have all the computing power we need on PC?
is there any USB version of motor control boards? and why not..

If you have a PC with a real Parallel Port ( LPT1: ) and you don't run an Operating System on it, ( or perhaps MS-DOS ) ... you can connect some leds, but you cannot use an Arduino shield directly.

Re “If [...] you don't run an Operating System on it”: You can do it on Linux from a privileged process, if you first request access to the port's IO registers with ioperm(0x378, 3, 1);.

To a normal PC? No. You can't. A PC doesn't have the GPIO pins etc that are needed.
You could wire it to a Pi though.

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


text:
HX711 - Inconsistent Readings

simulate this circuit – Schematic created using CircuitLab
Wiring is based on the scheme presented below -

(Reference: https://electronics.stackexchange.com/a/174580)
I am using Arduino Mega 2560, HX711 and four load cells to build a weighing scale but having a hard time calibrate the unit. I have tried different libraries and calibration schemes but none of them seem to help. I have found that the raw values corresponding to any given weight (including zero load) are not consistent. Firstly, the readings do not settle even after 10 minutes, and even if I take an average, the next time I put the same weight, I get an entirely different reading making the last average useless. I am seeing errors of the order of +/- 30 lbs when I put a known weight.
I first thought that maybe my load cells are the root cause but when hooked them up directly to Arduino and read the voltage across the bridge, I read stable constant values. Verified the voltage readings with a Voltmeter. (Yes, their resolution is not as good as HX711 but at least they are stable and consistent). I get the voltage reading close to my hand calculations.
Next, I tried testing the HX711 in different ways. In one test, I created a full-bridge using resistors other than load cells, forced the bridge out of balance but cannot read anything other than 16777215. Next, I wanted to see if the board is reacting to any voltage at all, so, I removed the bridge and did not connect anything to E+ and E- pins but supplied known voltages from a DC power supply (from 0 to 4.5V) to the A+ and A- (GND) pins. Now, it is reading only 8388607, no matter what voltage I supply. If I supply +5V or +3.3V from Arduino to the A+ and A- (GND) pins instead of DC Power supply, it then only reads 16777215.
I don't know how to interpret this behavior. How can I resolve the issue and bring the error down? Thanks for your help.
I have included the schematic below. All four Load Cells (LCs) are 3-wired (White, Black & Red). Resistance between W & B wires is around 1980 ohms while that between R & W or R & B is around 990 ohms. SO I connected the four LCs in the manner shown in the schematic. Wire colors have been labelled.
Code:
Code is pretty straightforward as I am simply reading raw values from the HX711 using the following HX711 library - github.com/queuetue/Q2-HX711-Arduino-Library.git
#include <Q2HX711.h>

const byte hx711_data_pin = 4;
const byte hx711_clock_pin = 8;

Q2HX711 hx711(hx711_data_pin, hx711_clock_pin);

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

void loop()
{
  Serial.println(hx711.read());
  delay(500);
}

Can you draw as a schematic or wiring diagram how everything is connected? And please provide your code in your question. Maybe there is something wrong with one of them

I have included both of them in the post. I think the variation in the values that I am seeing is because of residual strain and hysteresis but not sure of that. I have been noting the scale readings for past four days. I have not put any load at all and these are the readings I have obtained -
Day 1: 84442XX
Day 2: 84447XX
Day 3: 84442XX
Day 4: 84447XX
If zero lbs weight correspond to 84442XX, the same empty scale starts reading a different weight the other day. This is the problem I am trying to solve. I expect variation in readings since HX711 is 24-bit but what I have is too high.

If you getting readings at the limit of the HX711, (2^24=16777216) the load cells might not be close enough to identical, and you might have to bias them closer to zero.  Do you have a high resolution voltage meter that you can test the voltage difference between the signal+ versus signal-?  If it's more than 10-20mV, you could add a trim pot to bias a leg of the wheatstone bridge higher or lower.  //  Zero could move around significantly from day to day dependent on temperature and creep. Most use-cases of cheap load cells/scales have a means of zeroing them out immediately before use.

Here is is a picture of how I have seen the sensors connected.  Is this how your is?

When you connected the cells directly to the board, did you do it one at a time or all at once?  Is the board combining the weight values or is it done with the sensors/library?

Hi! Thanks for your response. I have tried many and currently am using the following HX711 library -
https://github.com/queuetue/Q2-HX711-Arduino-Library.git
And the code is simply reading raw values from ADC using hx711.read().
If I use a full-bridge of 4 load cells, I get continuously changing values and if I connect a full-bridge of one load cell and two external resistors, I only read 16777215 and nothing else.

I have connected them both ways. If I use a full-bridge of 4 load cells, I get continuously changing values and if I connect a full-bridge of one load cell and two external resistors, I only read 16777215 and nothing else, even if I put weights on the load cell.

My last piece of advice is to go over your connections for stray what ever.  Look at all the solder joints on EVERYTHING and see if you can find a bridge or something touching that should not.

Thanks for your time. I have checked it a number of times. Couldn't find any unintended connections plus all GND connections are also good.

Questions for clarity or similar belong to the comments under the question. When leaving that out, the question is reduced to "Try calibration". Please either use the comments (if you have enough reputation), or elaborate more about the calibration.

I understand, but it don't have the ability to comment yet, but I was trying to give help and ask questions.  I can delete the answer since no help full information was figured out.

@PriyeshSharma. Is your schematic accurate to how you have it wired?  The schematics I have seen have the sensors wired in a bridge configuration, you show a weird potentiometer setup that will probably result in the weird settings you see as the current is going to be doing wacky things as what you have will never balance out and show anything consistent.

@JeffA: Yes, this is how I have wired the load cells. The way I see it is these particular load cells are equivalent to variable resistors with their resistances changing as load is exerted and strain changes. Hence, the excitation is applied to and voltage is read from red wires (which equivalent to wiper of a potentiometer).

what is the part number for your load cells?

Bought them from Amazon. Do not have any part number or datasheet available. Looks like they are from a manufacturer called CJRSLRB. Not sure if they are the actual manufacturer or just the seller calling himself a manufacturer.

I am starting to think your HX711 is bad

Each of the cheap commodity three-wire red-white-black load cells has two strain gauges in it, configured as a half-bridge.  Under normal loading conditions, one strain gauge is compressed while the other is extended.  You can hook two of the cells up as two half-bridges and 4 strain gauges like your diagram if wire the half-cells white-to-black and black-to white to make sure they unbalance under load instead of balance.  Or you can hook 4 cells up per Priyesh's schematic with two strain gauges in series in each leg. See https://arduino.stackexchange.com/a/18698/6628

@PSharma have you ever been able to resolve the issue? If so, how ?


text:
How do you call a class method with named parameters?
I have a C++ class constructor like:
Motors(int p1=0, int p2=0);

However, when I attempt to instantiate it with named parameters like:
Motors motors(p1=123, p2=456);

the Arduino C/C++ compiler gives me the errors:
src/motors.ino:3: error: ‘p1’ was not declared in this scope
src/motors.ino:3: error: ‘p2’ was not declared in this scope

The compiler doesn't seem to support named parameters and thinks I'm referring to variables. I thought named parameters was a pretty widely supported feature, even in C++. What am I doing wrong?

C++ doesn't support named parameters, and I doubt it ever will.
It has strict calling conventions which mean you couldn't re-order the parameters at call-time without adding an unnecessary layer of data duplication/indirection (which would hurt performance). It would also need a significant change to compiler architecture, as variable/parameter names are usually stripped out long before the linker is invoked.
If you want to achieve a similar effect though, you could use comment blocks instead, e.g.:
Motors motors(/*p1*/ 123, /*p2*/ 456);


text:
Performance of internal vs external resistors
Is there any significant performance trade-off between buttons wired with the internal vs external pull-up/down resistors? I see a lot of tutorials demonstrating the use of external resistors when wiring a simple button, like this and this. But since the Arduino/AVR includes internal pull-up resistors, you can wire a button without any external resistor as demonstrated here.
Is there any good reason to complicate your design with an extra resistor?

If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.
There are a number of factors to consider.
If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).
If the pin is used as both input & output the pullup can reduce the voltage swing.
In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.

I think it depends on the application you're going for.  A simple switch probably doesn't need a resistor, since it doesn't require the chip to provide any specific voltage or current.
If you're trying to run an LED or something that requires a specific amount of current or voltage, then you may be better off supplying the power connection & resistor rather than relying on the chip to provide the proper power to the device.
Another situation may be where you're approaching the maximum power output of the chip that you might change to external pull-up/down resistors.

That's what I thought. I have a simple application that just has a few basic push-button switches, and I didn't understand why I was seeing so many complicated wiring schematics when simply connecting the button to ground and signal was sufficient. I just want to make sure I'm not missing something...

This anwser does not relate to the original question: pullup resistors are used for INPUT exclusively, hence they are not a matter of supplying current or voltage by the MCU. Limiting current on OUTPUT is another matter and can be done by resistors in series (not pure pullup).


text:
What is the maximum length an Interrupt Service Routine?
In general, what's the maximum length of instructions that can be included in an Interrupt Service Routine?
The docs say an ISR should be "as short and fast as possible", but that's bit vague.
For example, I have an ISR that gets called for each pulse on an motor's encoder.
void on_encoder_pulse(){
    encoder_change = true;
    count1 += 1;
    count2 += last_call;
    last_call = millis();
}

Will this run without interruption?

What is the maximum length an Interrupt Service Routine?

This depends on the max latency before servicing any other waiting Interrupt Service Routine (ISR).
An AVR ISR will execute with further interrupts disabled until the running ISR is completed. Any other interrupt(s) during the execution will be delayed. Data may be lost if the delay is too long. This depends on the interrupt source and frequency of interrupts.
In general an ISR (for incoming data) should only capture the data that could be lost and delay processing to the main loop function. A good example is the ISR for the Arduino Hardware Serial (USART) handling. Data sent and received are queued.
A traditional method (design pattern) is to have very short ISRs that capture data and push to an event queue. All processing is done in the main loop. This gives short latency and faster response, and reduces the risk of ISRs depending on each other, etc.
Cheers!

In general, on AVR devices, interrupts have been turned off (by hardware) when an ISR (interrupt service routine) begins execution.
Thus, if on_encoder_pulse() is an ISR and is invoked due to an interrupt,  it will run uninterrupted.
An ISR that within itself turns the interrupt system back on before it's done runs the risk of other interrupts being serviced before it completes.
The suggestion that ISR's be “as short and fast as possible” is intended to avoid other interrupts being missed, as will happen if an interrupt source activates multiple times while the interrupt system is off.  Most interrupt sources latch a bit and will be handled when the interrupt system is re-enabled; some don't latch a bit, and won't be seen if some ISR is long-winded.

As already explained by jwpat7, interrupts are, by default, not
interruptible. Thus, if another interrupt fires while your ISR is
running, it will no be serviced until your ISR completes. This delay you
impose on other interrupts is called latency. So your question boils
down to “how much latency can the other interrupts tolerate”.
There is no simple answer: it all depends on the timing requirements
of whatever those interrupts are servicing. For example:

The millis() counter is updated by interrupts. Any latency longer
than 1024 µs (on the Uno) can make it loose tics.
If you are using the serial port to receive data, a latency longer
than one byte time (1040 µs at 9600 pbs, less at higher baud
rates) will make you loose data.
If you are using the Servo library, any interrupt latency will
create jitter in the drive signal, and at some point this may become
visible as mechanical jitter.

Then, if you really need a precise answer, you will have to check the
timing requirements of every piece of hardware and every library you
are using. And then check the latency already imposed by the ISRs in
those libraries, as your latency can come in top of that.
If your program relies on loop() looping fast enough, you should also
keep in mind that interrupts also slow that.


text:
How to power up this LCD 7 segments display
I got two of these type of 7 segments display in LCD material.

And here is the datasheet

I tried to power up to UNO, it can make the segment on, while a second, the segment go off, but the pinMode does not changed.

Driving an LCD display is nothing like driving an LED display. You need to provide an alternating current to the right segments at the right time.
It is possible with an Arduino on a simple display like this, but not easy. Better is to use a chip that has a proper LCD display interface, such as the MSP430 "F" series (the FRAM ones).
To do it on an Arduino you need to treat it like a common anode matrix on one pass, and a common cathode matrix on the next pass, and do that repeatedly and rapidly.
That is, set COM1 HIGH and the other COMx pins LOW,  and the segments you want on LOW and the others HIGH, then do the same with COM2, etc. Then go back to the start and invert the logic, so set COM1 LOW and the other COMx HIGH, and your chosen segments HIGH.
It is best to do this from within a timer interrupt so that you can get good regular updates without your program causing delays.

But the issue as I can make a segment as ON, after about 0.5 second, the segment will auto off in fade out, but the arduino pin status did not changed. PS: I am using UNO.

That is because you aren't reversing the current like I instruct.

Could you please explain more ? or any schematic could provide ?

I thought I'd explained it perfectly clearly...

@AllenChak See first EEVblog #1045 - How To Drive an LCD for a basic explanation.

that's a controller-less dynamic (mutiplexed) display, with 4 coms.
So you will to program the mcu to do a lot:
1) the com pins are driven with 1/4 dc signal sequentially;
2) the seg pins are driven with 1/3 bias voltage. out-of-phase to be dark and in-phase to be transparent (not lit).
the way to do it is to:

put segment info in a buffer;
write a display update routine that scans digits and updates the com/seg pins according to the current digit's segment information;
call that display update routine periodically, preferrably from a timer isr.

the display update routine would be similar to an led display routine - an example of that (for led) would be here (https://dannyelectronics.wordpress.com/2017/06/30/a-more-flexible-driver-for-7-segment-leds/), but more complex due to the 4 com pins and bias generation.
it is much easier to pick a mcu with built-in lcd driver and program that mcu as a display controller / slave taking in information from a master (in this case your arduino).


text:
How to upload a sketch via Arduino Nano
I have two Nano boards, but the first one seems the CH340 chipset was burn. :( ,

Nano v3, CH340 chipset but unable to identify after connect to my Mac using USB
Nano v3, FTDI chipset and in good condition
USB to Serial module, using FTDI chipset

I am trying to upload a sketch via a USB-to-Serial module OR another Nano board (or UNO board v3) to my CH340 Nano Board.
Question:

How to wire them up?
Is it need upload a "Arduino as ISP" first?
step-by-step tutorial or website talking about this ??

I presume you have boot loader on your Nano, so you can use your USB to serial, just wire (D0)TX->RX(USB), (D1)RX->TX(USB), GND-GND and supply power to the target Nano. You will need to reboot Nano just before the uploading the code. Uploading is same as usual.
Using other Arduino as ISP needs more wires as well as 2nd Arduino, so i would use above method.

Firstly, yes, there are boot loader on Nano which chipset was burn one. Means solution A) using USB-to-Serial, B) "Arduino as ISP" board, both able to upload sketch to my broken Nano?

If only CH340 was burnt than yes, both shall work. CH340 (or FTDI) IC is only to provide USB to Nano D0 & D1 TTL serial conversion, so bootloader can detect and accept new firmware. BTW, there are different CH340 ICs and at least some drivers are incompatible among them. ISP programming method uses MCU SPI programming option so doesn't need USB-TTL conversion.

Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
Open Terminal from Recovery mode
Run the command csrutil enable --without kext
Reboot
Install driver


text:
Shift Register 74HC595 not working
I am trying to learn how to make a shift register work. I have been working off of the Arduino ShiftOut tutorial.
My issue is that the shift register isn't working when the circuit is powered and I am not sure what is wrong. I suspect the issue is with pins 10-13 on the 74HC595?
I have done this with an actual board and the 123d.circuits.io simulator with the same result:
http://123d.circuits.io/circuits/444111-shift-register

The code is very simple and taken from the tutorial:
// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

Why is GND (also) connected to Q0? Idem for STCP? You also need to swap the wires going to pins 11 and 12 on the chip.

@Gerben good catch that was a mistake.  see answer below for the other half of the fix

Solution: Remove ground from Q0 as Gerben correctly pointed out in comments.
Also: rotate LEDs 90 degrees so that the anode and cathode are on different rows.
What was tripping me up is in the Arduino tutorial diagram is a little unclear on this (I now understand why their way is correct and my way (in the question) was wrong:

What software did you use to draw this breadboard schematic? It's really nice.

@IOBToolkitTeam https://123d.circuits.io/circuits/444111-shift-register


text:
Arduino I can't make this statement work
int val1 = 0;
byte val2 = 10;
int buttonPin = A0;
byte result = 0;

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

void loop() {
    val1 = digitalRead(buttonPin);

    if (buttonPin == HIGH) {
        result = result + val2;
        result = result + 10;
    }
    else
    {
        digitalWrite(val1, LOW);
    }

    Serial.print("STATE   ");
    Serial.print(val1);
    Serial.print("    ");
    Serial.print(result);
    Serial.println();

    delay(100);
}

why did you post the code? ... what does the title of your post mean?

I trying to increase the value of result by 10 every time when the button is high

you have not said what is the problem ... it is like taking your automobile to a mechanic and saying "it has a problem" ... what do you think that the mechanic would repair?

what does button is high mean?

Please [edit] your question instead of putting additional information in a comment. You don't want to waste our time, do you? You hope that we think about your problem. BTW, what is your question?

One problem of your code is  that you are comparing the pin number of the button to HIGH, instead of the read button state. Will write an answer, when you made your question more clear, since I think this will not solve your problem completely

I'm sorry to say that your code is a complete train wreck. I know, you're still learning, but there's so many errors there that even a novice who had spent just a few minutes reading the documentation and examples would have avoided that it's just completely unrecoverable.

I appears you want to increment the result by val2 each time the button is pressed.  If you want to wire it up this way you can but there are potential issues with this, such as not catching each time you press the button, or thinking you pressed the button twice when you accidentally held it down for more than 100ms.  The code for this method is below:
const int buttonPin = A0;
bool buttonState = LOW;
int val = 10;
int result = 0;

void setup()
{
  pinMode(buttonPin,INPUT);
  Serial.begin(115200);
}

void loop()
{
    buttonState = digitalRead(buttonPin);

    if (buttonState == HIGH)
    {
        result = result + val;
    }

    Serial.print("STATE:   ");
    Serial.print(buttonState);
    Serial.print("\t");
    Serial.print("RESULT:  ");
    Serial.print(result);
    Serial.println();

    delay(100);
}

The way to prevent double counts or missing counts would be to use interrupts.  Later I may write that one up if you need that instead.
Good Luck!

I use void function to increase value. Thanks for you guys help


text:
Change USB VID and PID (Leonardo)
I'm new to using electronic boards, and have followed a guide online for printing a 6 DoF (degree of freedom) mouse. I'm stuck on an optional step that requires me to change the PID and VID of a "Arduino Leonardo" board.
I've located the appropriate "boards.txt" file, but I'm not sure which line to change. I've edited a few, but I'm worried I'll mess things up (a tutorial for it mentions they had destroyed 3 trying to rename it, and is back from 2009), and the ones I've changed do not result in a change.
I have checked out previous questions people have made regarding this topic, but quite frankly I can't understand the technical terms used in those.
This is the code in question I'm trying to compile, and lists example PID and VIDs as well.
I would love a clear explanation on which PID/VID I need to edit in the "boards.txt", so I can safely modify the board to be read as the space mouse in the code.

The Vendor ID (i.e. Logitech, Zerbra, ect) and Product ID (i.e. Specific Mouse made by Logitech, specific bar code reader by Zebra, ect) are values paid for by companies who manufacture USB peripherals.  When you use one of these VID/PID combinations you are telling your computer "your device is their device".  It's probably not on the up-n-up and you likely can't openly sell your USB product w/ "their VID/PID values". That said, you can probably make almost any VID/PID work on a Linux computer. On a Windows computer you probably have to masquerade as the USB peripheral you are imitating.

I see, that's understandable, selling products like that would fit pretty well under scamming and deceiving people. This is for a 3D printed project for my own personal use. Is it possible to change the right PID though, or is it sort of a territory where people aren't willing to openly discuss it since there's no real way to prove I'm not using it to mislead others?

I don't see a problem doing this for personal use.  Your question sounded like you didn't know what VID and PID numbers were used for.  So, a little background.  I'd write an answer ... but I'm still not clear if just knowing what a VID/PID number answered your question.
As for bricking your Arduino, well, if there is only 1 USB on your Arduino and you change the VID/PID away from being a USB/CDC device, then the connected computer will likely not talk to it.  But this has more to do w/with the processor (or USB interface device) used in your particular Arduino.

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". This is not a forum. Then come back and [edit] your question for clarification. -- I will not look into externally linked sources on some website. Can't you show a minimal example? -- The tutorial is not for the Leonardo, AFAIK the Leonardo does not use an FTDI chip for USB. -- What is this "boards.txt" you mention? -- Why do you need to change the VID/PID at all? -- Please provide a link to this "guide online".

I'm stuck on an optional step that requires me to change the PID and VID of a "Arduino Leonardo" board. - If it's optional and you are stuck, I suggest ignoring that step. If it's optional it can hardly require you to do it.

@thebusybee What is this "boards.txt" you mention? - Really? boards.txt is a well-known file that specifies baud rates, processor types, fuse settings and so on, generally used during the process of uploading code to a board. I'm not sure of the exact way it is used, but my guess is that the IDE reads that file in, populates its list of supported boards, and then when you choose one, sets up various defines used in the compile and uploading process.

I need to edit in the "boards.txt", so I can safely modify the board to be read as the space mouse in the code. - What's a "space mouse"?

@NickGammon This code makes your Arduino act as a 3DConnexion SpaceMouse. The "space mouse" is the "6 DoF (degree of freedom) mouse" they mentioned.

@NickGammon "The tutorial is not for the Leonardo, AFAIK the Leonardo does not use an FTDI chip for USB. " Pretty sure the idea is that the FTDI chip seems to contraindicate a normal Leonardo and by extension the normal boards.txt. That is, the busybee is NOT asking "what is this boards.txt thing you speak of?".  They're asking the OP to positively identify the specific boards.txt, which may or may not wind up being the on you've linked to. And that will potentially answer half a dozen questions. That's what I get out of it anyway.


text:
Arduino How can I add 30s delay and turn off the led to the following code
const int buttonPin =  2;
boolean currentState = LOW;
boolean lastState    = LOW;
boolean stateChange  = false;

int currentButton = 0;
int lastButton    = 4;
int ledArray[]    = {9, 10, 11, 12};
long previousMillis = 0;
long interval = 1000 ;

void setup() {
        pinMode(buttonPin, INPUT);
        for (int i=0; i<5; i++){
            pinMode(ledArray[i],OUTPUT);
        }
        Serial.begin(9600);
}

void loop(){
            currentState = debounceButton();
            stateChange = checkForChange(currentState, lastState);
            currentButton = getButtonNumber(lastButton, currentState, stateChange);
            indicatorLight(currentButton);
            lastState  = currentState;
            lastButton = currentButton;
}

boolean debounceButton()
            {
            boolean firstCheck   = LOW;
            boolean secondCheck  = LOW;
            boolean current = LOW;
            firstCheck  = digitalRead(buttonPin);
            delay(50);
            secondCheck = digitalRead(buttonPin);
                    if (firstCheck == secondCheck){
                        current = firstCheck;
                    }
            return current;
}

boolean checkForChange(boolean current, boolean last)
        {
        boolean change;
                if (current != last){
                    change = true;
                }
                        else {
                        change = false;
                        }
                return change;
}

int getButtonNumber(int button, boolean state, boolean change)
            {
            if (change == true && state == LOW){
                button++;
                        if (button > 3){
                        button = 0;
                        }
                        Serial.println("g");

            }
            return button;
}

void indicatorLight(int button)
         {
                for (int i=0; i<4; i++) {
                            digitalWrite(ledArray[i], LOW);
                        }
                        digitalWrite(ledArray[button], HIGH);
  }

Use millis() to capture a timestamp of when you are turning the LED on, then use that in loop() to check, if more than 30s passed. In that if statement turn off all LEDs. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE

You have the right idea to debounce the buttons, but there is a 50 ms delay per button which blocks the loop for a total of 200 ms with four buttons.
So consider using a non-blocking debouncer of which there are many examples on the internet, but here is a simple debouncer I put on GitHub. It could be implemented something like the following example:
#include "debouncer.h"

const uint16_t LED_OFF_TIME_DELAY_ms = 2000;  // milliseconds. For testing.
//const uint16_t LED_OFF_TIME_DELAY_ms = 30000;  // milliseconds.

struct ButtonLed
{
  Debouncer button;
  byte button_pin;
  byte led_pin;
};

const ButtonLed BUTTONS_LEDS[] =
{
  { Debouncer(5, 50, LED_OFF_TIME_DELAY_ms), 5, 11 },
  { Debouncer(4, 50, LED_OFF_TIME_DELAY_ms), 4, 10 },
  { Debouncer(3, 50, LED_OFF_TIME_DELAY_ms), 3, 9 },
  { Debouncer(2, 50, LED_OFF_TIME_DELAY_ms), 2, 8 }
};

void setup()
{
  for (const auto& button_led : BUTTONS_LEDS)
  {
    pinMode(button_led.button_pin, INPUT_PULLUP);
    pinMode(button_led.led_pin, OUTPUT);
    digitalWrite(button_led.led_pin, LOW);
  }
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  uint16_t timestamp = millis();

  //
  // TASK 1: Read the buttons and set their corresponding LEDs.
  //

  for (const auto& button_led : BUTTONS_LEDS)
  {
    button_led.button.Update();
    if (button_led.button.Fall())
    {
      digitalWrite(button_led.led_pin, HIGH);
    }
    else if (button_led.button.RepeatCount() == 1)
    {
      digitalWrite(button_led.led_pin, LOW);
    }
  }

  //
  // TASK 2: Blink the inbuilt LED.
  //

  const uint16_t LED_BLINK_INTERVAL = 100;
  static uint16_t led_blink_previous_timestamp = timestamp;
  static bool led_state = false;
  if (timestamp - led_blink_previous_timestamp >= LED_BLINK_INTERVAL)
  {
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    led_blink_previous_timestamp += LED_BLINK_INTERVAL;
  }
}

And here it is in action in the Wokwi simulator:


text:
How to connect Arduino Pro Mini with PC?
I'm about to buy Arduino Pro Mini (http://arduino.cc/en/Main/ArduinoBoardProMini).
As far as I can see it requires FTDI or similar circuit to program it.
Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?
Is this also case with Arduino Pro Micro? (https://www.sparkfun.com/products/12640)
Thanks in advance
Petar

After the sketch is uploaded you only need to provide the board power. The FTDI is only used for programming.

V-USB can be used to create a low-speed USB device in software, but you will need to program the chip before you can use it. It also has a number of caveats that must be adhered to regarding electrical and software specifications, so it not the best choice for an absolute beginner.
A USB-UART bridge (not necessarily a FTDI chip, although that is (was?) the most popular solution) will allow you to program and communicate with the chip over its serial port, but any AVR ISP programmer can also be used to program it without requiring a preexisting bootloader in place.

Thanks for quick replay. Info was very helpful. For now I will stick to the Micro board thus it has built in USB chip, but for later projects i will try V-USB (at least for those w/o high-speed communication requirements).

The "Arduino Pro Micro" has its own USB interface so you don't need extra stuff for it to work. However, a number of existing libraries that deals with Arduino shields do not support the new chip inside the Arduino Pro Micro (ATmega32U4) so check first to make sure it will work with what you need.
For the "Arduino Pro Mini" (which I use a lot since it is very very cheap, about $3 from ebay) to program it I use "USPASP" (also cheap ~$3) so I have three of them but you only need one to program as many Pro Minis as you like. And for communication I use a "USB to TTL UART" (based on the "CP2102" chip which works with Linux, Windows and Mac) they are also super cheap (about $2) and you connect it to the serial pins on your Pro Mini.
(Just search ebay for the terms I put in quotes and you will find many of them at low prices, they ship from china so it will take about a month to get to you which is why I ordered more than I need for future projects, or for a little extra you might find local sellers with same products)


text:
Arduino Nano no serial port for MacBook Air 2013
Problem
I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected.
Opening the Arduino software, pulling down the Tools > Serial Port menu does not show me a valid serial port. All I see is:
/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

What I've tried and did not work

I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg. Restarted after installation.
Tried connecting arduino to both USB ports on my Air.

More Info

Running Mac OSX 10.10 Yosemite
Same arduino and cable work when connected to a Windows machine or a Raspberry Pi.

If it helps, I can see the USB Serial in my Apple Logo > About This Mac > System Report under Hardware > USB
USB2.0-Serial:

  Product ID:               0x7523
  Vendor ID:                0x1a86
  Version:                  2.54
  Speed:                    Up to 12 Mb/sec
  Location ID:              0x14100000 / 8
  Current Available (mA):   500
  Current Required (mA):    Unknown (Device has not been configured)

I'm out of ideas and options. Any help would be greatly appreciated.
Thanks in advance :)

Is your nano a clone or a real nano?

It's a clone. Thought I've read that it's a real good one. Anyway, I found something that solved it for me. Going to put it as an answer.

Did you have it plugged into a Windows machine first or before you plug it into your Mac?it might've been bricked but the good news is you can unbrick it.

First time I tried it on my Windows. But it turns out that I needed some additional driver for Mac. See my answer.

This solved it for me.

Download this driver
Install it
Run sudo nvram boot-args="kext-dev-mode=1"
Reboot

Serial ports now showed up in the Arduino IDE and also when I used ls -1 /dev/tty*
Hopes this helps someone.
Reference: This thread

Thanks for this answer. This fixed my problem as well. Setup: Yosemite, 10.10.5 and this arduino uno clone: AVR-Duino / Mega 2560 UNO

On 2016-04-13, I downloaded the (version 1.2?,  dated 2015-11-19?) driver from there, did the required reboot, and did not need to do the unsigned driver kext setting.  On plugging it in, the device showed up as '/dev/cu.wchusbserialfa130' in Arduino/Tools/Port.

Please update your answer to reflect the fact that it's not longer necessary to tinker with the OS X kernel to allow unsigned drivers to be loaded in kernel space which is a gigantic security risk. Latest OS X recognises these vendor and product IDs correctly, without the need to install any drivers. Product ID: 0x7523, Vendor ID: 0x1a86.

Oh and the unsigned kext setting is not needed anymore because this chip is widely used by Arduino and other embedded boards. Read more...

@Paul-SebastianManole - please post your own answer, pointing this out. References to supporting information would help. For example, what is "Latest OS/X" exactly? Reading that I don't know if I have the latest or not. And certainly in 5 years time people will wonder. Something better would be: "OS/X version 10.8.6 onwards supports this ..." (or whatever version it is).

@NickGammon can't you read dates? How many major version updates of OS X does apple put out in a year? Besides, my answer would be the same except that little bit of information I added. And I did post a reference.

Yes, I am familiar with dates. For a novice, it isn't obvious which part of the answer is tinkering with the OS/X kernel, and which part isn't. I suggest you post your improved answer.

Beware! Kernel Panic! on macOS Sierra, as of 25th September, 2016.

@Paul-SebastianManole - device is not recognized by El Capitan (10.11.6; newest this ancient MacBook supports in Oct 2016) and drivers still need to be installed.

@Jangid didn't see your message before installing. What did you do to fix the problem?

To those wondering: I fixed the kernel panic on macOS Sierra with this: https://www.simplicate.info/2016/09/16/ch340-drama-osx-10-12-sierra-16a313a/


text:
While Loop does not stop when condition is false
Here's the code:
void loop() {
  while (1 == 1) {
    ObsLeft();
    while (SeeLeft < 50 || SeeLeft == 50) {
      Urong();
      ObsLeft();
      if (SeeLeft > 50) {
        Hinto;
        break;
      }
    }
  }
}

ObsLeft() analogReads the Infrared sensor input and Serial.prints it
Urong() makes the sumobot go backward
Hinto() stops the robot
SeeLeft is the analog value given by the Line Sensor (in my experience, white is 42, black is 800+)
The Problem:
When I run the program with the sensor seeing White, it makes the robot go backward, but when I move the bot so that the sensor sees Black, it still keeps going.
When I run the program with the sensor seeing Black, it does nothing.

while (1==1) is redundant. the loop() loops

Hinto; is the address of the function. Hinto(); calls the function.

Please post a full functioning code. Also I think you have forgotten the parenthesizes after Hinto, since it is a function. Maybe a copy paste error. Is 50 really a good value to distinguish between black and white, when white is 42 and black is over 800? In such a situation the analog value might easily go over 50 due to noise. Have you tried a threshold value a bit higher, maybe 100?

while (SeeLeft < 50 || SeeLeft == 50) { is same as while (SeeLeft <= 50) {

Usually, in arduino programming while loops should rather be ifstatements and leave looping to the loop() function. This is a good example. As long as there's no definition of variables (SEELEFT) and no hint where, why and how they ever change, any more help is questionable.

have you considered the possibility that the condition is not false?


text:
Code for a load cycler seems to be stuck
I am trying to make a battery load cycler to charge and discharge a battery repeatedly for a certain amount of cycles and here is my code:
bool in_charge_mode;
int cycles = 0;
float cutoffvoltage = 2.0f;

float get_batt_voltage() {
    return analogRead(A1) * 5.0f / 1023.0f;
}

void set_charge_mode() {
    in_charge_mode = true; // remember state
    digitalWrite(13, HIGH); //start charge
    digitalWrite(12, LOW); //stop discharging to load
}

void set_discharge_mode() {
    in_charge_mode = false;
    digitalWrite(13, LOW); //stop charge
    digitalWrite(12, HIGH); //discharge to load
}

void setup() {
    Serial.begin(9600);
    pinMode(12, OUTPUT); //Connected to relay 1 which is relay for load
    pinMode(13, OUTPUT); //Connected to relay 2 which is relay for charger
    // Check initial voltage
    float vbat = get_batt_voltage();
    if (vbat < cutoffvoltage) {
        // battery is below the cutoff voltage, we need to start charging
        set_charge_mode();
    } else {
        // we can discharge if above cutoff voltage
        set_discharge_mode();
    }
}

void loop() {
    if (cycles >= 500) {
        Serial.println("Refusing to do anything, number of cycles too high");
        set_charge_mode(); // to disconnect from load or something
        return;
    }

    float vbat = get_batt_voltage();
    Serial.println("Battery voltage: " + String(vbat) + " is charging: " + String(in_charge_mode));
    if (in_charge_mode) {
        if (vbat > 4.2f) {
            // we're done charging! increase cycle counter
            cycles++; // technically, this is the number of "charge ups complete"
            Serial.println("BATTERY CHARGED SUFFICIENTLY. Discharging again.");
            set_discharge_mode();
        } else {
            Serial.println("Still charging up the battery, waiting..");
        }
    } else {
        // in discharge mode
        if (vbat < cutoffvoltage) {
            // battery has sunk below our cutoff voltage, we need to charge up again
            Serial.println("BATTERY DISCHARGED. Charging up again.");
            set_charge_mode();
        } else {
            Serial.println("Still dicharging the battery, waiting..");
        }
    }
    delay(1000); // check again in one second
}

however the serial monitor keeps repeating this:
Battery voltage: 4.18 is charging: 0
Still dicharging the battery, waiting..
Battery voltage: 4.18 is charging: 0
Still dicharging the battery, waiting..
Battery voltage: 4.18 is charging: 0

It seems to trying to discharge it but keeps charging the battery? I've waited for about an hour and the voltage keeps staying at 4.18V and sometimes shows 4.17V but then goes back to showing 4.18V.
What could be going wrong? Thanks
EDIT: here is a picture of my circuit

Let us continue this discussion in chat.

hi jsotola i have attached the revised circuit in the chatroom, would you kindly take a look at it? Thanks

I have formatted your source, it was hardly readable. Please adopt a code style and stick to it.

hi i think you might've accidentally deleted the void loop from the code

No, I did not. Please use the scroll bar to view the other parts, the source view is height limited.

It probably has nothing to do with your code but the characteristics of your battery. What kind of battery you are using? Does your battery has the built-in over-charge and under-voltage protection circuit? What kind of charge you are using (does it has the protection for over-charge?). The battery may cut off at approximitely 4.2v but not quite 4.2v based on the over-charge protection threshold, and for the battery with under-voltage protection, depend on the IC, the cut-off might be at 2.3v instead of the 2.0v you are trying to do...

I do not think it is connected to the battery characteristics as you say because I tested it with a commercial battery charger that charges and discharges the battery to the same voltage numbers and it was able to do that fine.

From what you described, it further proof that your code work as it is supposed to do. isn't it? So you are using a "non-commercial" charger in this test, maybe you should look into this charger instead.

Hi I can't use the commercial charger because it only does it for a fixed number of cycles. I need it to go through 30 cycles which I why I am building this machine.


text:
Arduino Digispark ATtiny85 conditional logic not working
Expected Behavior:
I am attempting to use && or nested if statements to achieve the effect of two switches being required to close prior to an LED light (i.e., flip both switches), the LED turns on for 1 second, and then turns off.
Encountered Behavior:
It appears that no matter how I write the statement, if the SECOND if is true, the LED lights up.
Additional information:
The switches connect directly to ground when closed.
I have tried multiple conditional statements:

using &&: if (switch1 == LOW && switch2 == LOW) {LED code}
Nested if: if (switch1 == LOW) { if (switch2 == LOW) {LED code} }

I have tried multiple variable declarations:

int switch1 = 0; int switch2 = 1; (using integer representation of digispark pinout)
#define switch1 PB1

#define switch1 PB1
#define switch2 PB0

void setup()
{
  pinMode(2, OUTPUT);
  pinMode(switch1, INPUT_PULLUP);
  pinMode(switch2, INPUT_PULLUP);
}

void loop() {
  if (!digitalRead(switch1)) {
    if (!digitalRead(switch2)) {
      digitalWrite(2, HIGH);
      // turn the LED on (HIGH is the voltage level)
      delay(1000); // wait for a second
      digitalWrite(2, LOW);
    }
  }

  else {
    digitalWrite(2, LOW);
    delay(1);
  }
}

My Digispark Attiny85 is attached to a breadboard, where it receives power through the 5V and ground pins on the Digispark board. PB0 and PB1 connect directly to ground when closed, otherwise I count on the pull-up resistors. PB2 is connected to an LED -> resistor -> ground. All components share the same 5V power supply and ground.

what happens if you change the second if statement to  if (false){?

@jsotola Nothing happens now when I connect to ground PB0, PB1, or both

@jsotola. One last issue. It is the SECOND if , that if true, turns LED on. That is, the first if is irrelevant for some reason and I cannot figure out why this is the case

make the first if (false) ... what happens then?

@jsotola, I think I answered below. Can you verify my reasoning?

I am confident I solved the problem and think I know why it occurs.
PB1 on the digispark Attiny85 has a built in LED. This LED is still active when I run my code. The LED is dim, but consuming power. My hypothesis is that is is consuming enough current to drive that pin low when digital_read is called on PB1. Therefore, PB1 always evaluates to true, because of the internal LED (despite the fact that input_pullup should drive it false by default).
Here is how I tested this hypothesis:

If I plug PB1 into 5v+, the internal LED gets brighter, and my project LED never lights up. i.e., my first if is now !true, so the conditional fails to execute.
If I recode to exclude PB1 and instead map to PB3, my code runs as intended.

All of this is to say, I think that even when you specify PB1 as input_pullup, it does not behave as expected because of the internal LED.
@jsotola, thank you for your kindness and patience. What do you think?

makes sense ... remove the external LED and use the internal LED instead ... use PB0 and PB2 for the switches

Good debugging effort. In the future, you can also just spam a bunch of Serial.print() in there to monitor if your switches work

@towe I am not sure I can do that with digispark, but I am new to this and will  let you know what I find out

You would appear to have the incorrect physical pins connected to the switches:

Pins 0 and 1 connect directly to ground when closed, otherwise I count on the pull-up resistors.

However:

PB0 is physical pin 5
PB1 is physical pin 6

I apologize for the sloppy language. The digispark has the pins labeled and what I meant to say is that I connected to the pins labeled PB0 and PB1 on the digispark. So, I have the pins labeled PB0 and PB1 on the digispark connected to ground when closed

@jmarywien please update your question with this new information

@jsotola. Thanks updated language and added schematic


text:
Noob here.. Need help with a thermostat controlled relay
So After trying several sketches for a LM35 and none working I finally found one that was giving me accurate results. The problem is the code is way over my head. I was able to modify it enough to get the serial and temperature to a LCD but I cant figure out why its not tripping the relay after set values. The sketch completely ignores the temperature value therefor will never set the relay HIGH. What am I missing?
/*
 LM35 thermometer, no floats, no delays

  http://www.ti.com/lit/gpn/lm35
*/
const int relay = 0;
const byte sampleBin = 8, // number of samples for smoothing
           aInPin = A5;
const int fudge = 170; // adjust for calibration
const int kAref = 1090, // analog ref voltage * 1000
          kSampleBin = sampleBin * 1000,
          tEnd = 5000; // update time in mS
int tempC,
    tempF;
uint32_t total,  // sum of samples
         tStart; // timer start
int sensorPin = 5;// The analog pin the LM35's Vout is connected to.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

/*
Initialize serial connection with the computer*/
void setup()
{
  pinMode(relay, OUTPUT);
  Serial.begin(9600);
  lcd.begin(16,2);
  analogReference(INTERNAL); // use 1.1V internal ref
  analogRead(aInPin);
  for (int i = 0; i < sampleBin; i++) // for smoothing, fill total
    total += analogRead(aInPin);   // with sampleBin * current
                                   // reading
}

void loop()
{
  if (millis() - tStart > tEnd)
  {
    tStart = millis(); // reset timer
    total -= (total / sampleBin); // make room for new reading
    total += analogRead(aInPin); // add new reading
    tempC = total * kAref / (kSampleBin + fudge);
    tempF = (tempC * 18 + 3200) / 10;
    Serial.print("Temperature- ");
    prntTemp(tempF);
    Serial.println();
  }
}

void prntTemp(int temp)
{
  Serial.print(temp / 10); // whole degrees
  Serial.print(".");
  Serial.print(temp % 10); // tenths
  Serial.print("\t");

  // display Temperature on LCD
  lcd.setCursor(0,0);
  lcd.print("Temperature-");
  lcd.setCursor(0,1);
  lcd.print(tempF);
  lcd.println(" degrees F ");
  delay(10);// print data every 10milliseconds

  if (tempF >= 78.0)
  {
    digitalWrite(relay, HIGH);
  }
}

Does the LCD show the expected temperature? -- Are you sure that your relay is connected to Pin 0? Did you check this with another simple sketch? -- tStart is initialized with 0, do you want this?

Not related to your problem: The delay(10); in prntTemp() is not necessary, because the latter is called only every 5 seconds. -- Not related to your problem that relay is not set HIGH, but will be a problem if that will work: You need an else branch that resets the relay to LOW. -- And, again not related to your problem: You don't need to access tempF in prntTemp() as it is provided as the argument in parameter temp.

Please show us the serial output


text:
Arduino with NRF24L01. Getting correct data from unkown transmitter
I want to use my Arduino with this: VAC8010F measure unit. It communicates with NRF24L01. The problem is I simply don't know which band or information it is receiving. Can somebody help me with this?
Thanks for any suggestions!

What does your favorite search engine reveal? What did the data sheets and documentation tell you? What is it what you do not understand in their contents? -- Please take the [tour] and read "[ask]". Then show some effort and come back to [edit] your question.

You need to know the channel and the pipe-id (and speed, though my guess would be 1Mbps). To find the channel https://github.com/nRF24/RF24/blob/master/examples/scanner/scanner.ino might help. Not sure how to find the pipe-id.

One possibility is sniffing the SPI bus and seeing how the module is configured. Another is using an SDR and decoding the communication on-air. Third method is dumping the unit's firmware and reverse-engineering it. Any other methods are probably too slow, I'm not aware of a promiscuous mode on the nRF24L01+ and checking all speeds, channels and pipes is way too slow.

Sniffing the SPI bus is probably the easiest, you could possibly even attach your own wires to the bus and possibly read out all the registers.

Don't have full details yet. But the VAC8010F uses modbus RS485 protocol.
My research shows that the NRF24 just transmitts and receives the MODBUS protocol to and from master/slave. I have found modbus libs and samples of code on the net. There is a command driven program to communicate with MODBUS free for linux, which is the o/s I use. I don't know about win. Anyway, once I receive the MAX485TTL interface for my ARDUINO MEGA I will write code for data  logging to p.c. then modify to use the NRF24, as I should be able to extract the ADDRESS, and CHANNELS etc, and packet construct.
Hope this is of some help.
Patrick

Nordic has an app to connect to nRF
https://www.instructables.com/Send-Data-to-Mobile-Using-NRF24L01-Using-NRF-As-a-/
The app is available for all platforms.
Did not try it myself. Hope this helps.
I going to do the same, but want receive it on Android.
If you got some news, please let me know.
Thanks

Have got a cheap Logic Analyzer to use with Saleae Software. Many protocols can be choosen including modbus. @Patrick: Do you know the baudrate? is it RTU/ASCII? Who is Master/Slave?


text:
How does code typed in Arduino IDE runs on a nodemcu?
I actually have a series of questions regarding Nodemcu and esp8266.

How does code typed in Arduino IDE run on Nodemcu?
What firmware is present on the nodemcu?
How do I upload the above firmware on esp8266-01 module?
I want my esp8266-01 module to work with a Lilypad Arduino. So this is the way I want it to work: Lilypad Ardiuno has acquires some data using a sensor. It wants to post this data to a server on internet. So to do the job it uses a ESP8266-01. Will the configuration work?

NodeMCU name has a development board and a firmware. both can be used independently. maybe you have the NodeMcu firmware on the NodeMcu board. NodeMcu firmware with the Lua language will not work with Arduino IDE.

how does code typed in Arduino IDE runs on Nodemcu

The IDE runs the compiler which turns the C into assembly and then machine code.  That is then uploaded to the ESP8266.

what firmware is present on the nodemcu.

The code that you just wrote and uploaded.

i want my esp8266-01 module to work with a Lilypad Arduino .So this is the way I want it to work Lilypad Ardiuno has acquires some data using a sensor it wants the post this data to a server on internet.So to do the job it uses a ESP8266-01.So will the configuration work?

Sure, if you program it to do that.  Two choices:

Use the AT firmware on the ESP-01 (installed by default)
Write custom firmware (as above) for the ESP-01 to do what you want.

Thankyou so much @Majenko , it would be very kind of you if you point me to some references for question no. three.thankyou once again .it was very helpful

Google: Arduino ESP8266 AT and you'll find your answers.


text:
Can I change the text on the LCD by rotating the potentiometer?
I am working on a project on my Arduino Uno in which I want to change the text on the LCD every time the potentiometer has been rotated. In order to do this, I have stored the angle values into an int, constantly check if the angle has been rotated enough to change the text, and if it has, print the next message. I am not sure if either my code or circuit is wrong as nothing happens at all when i rotate the potentiometer.
Here is my code so far and an image of the circuit (the innermost potentiometer is for the brightness, the one on the right is for changing the text on the LCD. I think I may have wired the second potentiometer incorrectly but I am not sure how to fix this).

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // removed 3
// set up a constant for the button
const int buttonPin = 6;
// variable to hold the value of the button
int buttonState = 0;
// variable to hold previous value of the button
//int prevbuttonState = 0;
// a variable to choose which reply will be displayed
int reply = -1;
int prevReply = -1;
int potPin = A0;
int potVal = 0;
int angle = 0;
int prevAngle = 0;
//int startTime = 0;
//int timeElasped = 0;
//int workoutTime = 0;

void setup() {
  // set up the number of columns and rows on the LCD
  lcd.begin(16, 2);

  // set up the switch pin as an input
  pinMode(buttonPin, INPUT);

  Serial.begin(9600);
  prevAngle = map(potVal,0,1023,0,300); // set prevAngle to original angle. later, code that if the angle isnt 0 tell user to reset it
  // Print a message to the LCD.
  lcd.print("Pick a");
  // set the cursor to column 0, line 1
  // line 1 is the second row, since counting begins with 0
  lcd.setCursor(0, 1);
  // print to the second line
  lcd.print("Muscle Group!");
}

void loop() {
  // check the status of the switch
  buttonState = digitalRead(buttonPin);
  potVal = analogRead(potPin);
  Serial.print("potVal: ");
  Serial.print(potVal);
  angle=map(potVal,0,1023,0,300);//used to be 179, changed to 300 assuming it equals the max angle available in the potentiometer
  Serial.print(", angle: ");
  Serial.println(angle);
  if (angle > prevAngle+69){ // if the pot has been rotated enough clockwise, display next group
    if (reply!=3)
      reply = reply+1;//provide next muscle group
    else
      reply = 0;//return to first muscle group
    /*if (prevReply==-1)
      prevReply=reply;*/
  }
  else if (angle < prevAngle-69){ // if the pot has been rotated enough counterclockwise, display prev group
    if (reply!=0 && reply!=-1)
      reply = reply-1;//provide previous muscle group
    else if (reply==0)// check if reply is still equal to -1 btw
      reply = 3;//return to last muscle group
    else if (reply==-1){
      reply = 0;
      //prevReply=reply;
    }
  }
  //prevReply = reply;
  if (buttonState == HIGH) { //if the button has been pressed, display new random exercise within muscle group that was chosen
      if (reply == 0)
        reply = random(4,6);
      if (reply == 1)
        reply = random(7,9);
      if (reply == 2)
        reply = random(10,12);
      if (reply == 3)
        reply = random(13,15);
      // clean up the screen before printing a new reply
      lcd.clear();
      // set the cursor to column 0, line 0
      lcd.setCursor(0, 0);
      // print some text
      lcd.print("Time to do some");
      // move the cursor to the second line
      lcd.setCursor(0, 1);
      delay(500);
      lcd.clear();
      lcd.setCursor(0, 0);
      /*if (workoutTime - millis() + startTime==0){
           lcd.clear();
           lcd.setCursor(0, 0);
           lcd.print("You did it!! :]"); //if reply keeps looping, stop loop once timer=0. if reply never loops, figure out how to make it loop for the timer*/
      }
      //if (prevReply != reply) // if we have chosen a new workout, change the starting time
        //startTime = millis(); // record millis() function to see how much time passes btwn start of program to start of timer
      if (prevReply != reply){
      switch (reply) { // choose a saying to print based on the value in reply
        case 0:
          lcd.print("Arms");
          break;

        case 1:
          lcd.print("Core");
          break;

        case 2:
          lcd.print("Chest");
          break;

        case 3:
          lcd.print("Legs");
          break;

        case 4:
          //workoutTime = 2400;
          lcd.print("Arm wrkt 1; " /*+ workoutTime - millis() + startTime*/); // temporary workout names, to be replaced in a later draft
          break;

        case 5:
          //workoutTime = 1200;
          lcd.print("Arm wrkt 2; " /*+ workoutTime - millis() + startTime*/);
          break;

        case 6:
          //workoutTime = 1500;
          lcd.print("Arm wrkt 3; " /*+ workoutTime - millis() + startTime*/);
          break;

        case 7:
          //workoutTime = 1800;
          lcd.print("Core wrkt 1; " /*+ workoutTime - millis() + startTime*/);
          break;

        case 8:
          //workoutTime = 900;
          lcd.print("Core wrkt 2; " /*+ workoutTime - millis() + startTime*/);
          break;

        case 9:
          //workoutTime = 2400;
          lcd.print("Core wrkt 3; " /*+ workoutTime - millis() + startTime*/);
          break;

        case 10:
          //workoutTime = 2100;
          lcd.print("Chest wrkt1; " /* + workoutTime - millis() + startTime*/);
          break;

        case 11:
          //workoutTime = 1200;
          lcd.print("Chest wrkt2; " /* + workoutTime - millis() + startTime*/);
          break;

        case 12:
          //workoutTime = 1200;
          lcd.print("Chest wrkt3; " /* + workoutTime - millis() + startTime*/);
          break;

        case 13:
          //workoutTime = 1500;
          lcd.print("Leg wrkt 1; " /* + workoutTime - millis() + startTime*/);
          break;

        case 14:
          //workoutTime = 2400;
          lcd.print("Leg wrkt 2; " /* + workoutTime - millis() + startTime*/);
          break;

        case 15:
          //workoutTime = 1800;
          lcd.print("Leg wrkt 3; " /*+ workoutTime - millis() + startTime*/);
          break;
        prevReply=reply;
      }
  }
  prevAngle=angle;
}

get rid of all of your code ... write simple code that reads the value of the potentiometer and prints it to serial console ... when that works as expected, then go back to your code

Please include the image of your circuit directly into your question.

You print the analog value and the resulting angle to Serial. Do they show up in the Serial Monitor as expected?

Here is a (heavily) stripped-down version of your code:
void loop() {
    potVal = analogRead(potPin);
    angle = map(potVal, 0, 1023, 0, 300);
    if (angle > prevAngle + 69) {
        // stuff...
    } else if (angle < prevAngle - 69) {
        // stuff...
    }
    // lots of more stuff...
    prevAngle = angle;
}

Imagine this executing a few thousand times a second. Each time, it
computes the angle of the potentiometer's knob, then copies the computed
angle into prevAngle. Unless you turn the pot really fast, the angle
is unlikely to change by more than 69° in that fraction of a
millisecond.
I suggest not updating prevAngle on every iteration. Instead, let
angle slowly drift away from prevAngle through many iterations of
the loop. When the two are more than 69° apart, then you take the action
you wanted to take, and only then you update prevAngle.


text:
Visual Studio Code - intellisense issue
Just started with Arduino Community Edition for Visual Studio code. I can select the com-port, Arduino model, build and upload the code  all is working fine.
I have a intellisense problem I am not able to solve. I got errors for all my includes, e.g. my main program "LedMaster.ino"
cannot open source file "WS2812FX.h" (dependency of "LEDController.h").
I've added the full path to WS2812FX.h in my projects "c_cpp_properties.json":
"forcedInclude": [
    "C:\Users\wbk\Documents\Arduino\libraries\WS2812FX\src\WS2812FX.h"
],

This did not solve the issue. It seems that intellisense is not able to build the correct include path.
The next time I start Visual Studio Code my workspace's "c_cpp_properties.json" is rebuild and the forcedInclude added manually for "WS2812FX.h" is deleted.
How do I set up Visual Studio Code correctly?