text:
My DS18B20 is reading high. How can I get it to return the correct temperature?
I am working on a heating control system for my home, but having problems with the temperature sensor reading higher than I expect.
I have a 5V Arduino Mini Pro clone hooked up to a relay module, an HD47780 display and a Tiny RTC module, with a DS18B20 attached to it.
The DS18B20 is powered from the 5v Vcc applied to the Tiny RTC module rather than using parasitic power on the DQ line (as I wasn't sure if the Onewire libraries supported this mode of operation) and the DS18B20 datasheet says that Vcc may be between 3.0v and 5.5v. I measured the regulated power from the Mini Pro's  being at 5.2v.
I am comparing the temperature from the DS with the existing room thermostat (bi-metallic), an RS desktop temperature monitor with two sensors, a small 'thermo-hygrometer' and a bi-metallic fridge thermometer (in the upper quarter of its temperature range)†. The readout from the DS is always around 1-2 degrees higher than the readout from the other sensors, which are within a degree of each other.
† Not the actual one, but something similar.
Reading various forums I have heard that these sensors are quite accurate but can suffer from localised heating from components near them, so I moved the sensor onto a 20cm cable and positioned it well away from the rest of the electronics. This made no difference.
I then read that the DS can become self heating if it is supplied with too high a Vcc voltage, so I added a Red LED with 1.7v drop and measured the new voltage over the DS as 3.5v, but again, after waiting for the temperatures to stabilise once more, this made no difference.
Can anyone suggest why the DS may be reading high and what I can can do to prevent this?

How confident are you that your room thermostat isn't just reading 1-2 degrees low? You should get a third thermometer, and compare to determine where your offset is actually coming from. Since the RS thermometer likely uses the same readout electronics for both sensors, it's probably not really useful as two distinct calibration references.

I've put a lot of DS18B20 sensors in place now on various sensor nodes - maybe 50 or so. I've learnt a bit about the readings returned from them. I know you have isolated some of these as not being the cause, but it is good to confirm that they are issues.
I don't know if you are using Celsius or Fahrenheit, so the degree of the problem isn't clear.
Localised heating
I don't think of Arduino as a "hot" chip, but putting a DS18B20 in an enclosure with an Arduino and LCD caused me to see readings 2-3°C higher than expected.
Moving it outside the enclosure fixed this.
Heating from high Vcc/frequent conversions
If you supply the chip with a high Vcc and perform frequent conversions (i.e. as frequently as you can), the chip does warm up. I have seen this increase readings by 1-2°C.
I haven't seen the problem with high Vcc alone, but I operate most DS18B20 in parasitic mode and convert at most once every 10s. The ones operated in active mode generally have the powered turned off when not being used.
OneWire and DallasTemperature do support parasitic mode.
Not all temperature sensors are created equal
I had a number of temperature sensors before I started playing around with DS18B20. Almost without exception, these under-read. Most of them are based on thermistors and calibration is poor. I thought the DS18B20 were over reading, but when I used a good thermocouple and meter, I could validate that they were correct.
This was about learning to trust the DS18B20.
Heat conducted along wire
If you have the sensors on a wire, the wire conducts a surprising amount of heat. This can be an issue when running wiring along pipes.
Fake DS18B20
These sensors are very popular, and this seems to have caused fakes to appear. I have a batch of stainless steel waterproof sensors that over-read and the timings were out. They worked with the OneWire library, but not a DS2482 OneWire master. I have heard of the normal TO-92 cased ones being fake as well.

In the great wisdom of the board software, I'm not allowed to answer this question, so I'll add a comment here. As I found out the hard way on https://github.com/PaulStoffregen/OneWire/issues/91 , if you use a 3.3V chip, you need to replace the 4.7k resistor with a 2.7k resistor, or some sensors will return incorrect values.

In my case, the wiring between my uC and the sensor was too short, and was transmitting some heat. I thought that couldn't be the case at first, since another temp sensor was reporting accurate temps at the same distance. I moved it to another location on the board and voila!

Perhaps you might want to calibrate your sensor.
What does it read when immersed in boiling water (assuming sea level) ? 102.5 Celsius?  That would give you a high-temperature calibration of -2.5C.
Obviously it's better to calibrate around the temperatures you expect to me measuring.  That means trusting (or averaging?) some measuring device and calibrating to that.

I have seen offsets of several degrees C when using DS18B20 on a 3.3V bus, switching to a stable 5.0V bus and I got more reasonable values. (tested with and without parasitic power)

That's interesting, thanks, and the opposite of what some people have been reporting. I wonder if this is another fake DS18B20 issue.

I've made some experiments.
If DS18B20 was on short cable <1cm to my Arduino Pro Micro the readings was 5 degrees more than environment was. On cable lenght >10cm from arduino board and no matter where the resistor was mounted (near arduino or near DS18B20) the readings was fine.

After reading your answer, I tried moving the sensor away and my readings dropped 5 degrees to a more accurate value. Do you have any idea why? I don't think the heat of the circuit caused the difference.


text:
Unable to correctly read CSC GATT data with ArduinoBLE on a Arduino Nano 33 IOT
I've set up a Nano 33 IOT as a central device and I'm attempting to read the data from a Cycling speed and cadence BLE device.
The spec for the CSC Gatt service I want is: https://www.bluetooth.com/wp-content/uploads/Sitecore-Media-Library/Gatt/Xml/Services/org.bluetooth.service.cycling_speed_and_cadence.xml
And the characteristic:
https://www.bluetooth.com/wp-content/uploads/Sitecore-Media-Library/Gatt/Xml/Characteristics/org.bluetooth.characteristic.csc_measurement.xml
I've tried a few different approaches, this one seems like it should get me the closest. I'm afraid I'm feeling around in the dark and hope someone can give me a definitive answer of how to read these values because I'm not even sure what they SHOULD look like even if I do somehow manage to read them correctly!
I initially tried using this code to read the values, which seemed to get me reasonably close, but seeing as there are different data types and I could just as easily read 32 values, I don't believe it to be correct.
uint16_t cscValues[16];
cscCharacteristic.readValue(cscValues, 16);

for(int i = 0; i < 16; i++){
    Serial.print(i);
    Serial.print(":");
    Serial.print(cscValues[i]);
    Serial.print(" ");
}
Serial.println("");

this gives the output:
//not moving:
10:50:49.401 -> 0:21249 1:0 2:11008 3:8314 4:556 5:8192 6:25637 7:0 8:0 9:0 10:704 11:8192 12:568 13:8192 14:22485 15:0
10:50:50.409 -> 0:21249 1:0 2:11008 3:8314 4:556 5:8192 6:25637 7:0 8:0 9:0 10:704 11:8192 12:568 13:8192 14:22485 15:0

//moving:
10:51:07.518 -> 0:24577 1:0 2:8448 3:8338 4:556 5:8192 6:25637 7:0 8:0 9:0 10:704 11:8192 12:568 13:8192 14:22485 15:0
10:51:08.513 -> 0:25345 1:0 2:36864 3:8342 4:556 5:8192 6:25637 7:0 8:0 9:0 10:704 11:8192 12:568 13:8192 14:22485 15:0
10:51:09.490 -> 0:26113 1:0 2:6144 3:8347 4:556 5:8192 6:25637 7:0 8:0 9:0 10:704 11:8192 12:568 13:8192 14:22485 15:0

The method I'm currently using is based off of a Arduino forum post I found: https://forum.arduino.cc/index.php?topic=711228.0
My full sketch:
#include <ArduinoBLE.h>

#define CSC_DATA_SIZE 16

typedef struct __attribute__( ( packed ) )
{
  int32_t cum_wheel_rev;
  int16_t last_wheel_event;
  int16_t cum_cranks;
  int16_t last_crank_event;
} csc_data_t;

typedef union
{
  csc_data_t values;
  uint8_t bytes[ CSC_DATA_SIZE ];
} csc_data_ut;

csc_data_ut cscData;

void setup() {

  Serial.begin(9600);

  //wait until the serial port is connected for debugging
  while (!Serial);

  // begin initialization
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");

    while (1);
  }

  Serial.println("BLE Central scan");

  // start scanning for peripheral
  BLE.scanForUuid("1816"); // Cycle speed and cadence UUID
}

void loop() {
  //Read BLE devices

  // check if a peripheral has been discovered
  BLEDevice peripheral = BLE.available();

  if (peripheral) {
    // discovered a peripheral
    Serial.println("Discovered a peripheral");
    Serial.println("-----------------------");

    // print address
    Serial.print("Address: ");
    Serial.println(peripheral.address());

    // print the local name, if present
    if (peripheral.hasLocalName()) {
      Serial.print("Local Name: ");
      Serial.println(peripheral.localName());
    }

    // print the advertised service UUIDs, if present
    if (peripheral.hasAdvertisedServiceUuid()) {
      Serial.print("Service UUIDs: ");
      for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
        Serial.print(peripheral.advertisedServiceUuid(i));
        Serial.print(" ");
      }
      Serial.println();
    }

    // print the RSSI
    Serial.print("RSSI: ");
    Serial.println(peripheral.rssi());

    Serial.println();

    // stop scanning
    BLE.stopScan();

    getSpeed(peripheral);

    // peripheral disconnected, start scanning again
    BLE.scanForUuid("1816"); // Cycle speed and cadence UUID
  }
}

void getSpeed(BLEDevice peripheral) {
  // connect to the peripheral
  Serial.println("Connecting ...");

  if (peripheral.connect()) {
    Serial.println("Connected");
  } else {
    Serial.println("Failed to connect!");
    return;
  }

  // discover peripheral attributes
  Serial.println("Discovering attributes ...");
  if (peripheral.discoverAttributes()) {
    Serial.println("Attributes discovered");
  } else {
    Serial.println("Attribute discovery failed!");
    peripheral.disconnect();
    return;
  }

  // retrieve the LED characteristic
  BLECharacteristic cscCharacteristic = peripheral.characteristic("2A5B");

  if (!cscCharacteristic) {
    Serial.println("Peripheral does not have CSC characteristic!");
    peripheral.disconnect();
    return;
  }

  if (!cscCharacteristic.canSubscribe()) {
     Serial.println("canSubscribe False");

  } else {
  if(!cscCharacteristic.subscribe()) {

    Serial.println("subscription Failed");
    }else {
      Serial.println("subscribed!");
    }
  }

  int totalWheelRevolutions = 0;
  int wheelDiameter = 750; // in mm

  while (peripheral.connected()) {
    //happens every second.
    if (cscCharacteristic.valueUpdated()) {
      if (cscCharacteristic.valueLength() > 0) {
          cscCharacteristic.readValue(m5600Data.bytes, M5600_DATA_SIZE);

          Serial.print(" cum_wheel_rev: ");
          Serial.print(cscData.values.cum_wheel_rev);
          Serial.print(" last_wheel_event: ");
          Serial.print(cscData.values.last_wheel_event);
          Serial.print(" cum_cranks: ");
          Serial.print(cscData.values.cum_cranks);
          Serial.print(" last_crank_event: ");
          Serial.print(cscData.values.last_crank_event);
          Serial.println("");
      }
    }
  }

  Serial.println("Peripheral disconnected");
}

The output is:
10:42:15.427 -> BLE Central scan
10:42:16.193 -> Discovered a peripheral
10:42:16.193 -> -----------------------
10:42:16.193 -> Address: df:f4:55:1e:16:27
10:42:16.193 -> Local Name: XOSS S-021477
10:42:16.193 -> Service UUIDs: 1816
10:42:16.193 -> RSSI: -72
10:42:16.193 ->
10:42:16.193 -> Connecting ...
10:42:16.703 -> Connected
10:42:16.703 -> Discovering attributes ...
10:42:17.473 -> Attributes discovered
10:42:17.508 -> subscribed!
//moving:
10:42:18.524 ->  cum_wheel_rev: 11009 last_wheel_event: -32256 cum_cranks: 251 last_crank_event: 0
10:42:19.529 ->  cum_wheel_rev: 11265 last_wheel_event: -19968 cum_cranks: 7 last_crank_event: 0
10:42:20.511 ->  cum_wheel_rev: 11777 last_wheel_event: -10752 cum_cranks: 21 last_crank_event: 0
10:42:21.520 ->  cum_wheel_rev: 12033 last_wheel_event: -512 cum_cranks: 26 last_crank_event: 0
10:42:22.636 ->  cum_wheel_rev: 12545 last_wheel_event: -6912 cum_cranks: 31 last_crank_event: 0
10:42:23.764 ->  cum_wheel_rev: 13057 last_wheel_event: 4608 cum_cranks: 37 last_crank_event: 0
10:42:24.747 ->  cum_wheel_rev: 13313 last_wheel_event: -25600 cum_cranks: 39 last_crank_event: 0
10:42:25.615 ->  cum_wheel_rev: 13825 last_wheel_event: 2816 cum_cranks: 44 last_crank_event: 0
10:42:26.631 ->  cum_wheel_rev: 14337 last_wheel_event: -11264 cum_cranks: 48 last_crank_event: 0
10:42:27.610 ->  cum_wheel_rev: 14849 last_wheel_event: -17664 cum_cranks: 53 last_crank_event: 0
10:42:28.635 ->  cum_wheel_rev: 15361 last_wheel_event: -12288 cum_cranks: 57 last_crank_event: 0
10:42:29.616 ->  cum_wheel_rev: 15873 last_wheel_event: -18432 cum_cranks: 61 last_crank_event: 0
10:42:30.642 ->  cum_wheel_rev: 16385 last_wheel_event: -29696 cum_cranks: 65 last_crank_event: 0
10:42:31.619 ->  cum_wheel_rev: 16641 last_wheel_event: -21248 cum_cranks: 67 last_crank_event: 0
10:42:32.612 ->  cum_wheel_rev: 16897 last_wheel_event: 23040 cum_cranks: 70 last_crank_event: 0
10:42:33.642 ->  cum_wheel_rev: 17665 last_wheel_event: -7168 cum_cranks: 77 last_crank_event: 0
10:42:34.619 ->  cum_wheel_rev: 18177 last_wheel_event: 18944 cum_cranks: 81 last_crank_event: 0
10:42:35.637 ->  cum_wheel_rev: 18945 last_wheel_event: 11264 cum_cranks: 86 last_crank_event: 0
10:42:36.622 ->  cum_wheel_rev: 19457 last_wheel_event: -29440 cum_cranks: 89 last_crank_event: 0
10:42:37.616 ->  cum_wheel_rev: 19969 last_wheel_event: -5888 cum_cranks: 92 last_crank_event: 0

//not moving:
10:42:38.623 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:39.608 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:40.624 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:41.640 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:42.620 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:43.642 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:44.622 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0
10:42:45.638 ->  cum_wheel_rev: 20481 last_wheel_event: 20224 cum_cranks: 96 last_crank_event: 0

I'm well versed in programming, but new to Arduino. Any help would be extremely valuable!
Thank you!

So I've managed to realise I was missing the flags in my data. So by adding  'int8_t flags' to the attributes I got it to work. Kind of... I still need to adjust for when fields should be read or not. and I've got some idea's but I'm not sure of the best way to do that.
typedef struct __attribute__( ( packed ) )
{
  int8_t flags;
  int32_t cum_wheel_rev;
  int16_t last_wheel_event;
  int16_t cum_cranks;
  int16_t last_crank_event;
} csc_data_t;

source: Stack Exchange

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

sort: votes


text:
nRF24L01+ problem with receiving response
I'm sending currently data from a Raspberry to an Arduino, but I have a problem with receiving response from the Arduino back to the Raspberry:

Sent the message: ['H', 'i', '.', '.', 'A', 'r', 'd', 'u', 'i', 'n', 'o', ' ', 'U', 'N', 'O', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Timed out.

Currently message received is in "got_time", so I see numerical value. When I change it to string I see "Hi..Arduino UNO" response. Problem is with timeout on the Raspberry. Raspberry sends message, Arduino receives it, Arduino should send confirmation of receipt of the message, Raspberry shows timeout of it.
Can you guide me to the solution?
Arduino Nano code:
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*/

#include <SPI.h>
#include "RF24.h"
#include "printf.h"

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 1;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(9,10);
/**********************************************************/

const uint64_t addresses[2] = { 0xE1E2E3E4E5LL, 0xE6E7E8E9E0LL };
// byte addresses[][6] = {"1Node","2Node"};

// Used to control whether this node is sending or receiving
bool role = 0;

void setup() {
  Serial.begin(115200);
  printf_begin();
  Serial.println(F("RF24/examples/GettingStarted"));
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

  radio.begin();

  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW);

  // radio.setRetries(15,15);
  radio.setPayloadSize(32);
  radio.setChannel(0x76);
  // radio.setPALevel(RF24_PA_MIN);
  // radio.setAutoAck(true);

  // Open a writing and reading pipe on each radio, with opposite addresses
  if (radioNumber) {
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  } else {
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }

  // Start the radio listening for data
  radio.startListening();
  radio.printDetails();
}

void loop() {

/****************** Ping Out Role ***************************/
  if (role == 1)  { /* Not used in this case */ }
/****************** Pong Back Role ***************************/

  if (role == 0) {
    unsigned long got_time;

    if(radio.available()) {
                                                                    // Variable for the received timestamp
      while (radio.available()) {                                   // While there is data ready
        radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
      }

      radio.stopListening();                                        // First, stop listening so we can talk
      radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.
      radio.startListening();                                       // Now, resume listening so we catch the next packets.
      Serial.print(F("Sent response "));
      Serial.println(got_time);
    }
  }

/****************** Change Roles via Serial Commands ***************************/
/* Not used in this case */
} // Loop

Raspberry Pi 0 code:
import RPi.GPIO as GPIO  # import gpio
import time      #import time library
import spidev
from lib_nrf24 import NRF24   #import NRF24 library

GPIO.setmode(GPIO.BCM) # set the gpio mode

# set the pipe address. this address shoeld be entered on the receiver alo
pipes = [[0xE1, 0xE2, 0xE3, 0xE4, 0xE5], [0xE6, 0xE7, 0xE8, 0xE9, 0xE0]]
radio = NRF24(GPIO, spidev.SpiDev())   # use the gpio pins
radio.begin(0, 25)   # start the radio and set the ce,csn pin ce= GPIO08, csn= GPIO25
radio.setPayloadSize(32)  #set the payload size as 32 bytes
radio.setChannel(0x76) # set the channel as 76 hex
radio.setDataRate(NRF24.BR_1MBPS)    # set radio data rate
radio.setPALevel(NRF24.PA_MIN)  # set PA level

radio.setAutoAck(True)       # set acknowledgement as true
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[0])     # open the defined pipe for writing
radio.openReadingPipe(1,pipes[1])     # open the defined pipe for writing

radio.printDetails()      # print basic detals of radio
time.sleep(3)

sendMessage = list("Hi..Arduino UNO")  #the message to be sent
while len(sendMessage) < 32:
  sendMessage.append(0)
try:
  while True:
    start = time.time()      #start the time for checking delivery time
    radio.write(sendMessage)   # just write the message to radio
    print("Sent the message: {}".format(sendMessage))  # print a message after succesfull send
    radio.startListening()        # Start listening the radio

    while not radio.available(0):
      time.sleep(1/100)
      if time.time() - start > 2:
        print("Timed out.")  # print errror message if radio disconnected or not functioning anymore
        break

    radio.stopListening()     # close radio
    time.sleep(3)  # give delay of 3 seconds
finally:
  GPIO.cleanup() # this ensures a clean exit

Arduino console:

RF24/examples/GettingStarted
*** PRESS 'T' to begin transmitting to the other node
SPI Speedz   = 10 Mhz
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe6e7e8e9e0 0xe1e2e3e4e5
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe6e7e8e9e0
RX_PW_P0-6   = 0x10 0x10 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x02
RF_CH        = 0x76
RF_SETUP     = 0x03
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_LOW
ARC      = 5
Sent response Hi..Arduino UNO
Sent response Hi..Arduino UNO
Sent response Hi..Arduino UNO
Sent response Hi..Arduino UNO

Raspberry Pi 0 console:

STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     =
 0xe1e2e3e4e5 0xe6e7e8e9e0
RX_ADDR_P2-5     =
0xc3
0xc4
0xc5
0xc6

TX_ADDR      =
 0xe1e2e3e4e5
RX_PW_P0-6   =
0x10
0x10
0x00
0x00
0x00
0x00

EN_AA        =
0x3f

EN_RXADDR    =
0x03

RF_CH        =
0x76

RF_SETUP     =
0x01

CONFIG       =
0x0f

DYNPD/FEATURE    =
0x3f
0x06

Data Rate    = 1MBPS
Model        = nRF24l01+
CRC Length   = 16 bits
PA Power     = PA_MIN
Timed out.
Timed out.
Timed out.

Writing to a console takes a very llng time. Perhaps the Arduino has already responded before the raspi starts listening. Try stat listening before you write out the message. Also, your Arduino code reads the whole message in a single unsigned  long variable, i.e. every new send character overwrites the last one. Then it sends only the last received charackter (a 0) back to the raspi. Is that what you want?

When I commented out print("Sent the message notthing changed (still "Timed out."). All I want to stable communication and sending messages at start Rpi to Arduino. Finally 2 way.

Next try: Perhaps the arduino still responds too fast. Use a delay before the write command. delay(5); radio.write(... in the arduino code.  Of cause, it is possible that there is a hardware problem. But why should it work in one direction but fail in the other? I think the problem is that you stop listening in order to send the message and the arduino responses before the Raspi starts listening again. A stable communication is only possible if you use a communication method with a connection management like bluetooth.

I added delay before radio.write from 5 up to 1000. Still timeout.

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


text:
Servomotor and Bluetooth module block each other
For a small project, I aim to connect a digital temperature sensor (KY-028), a Bluetooth module (HC-05) and a servomotor (SG90). The problem is it seems I can't connect the Bluetooth module and the servomotor together at the same time. The Bluetooth module together with the temperature sensor works fine. The servo with the sensor, again, all fine. But it seems these two don't agree with each other: as soon as I upload the code on the board (Arduino UNO), the servo starts vibrating (not even rotating), altough I made sure no command that asks it to do so is reached. Also while doing this, the Bluetooth module's led is turned off and it is unrecognizable by other devices.
When I upload the program to the board, I disconnect the RX and TX pins of the Bluetooth module from the pins 0 & 1 of the Arduino board, (otherwise I get errors and the program is not uploaded - if needed, I will get the error codes I get and edit the post), but after upload, the servo starts behaving weird, as described before. As I read on another article (if I manage to find the link again I will post it here), it might behave like this because there are unconnected pins in my whole circuit (which is true, but otherwise I can't connect the Bluetooth module). How could I possibly connect both of them on the same board?
I tested the code segments, they act as they should, I tried switching the pins so that I did not miss anything by mistake, as I am a total beginner (for instance I tried putting the signal wire of the servo on both PWM and not PWM supporting pins, tried connecting the Bluetooth module and the servo to different grounds etc.) but no success.
Any help would be much appreciated. If the layout of my circuit is needed, I will try to make one in a simulator. Thank you very much!
Edit
Here is the code:
#include <Servo.h>
#include <SoftwareSerial.h>

int txPin = 1;
int rxPin = 0;
int digitalPin = 7; // KY-028 digital interface
int analogPin = A2; // KY-028 analog interface
int angle = 0;
int temp;
bool incTemp = false, decTemp = false;

Servo servo;
SoftwareSerial BT(txPin,rxPin);

void setup() {
  pinMode(digitalPin, INPUT);
  pinMode(analogPin, INPUT);

  servo.attach(11);
  delay(100);

  BT.begin(9600);
  Serial.begin(9600);
}

void loop() {
  temp = analogRead(analogPin);
  Serial.println(temp);

  if (BT.available())
  {
    char bytesToSend[2];
    bytesToSend[0] = 101;
    bytesToSend[1] = temp;
    bytesToSend[2] = 110;
    BT.println(bytesToSend);
  }

  if(incTemp)
  {
    servo.write(90);
    delay(100);
    servo.write(135);
    delay(100);
    servo.write(180);
    delay(100);
    servo.write(135);
    delay(100);
  }
  else if(decTemp)
  {
    servo.write(90);
    delay(100);
    servo.write(45);
    delay(100);
    servo.write(0);
    delay(100);
    servo.write(45);
    delay(100);
  }

  delay(2000);
}

For the incTemp and decTemp variables I will use an interrupt to detect when the Bluetooth paired device is sending a command to activate the servomotor. But for now, as it can be seen, the blocks that ask the servo to rotate cannot be reached. For the layout I will try to find a simulator that provides the components I use and I will come back with the design.
Later edit, after following Majenko's advice
Here is the currently working code. An answer with the full implementation will come when the project is complete.
#include <Servo.h>

int txPin = 1;
int rxPin = 0;
int digitalPin = 7; // KY-028 digital interface
int analogPin = A2; // KY-028 analog interface
int angle = 0;
int temp;
bool incTemp = false, decTemp = false;

Servo servo;

void setup() {
  pinMode(digitalPin, INPUT);
  pinMode(analogPin, INPUT);

  Serial.begin(9600);
}

void loop() {
  temp = analogRead(analogPin);
  Serial.print("T");
  Serial.print(temp);
  Serial.println();

  if(incTemp)
  {
    servo.attach(11);
    delay(100);

    servo.write(90);
    delay(100);
    servo.write(135);
    delay(100);
    servo.write(180);
    delay(100);
    servo.write(135);
    delay(100);

    servo.detach();
    delay(100);
  }
  else if(decTemp)
  {
    servo.attach(11);
    delay(100);

    servo.write(90);
    delay(100);
    servo.write(45);
    delay(100);
    servo.write(0);
    delay(100);
    servo.write(45);
    delay(100);

    servo.detach();
    delay(100);
  }

  delay(2000);
}

Please show your code and your wiring.

@Majenko I provided the code. But for the simulator I am not quite sure what to use. Neither Tinkercad nor Fritzing provide all the components I use...

Maybe this: https://arduino.stackexchange.com/questions/57584/does-softwareserial-and-the-servo-library-produce-interrupt-conflicts

I had a hunch I might see this: SoftwareSerial BT(txPin,rxPin); ...  NEVER use SoftwareSerial on pins 0/1 as they are the HARDWARE UART. You are using the right pins, but DO NOT use SoftwareSerial. Use Serial.

@Majenko Somehow it works but I am not quite sure how the Bluetooth communication is covered by the Serial interface. I edited the post with the currently working code (I also attach the servo only when needed and detach it after). Do you have any link where I can get a better understanding of why the Serial interface actually sends data over Bluetooth? When the whole project is complete, I will eventually post an answer with the fully working code.

The Serial sends data over pins 0 and 1. Those pins are also connected directly to the USB interface chip. Which is also why you have to disconnect bluetooth to upload your code.

So, I got carried away with my exams and I forgot to come back with an update and a solution. To take it short, I added a new source of power to the circuit and I am only turning the servo on when needed to rotate, then turn it off again. The code can be seen below:
#include <Servo.h>
#include <SoftwareSerial.h>

int rxPin = 2;
int txPin = 3;
int digitalPin = 7; // KY-028 digital interface
int analogPin = A2; // KY-028 analog interface
int servoPin = 11;

int angle = 0;
int temp;

const int minTemp = 150;
const int maxTemp = 350;
const int minAngle = 0;
const int maxAngle = 180;
const char sendDataPackageStartByte = 'T';
const int receiveDataPackageStartByteVal = 83; //"S"
const int receiveDataPackageEndByteVal = 13;
const int communicationDelay = 1000;
const int servoDelay = 100;

SoftwareSerial BT(rxPin,txPin);

Servo servo;
void setup() {
  pinMode(digitalPin, INPUT);
  pinMode(analogPin, INPUT);

  Serial.begin(9600);
  BT.begin(9600);
}

void loop() {
  if(BT.available() <= 0)
  {
    temp = analogRead(analogPin);
    BT.print(sendDataPackageStartByte);
    BT.print(temp/100);
    BT.print(temp/10%10);
    BT.print(temp%10);
    BT.println();
    delay(communicationDelay);
  }
  else
  {
    readData();
  }
}

void readData()
{
  if (BT.available())
  {
    char temp[3];
    while(BT.available() > 0)
    {
      char crtByte = BT.read();
      if (crtByte == receiveDataPackageStartByteVal)
      {
        temp[0] = BT.read();
        temp[1] = BT.read();
        temp[2] = BT.read();

        if(BT.read() != receiveDataPackageEndByteVal)
        {
          return;
        }

        break;
      }
    }

    int desiredTemp = atoi(temp);
    int desiredAngle = map(desiredTemp, minTemp, maxTemp, minAngle, maxAngle);
    printDataToSerial(desiredTemp, desiredAngle);

    turnServo(desiredAngle); //attach servo, write value, dettach
  }
}

void printDataToSerial(int desiredTemp, int desiredAngle)
{
  Serial.println("Desired Temperature:");
  Serial.println(desiredTemp);

  Serial.println("Desired Angle:");
  Serial.println(desiredAngle);
}

void turnServo(int angle)
{
  servo.attach(servoPin);
  delay(servoDelay);
  servo.write(angle);
  delay(servoDelay);
  servo.detach();
  delay(servoDelay);
}

Also, here would be the layout of my final circuit:

Basically what I wanted to achieve was sending and displaying the current temperature from an Arduino device to an Android one, then allow the user to adjust the temperature, simulating this with a servo commanded over Bluetooth. For those interested in the Android part as well (and the whole project actually), here is the link to the project repository on GitHub. The Android part is written with C# in the Xamarin Android framework. I hope this helps anyone landing here, good luck! :D


text:
How to get a stable LED lighting without scintillation over I2C bus
I built an 8x8 led matrix using white 5mm LEDs. I drive the LEDs using the MCP23017 connected to an Arduino over the I2C bus. The wiring of the LEDs in the matrix is such that a row is made up of 8 LEDs whose cathodes are wired together, and a column is made up of 8 LEDs whose anodes are wired together. The end of each row and each column is connected to a GPIO pin of the MCP23017.
The size of the pixel is 4cmx4cm which means that a row is 32 cm long (the same for a column).
I cannot get the light to be "stable", it keeps scintillating. I increased the clock frequency of the I2C bus from 100kHz to 400kHz, the light is more stable now, but not enough since the scintillation persists. Before that, I set the I2C clock frequency to 1700kH and the lighting became even slower..., I tried increasing the values of the pullup resistors of the GPIO pins of the MCP23017 to have a quicker response on its GPIO pins, but it had no effects.

I am thinking of 2 potential reasons:

The wires are too long for the I2C protocol to handle (a side of the led matrix is 32cm long).
the current reaching every column (the anodes) is not enough since there are so many leds to light up.

What do you think is causing this bad lighting? should I change the MCP23017 with another type of expander/protocol?
Here's the code:
#include <Wire.h>
#include <Adafruit_MCP23017.h>

bool four[3][5] = {{1, 1, 1, 0, 0}, {0, 0, 1, 0, 0}, {1, 1, 1, 1, 1}};
Adafruit_MCP23017 mcp;

void setup() {
  mcp.begin();
  for(int i=0; i<16; i++){
    mcp.pinMode(i, OUTPUT);
    }
}

void set_column(uint8_t col_idx, bool pixels[]){

  for(uint8_t i=0; i<8; i++)
    mcp.digitalWrite(i, HIGH);

  for(uint8_t i=8; i<16; i++) //Anodes are connected to Bank B of the MCP23O17
    if(i!=col_idx+8)
      mcp.digitalWrite(i, LOW);
    else
      mcp.digitalWrite(i, HIGH);

  for(uint8_t i=0; i<8; i++) //Cathodes are connected to Bank A of the MCP23O17
    if(pixels[i])
      mcp.digitalWrite(i, LOW);
}

void display_character(bool character[3][5]){
  bool pixels[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  for(int col=0; col<3; col++){
    for(int i=0; i<5; i++){
      pixels[i+3] = character[col][i];
      }
    set_column(7-col, pixels);
    }
}

void loop() {

  uint32_t time = millis();
  while(millis() - time < 1000)
    display_character(four);
}

The problem is that you're using I2C. It's just not fast enough.

What library are you using? It seems to do one transmission to set one pin. That would result in up to 24 transmissions. Also you write pins 0 to 7 twice, which is unnecessary. Instead it should be possible to write all 16 pins with one transmission. That would be way faster

MAX7219 would be much better driver for 8x8 matrix than bitbandig over extender. And as noted, you should write whole colum at once. However row outputs can drive only about 30mA, so I hope you don't have resistors for the colums too small

@Majenko, Even 400k Hz as clock frequency of I2C is not enough? why is that?

@chrisl I am using the library Adafruit_MCP23017 (I updated the code snippet in the question). Yes each pin of the MCP23017 setting takes a transmission... I realize I can set them much fewer transmissions. Thanks for the suggestion.

@KIIV I put a 20ohm resistor for each column, I chose this value to get as a brighter light as possible. Am I wrong on this point?

@S.E.K. "Absolute Maximum" sink or source current is 25mA per pin and 150mA for Vss / 125mA Vdd. If the forward voltage of LEDs is about 3V and Vcc for MCP 5V then you have  2V on 20R resistor -> 100mA (theoretically) for a single led. Basically it'll burn soon or later

@KIIV if the current per pin is 25mA, then the voltage through the 20R resistor according to Ohm's law is 20*0.025=0.5V, how did you find that I have 2V on 20R? (My electronics knowledge is kind of shaky...)

Led has for example nonlinear characteristic where at 3.1V there will be 20mA (depends on color and other params. After that point voltage raises slowly but current shoots up rapidly. 3.5v might be easily over 100mA.

Personally I would either use a dedicated LED matrix drive chip, or a dedicated Arduino to drive the display matrix directly.


text:
http request in time intervals
I'm doing a program that receives data from a web page every so often, but only receives the data once and then receives everything blank. I need help to receive the data every time indefinitely. I am using arduino uno with arduino etherner shield
My code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, 0, 177);
EthernetClient client;

int REDLed= 2;
int GREENLed= 3;
int BLUELed= 4;

void setup()
{
  pinMode(REDLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  Serial.println("power up" );
  delay(3000);
}

void loop()
{
  Serial.println("SubmitHttpRequest - started" );
  SubmitHttpRequest();
  Serial.println("SubmitHttpRequest - finished" );
  delay(10000);
}

void SubmitHttpRequest()
{
  if (client.connect(server, 80))
  {
    Serial.println("connected");
    client.println("GET /arduino/getstate.php?color=All HTTP/1.1");
    client.println("Host: cybertodo.mx");
    client.println("Connection: close");
    client.println();
  }
  else
  {
    Serial.println("connection failed");
  }
  delay(100);
  changeLed();
}

void changeLed()
{
  String content = "";
  Serial.println(client.available());
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }
  Serial.println(content);
  if(content.substring(30,31)== "1")
  {
    digitalWrite(REDLed, HIGH);
  }
  else if (content.substring(30,31)== "0")
  {
    digitalWrite(REDLed, LOW);
  }

  if(content.substring(31,32)== "1")
  {
    digitalWrite(GREENLed, HIGH);
  }
  else if (content.substring(31,32)== "0")
  {
    digitalWrite(GREENLed, LOW);
  }

  if(content.substring(32,33)== "1")
  {
    digitalWrite(BLUELed, HIGH);
  }
  else if (content.substring(32,33)== "0")
  {
    digitalWrite(BLUELed, LOW);
  }
  content = "";
}

Looks like you might be looping faster than the client.avaiable() is receiving data.  Consider what happens if you only get half the response at a time -- the ifs drop though, you delete the content, then exit the changeLed() and de-allocate content.  Consider making content global, and acting and clearing only when you get a full message.

Immediately after making the request when reading client.available() will be 0 since no data was received yet so:
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }

Will never actually run. Try something like:
unsigned long last = millis();
String content = "";

while(client.connected()) {
  int len = client.available();
  if(len > 0) {
    last = millis();

    char buff[len];
    for(int i = 0; i < len; i++) {
      buff[i] = client.read();
    }
    content += String(buff);

  } else {
    if(millis() - last > 2000) {
      client.stop();
      return;
    }
    delay(1);
  }
}

Also note if you use Connection: close on the client then you must close the connection. This example doesn't do that until 2 seconds have passed. To do this properly you'd need to also add header parsing to your client and close the connection once the amount specified in Content-Length is received.

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


text:
Servo motor sweeps beyond 180
I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0-->180-->0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?
int angle = 0;

void setup() {
  myservo.attach(9);
  myservo.write(angle);
}

void loop()
{
  for (angle = 0; angle < 180; angle += 1)
  {
    myservo.write(angle);
    delay (50);
  }

  for (angle = 180; angle > 0; angle -= 1)
  {
    myservo.write(angle);
    delay(50);
  }
}

Are you trying to have the servo sweep at a particular speed? Why not just use:
void loop()
{
  angle=180;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.

  angle=0;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.
}

Thanks. I tried this and it worked for 0.5 second delay but when I increased the time the servo makes a 360 again. it goes 180 degrees-->360 turn-->0 degree--> 180 then pauses-->360 degree turn and repeats.

Can you post a link to the exact servo unit you are using?

I purchased the Elegoo Uno Project Super Starter Kit                                             (http://www.elegoo.com/product/elegoo-uno-project-super-starter-kit/)

If that servo goes over 180 travel, something is wrong with it.

Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?

Not that I am aware of. I made no modifications to it.

Is it a continuous rotation servo ? Can you give the brand and type and a link to where you bought it ?

I had a bunch of SG90 mini servos so I tried your code. My servos turn 0 -> 180 -> 0 -> 180 -> 0 -> 180, over and over. No 360 spins at all.

Maybe your servo is defect? (can you check with another servo?)
Maybe it is not getting enough power? (how are you powering it?) It needs at least 4.8V and at least 220mA
Maybe it doesn't get a strong clean PWM signal? (You'll probably need an oscilloscope to check this)

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


text:
SSD1306 - Is there a way to scroll a certain number of pixels only?
For a hobby project, I am trying to make some sort of little game with an ATtiny85 and an SSD1306 OLED display, mostly to see how much I can do with the least hardware possible. Something like Captain Rectangle rescues the Circle Princess from the Evil Triangles.
I have been seeing what I can do with an SSD1306 (datasheet), specifically horizontal scrolling. It has a feature to scroll the display horizontally (left or right) at a certain rate, i.e. 1 pixel per given number of frames. This is achieved by issuing three commands:

The first command sets up the scroll.
The second command starts the scroll.
The third command stops the scroll.

While letting the display unit take care of scrolling all by itself sure takes a load off the minimalist MCU, what I really want is to just scroll 1 pixel right away (OK if it takes the display milliseconds to do this). Is there a reliable way to do that?
Some things I have tried:

Draw a column of pixels, setup and start the scroll, stop the scroll right away, delay 10ms, repeat.  The screen does not do much scrolling--I think it only scrolls every x number of attempts, depending on the timing of when the OLED wants to do scrolling vs. when I tell it to stop.
Stop scrolling, draw a column of pixels, setup and start the scroll, delay 10ms. In a preliminary demo, this appears to mostly work, but obviously I will have to read more about the timing of the scrolling to really know, and besides this is a fragile solution--if the OLED scrolls 1 too many or too few pixels, then the MCU program's understanding of what should be on the screen will not line up with that of the display.
I also looked at the "Set Column Address" command, which specifies column start address and end address of the display data RAM, but that has no effect on data already displayed--it does not move visibly on the screen, but only affects subsequent writes--where the address pointer points, and what columns it may point to.

BTW, I am using vertical memory address mode, i.e. I send data one column of pixels at a time, since that is what would have to be drawn when scrolling horizontally 1 pixel.
I see there are more options to try with vertical scrolling, though my screen size (128x64) is not conducive to that.
I could also try re-writing everything on the display every 10ms, but first, did I overlook anything in the datasheet?

If someone with privileges could please add an SSD1306 tag, that would be great.
BTW, I'm using Arduino IDE and a Trinket, but I think that's immaterial.

are you not able to add the tag yourself?

the SSD1306 datasheet that you posted ... search for the word "vertical" in the datasheet


text:
Feeding microcontroller and linear actuators (motors) with the same power supply
I have already made a diagram using a motor controller. I want to use only one power supply to feed arduino and motors. I want to use MDD10 dual motor driver.
The details of the actuators each one is:
Input voltage: 12VDC,
Max Load: 750N(168.607lbs),
Stroke Length: 16 inch,
Travel Speed: 12mm/s,
Duty Cyle: 25%,
Current: 5A.
The power supply is 12V, 10A.
Could you please check if it is ok, or which would be the best solution?
Some of my concerns are:
Be sure if the feed of 12 volts for the motors, and 5 volts for Arduino are correct and can live together as shown.
Be sure if the wiring for the Arduino, driver and motors is correct since it looks kind of simple.

I want to know if this is the natural approach by doing it with a voltage regulator to feed the Arduino and with 12V 10A power supply to feed the motors, or if there are other, better options to make the circuit feed only using one power supply (12V, 10A).
MDD10 Datasheet Link: https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-10a-7-30v-dual-channel-dc-motor-driver-shield-datasheet.pdf
Thanks in advance
UPDATE
I have increased power supply to 13A, also changed the linear voltage regulator (7805) to a switching voltage regulator (OKI-78SR-5), what do you think about this approach?

Or I should try with the 12V DC Vin of Arduino(I understand that it works with a linear voltage regulator)? Being this option, it could be maybe with a voltage pre-regulation stage(for example from 12V to 9V) or maybe connecting directly to the jack.

Thanks, Best Regards.

First of all I would look to see if the two motors will actually run at the same time.
If not then the 10A power supply, is fine.
If they do run together, for how long? (you mention 25% duty cycle), power supplies usually have a over capability for a short period of time, and batteries will supply more current but at a slightly reduced voltage, so if going slightly slower isn't an issue then this would be fine.
Then there is the question of do they really use all 5Amps, I very much suspect not, unless you are fully loading the actuator(750N), they prob run at 2-3 amps at most.
Secondly
Circuit protection, fuses or thermal shutdown links for the motors is required, better still instant overcurrent protection for them set at 1.2x nominal current.
Do some worst case tests and measure the current, set the protection to 1.2 x this.
Remember if there is an issue the supply voltage will start to drop, its now that the micro will suffer if the voltage dips too much and you have no protection/sensing.
So suspect the power supply is more than ok.

Your approach looks reasonable, but you don't have enough power. The motors will draw 10A, which is the full output of your power supply/battery. That doesn't leave any left over for your Arduino system.
You should have a high enough capacity power supply/battery for your total peak power requirement plus a little margin (say 10%-20%) The Arduino and all the other electronics on it might draw another 1/2 amp, so 10.5 total. Add 20% margin to that and you get 10.5 * 1.2, or about 12.6 A.
(When you drive a power supply up to its upper limit its output voltage can start to sag. By having a buffer it doesn't have to work as hard.)
One advantage you have in your circuit is that you're feeding unregulated 12V to your motors, and then feeding 12 into your Arduino's voltage regulator. That way even if the 12V supply droops to 10V under maximum load, the voltage regulator will still be able to maintain a clean 5V supply to your MCU.
Also note that you could feed 12V into the Arduino's V in and use its built-in voltage regulator. As long as don't draw a lot of current out of its 5V line the built-in regulator could manage the 5V voltage regulation itself. If you need ≥500 mA, though, you might want to use an external buck converter (or a high capacity linear regulator with a good heat sink.)

Hello Duncan C. So what I understand is that the circuit I show could connect it directly to the 12-volt arduino jack because I don't need much current. And only If I need more current for an extra element that is connected to arduino output, I would need a buck converter or high capacity linear regulator to increase amperage. Did I understand correctly? Could you give an example when I need a buck converter, What exactly is a buck converter/high capacity linear regulator? Thanks

The Arduino uses a linear voltage regulator. A linear voltage regulator is an analog circuit that uses a transistor to apply a variable resistance to the input voltage to lower it down to the output voltage. It converts the excess voltage to heat, so at high source voltages and current loads it gets hot. A buck converter is a type of switching power supply that instead uses pulses of current to regulate the output voltage. Buck converters are more efficient, and don't create as much heat at high current loads.

If you're just powering an Arduino and a few components, you won't be using much current, so the built-in linear power supply in the Arduino will be fine. If you need ≥500mA of 5V, the Arduino's power supply will start to get hot, and as you get up to 1A, it may even overheat when fed from a 12V supply.

Hey @Duncan, Greetings. I have updated my question. I changed the schematic by adding a switching regulator, instead of the linear regulator. I am also referring to the option to connect directly to the 12V jack of arduino. Could you please check it? Thanks

Same problem. You don't have enough power. You want your power supply to provide a little MORE current than your max need, and your 10A supply is less, not more. Boost the battery/power supply to ≈13A and you should be good.

Hello @Duncan,  I made another update. I have already changed the current of the power supply to 13A. I also added a schematic for using Vin pin of Arduino as another second option. Could you please chek the two options, and tell me which one you think is better. Thanks


text:
Problem with arduino starter kit project 7

Can someone pls help me only the two buttons clossest to the big green wire work and i don^t know why i have already tried swapping buttons
EDIT 1:
my code

and i know the first two are working because they generate a tone with the piezo
the third one does nothing and the last one only makes static noises

Why bother, I don't like multiple buttons with resistors for an analog value. I think your circuit is okay. It could be a bad contact of the breadboard.

How can you tell, that they  don't work? Please explain more. And please show us your code. You can edit your question to add these information by clicking at the edit button under your question. Please format the code correctly, by selecting it and clicking the {} button

@Jot This is a starter kit project. It teaches how you can multiplex multiple buttons into a single analog input and figure out which button(s) are being pressed from a single line. It might not be something you want/need to do, but it's still a worthwhile concept to learn.

please do not post a picture of the code .... post the code text .... use the {} button to format it

your code contains a serial.print() command .... please open the serial monitor in the arduino IDE and find out what values are being printed for each button press .... add those values to your question above

@DuncanC but I still don't like it. The contacts of the buttons can get dirty, multiple buttons can be pressed, and with 1MΩ it is very sensitive for electrical noise. Avoiding troubles is more important to learn.

I still think it's a worthwhile technique to learn. As for the resistors, I wonder why those values were chosen. I'd be inclined to use power-of-two values (1KΩ, 2KΩ, 4KΩ, 8KΩ) That way you could decode single and multiple button presses.

I see the problem. The connections to the first 2 buttons are correct. You're missing a yellow wire linking the output of the bottom 2 buttons to AO however, so the 3rd and 4th buttons are not connected to your A0 pin at all. Add a yellow wire between row 24 and row 20 on your breadboard.
EDIT:
I see now that there is a green wire connecting rows 24 and 20 together. However, that is the likely place where things go wrong. I would suggest taking a couple of jumpers and connecting them to a multimeter set to continuity mode. Put one in row 28, and then test continuity to row 24, row 20, and row 16.
One of your wires may not be seated into the breadboard properly, or you may even have a bad row on your breadboard. I've seen that before.
EDIT #2:
A multimeter is your friend. If you don't have one, you should get one, and learn how to use it. It's invaluable for troubleshooting circuits. (Get one that has a continuity mode that beeps when it detects continuity, and that has auto-ranging voltage and resistance measurements.)

thank you this really helped me think what if it is the breadboard so i took of the sticky backside and there were some loose pieces of metal i pushed on these pieces and now it works

only problem i have now is that the analog read value from the when i press the last button isn't a steady 1023 but even if i connect the analog directly to the 5v line it isn't steady so i think that should be solved in code but i am not sure

Yes, I would suggest not matching a specific value. Write your code to check for a range of analog values. Your circuit is a voltage divider, and the button with no resistor (the bottom one in your illustration) will give a value close to, but not quite, 5V. I'd suggest looking for a value ≥1020 for that button. Check the value you get for the other buttons and implement ranges with upper/lower bounds for those.

thanks alot for the reply the value >= 1020 made it work perfectly for me. Again thanks for your help


text:
Arduino Uno - Variables randomly changing
So I have a circuit for a timer (I don't think it is the problem)

Sorry for it being a little messy.
And I have this code (probably the problem):
// LiquidCrystal - Version: Latest
#include <LiquidCrystal.h>

/*

*/

const int switchUnitButton = 9;
const int selectButton = 10;
const int startButton = 8;
const int stopButton = 7;
const int d4 = 5;
const int d5 = 4;
const int d6 = 3;
const int d7 = 2;
const int rs = 12;
const int en = 11;
String unit = "sec";
int unitCycle = 1;
int secCount = 0;
int minCount = 0;
int hourCount = 0;
int dayCount = 0;
int switchUnitState;
int prevUnitState;
int selectState;
int prevSelectState;
int startState;
int prevStartState;
int stopState;
int prevStopState;
LiquidCrystal lcd = LiquidCrystal(rs, en, d4, d5, d6, d7);

void setup() {
  Serial.begin(9600);
  pinMode(switchUnitButton, INPUT);
  pinMode(selectButton, INPUT);
  pinMode(startButton, INPUT);
  pinMode(stopButton, INPUT);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  switchUnitState = digitalRead(switchUnitButton);
  selectState = digitalRead(selectButton);
  startState = digitalRead(startButton);
  stopState = digitalRead(stopButton);

  if (switchUnitState == HIGH) {
    if (prevUnitState != switchUnitState) {
      if (unitCycle < 4) {
       unitCycle++;
      } else if (unitCycle == 4) {
       unitCycle = 1;
      }
    }
  }

  Serial.print(unitCycle + "\n");

  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

  lcd.setCursor(0, 0);
  lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));
  lcd.setCursor(0, 1);
  lcd.print("Hr: " + String(hourCount) + " Day: " + String(dayCount));

  prevUnitState = switchUnitState;
  prevSelectState = selectState;
  prevStartState = startState;
  prevStopState = stopState;
}

And sometimes without me clicking a button the unit value changes or sometimes when I click the selectButton for the amount to go up it changes which unit it is adding to. And sometimes the string has parts before it from other units like "inhour" what is happening?

Your second button is wired wrong - or is that just a "typo"?

Oh, and all that String abuse will cause untold problems. You don't need any of it.

So I should just use unitCycle for which unit rather than the changing string? And yes that button was a "typo";

I fixed that "typo"

There is never any call to change a string like that or use it as a state variable. Just print a different word depending on what the cycle is. And don't forget to use F() for your literals to save RAM.

@Majenko Alright I'll look into that, thanks

Seems you forgot to debounce the buttons.

You are seriously abusing the String class.  There is absolutely no need to use any Strings at all in your program.
For example:
  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

would be better written as:
  if (unitCycle == 1) {
    Serial.println(F("sec"));
  } else if (unitCycle == 2) {
    Serial.println(F("min"));
  } else if (unitCycle == 3) {
    Serial.println(F("hour"));
  } else {
    Serial.println(F("day"));
  }

And:
  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

as:
  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unitCycle == 1) {
        secCount++;
      } else if (unitCycle == 2) {
        minCount++;
      } else if (unitCycle == 3) {
        hourCount++;
      } else {
        dayCount++;
      }
    }
  }

And then the cardinal sin:
lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));

All that string creation, concatenation, and destruction is just evil.  Instead, use:
lcd.print(F("Sec: "));
lcd.print(secCount);
lcd.print(F(" Min: "));
lcd.print(minCount);

Haha, alright, thanks for your time, and help!

@BeastCoder2 You might want to read this: https://majenko.co.uk/blog/evils-arduino-strings

Alright I will, your website is really cool!

eyeroll... I had one wire in the wrong pin...


text:
Programming the serial description
Is it possible to program a custom description so that my python program can know exactly what USB port to connect to for that specific programming?
It should be able to find any board with that program so the best approach is if a custom description can be programmed with the active program being uploaded.
I want to make sure my setup can handle multiple Arduino boards and always know what USB to use for each specific use.
This finds a general Arduino device:
for port in serial.tools.list_ports.comports():
    if "Arduino" in port.description:
        print "Arduino device!"

But I want something like this:
for port in serial.tools.list_ports.comports():
    if "proximity_sensor" in port.description:
        print "My specific Arduino program!"

Use the serial_number parameter to find a specific board?

Yes, this will find one specific board. What I want is to find a series of boards with a specific programming. I will update my initial question to clarify this.

On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.
However (shameless self-promotion coming here...) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:
USBFS usbDevice;
USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
CDCACM USBSerial;

void setup() {
    USB.addDevice(USBSerial);
    USB.begin();
}

void loop() {
    USBSerial.println(millis());
    delay(1000);
}

Which results in:
[  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
[  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
[  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  661.458619] usb 2-1.2.7: Product: My Little Widget
[  661.458621] usb 2-1.2.7: Manufacturer: Espentech
[  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
[  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device


text:
How to upload and store settings/variables from computer on the arduino?
I'm literally as green of a noob as I can be at this moment. Been watching a ton of tuts as I plan my project, but can't seem to find anything about settings being uploaded from an external source, and then stored on the arduino.
I want to create a board with multiple buttons. I want these buttons to then transmit MIDI PC/CC based on customizable settings uploaded via a computer. So, I'll create an app that can "create" the settings (json?) for each button. Ideally, I'd just connect the board, create the settings, then upload it to the device.
I've been reading about storing things like this in EEPROM, but that has a limited life span (which scares me). So, do I store these variables in EEPROM, or do I just compile and upload the app that has the new values in the variables?
I'm just looking for a possible direction and links for research.
Thanks in advance.

interesting project .... perhaps you can store the settings in a file on an SD card

Re “or do I just compile and upload the app”: that would store the settings with the app, in the flash memory, which has a shorter life span than the EEPROM.

wow!? a downvote for wanting guidance?

https://arduino.stackexchange.com/tour

Your question is quite broad, so I will give you some directions for the different parts.

Communication with the PC to receive settings: For the Arduino Uno you are basically left with the Serial (UART) interface to communicate with the PC. For wired communication you can simply use the USB port. On your PC you need a program to send the settings over the serial com port to the Arduino. You can either use any serial terminal program or you can write your own. That depends on your needs. On the Arduino you need code to parse the serial communication to get the settings. It seems, that your can be rather complex (not just simple numbers of the same type). So you should implement a basic message protocol. It is common to use the newline character (\n) as the delimiter at the end of a message. In your code you read the serial data into a buffer, until you read a newline character. Then you start to process the message in a whole. You can see the implementation of this protocol in the SerialEvent example that comes with the Arduino IDE. Then you can use JSON as text based data format to transmit it to the Arduino. There you can use the Arduino JSON library to decode the data and get the settings. If you don't want to use JSON, you can also use a simpler protocol.
Saving the received settings: Without any further hardware the EEPROM is the way to go. The "life span", that you mention, are the possible number of write cycles, until a cell is not longer garanteed to work correctly. Read cycles don't do any harm here. Atmel gives a number of 100.000 write cycles, but notice, that this is the minimum garanteed number. (Have a look at this question for further info) Do you really change the settings this often? Make a short calculation like this: Imagine that you want to change the settings 10 times a day on every day in the year. Even then you get about 27 years with the EEPROM write cycles, far enough for other components to break. But if you really want to go safe here, you can use wear leveling. With this technique you rotate through different EEPROM cells to save your settings. You use more space in EEPROM, but each individual cell will get only a fraction of the write load. There are even libraries ready to use for this. A quick google search gave me the EEPROMWearLevel library, though I haven't used it myself. Depending on the total size of your settings, you might get a life span multiple times bigger with this. If you still don't want to use EEPROM, you can do as jsotola wrote in his comment: You can by a SD card module for Arduino and a fitting SD card and save the data there. This will lead to more programming overhead, especially, if you want to use a file system to also be able to read and write the SD card on the PC. (Note: The storage chips in SD cards have the same problem with limited write cycles, so they have the wear leveling incorporated into the hardware of the card)

You might as well decide, that you don't need the settings to be persistent between resets. Then you can just use variables and fill them with the settings from the Serial interface code.
You yourself have to decide, what the best way to go is here.

Thank you for taking the time to answer my questions. I appreciate it.

If you consider my answer as correct/fitting, please accept it as correct :)

I think I'm going to go the route of saving to the EEPROM. Here goes nothing...


text:
7 segment display blinking
I want to display the DHT22 temperature and humidity sensor in a 3 digit 7 segments display. It's always showing the  sensor value and after 2 or 3 sec the display turns off, and then the display turns on, and so on.
I need help to understand where is the mistake on the code to make the display always turned ON.
#include <SevSeg.h>
#include <EEPROM.h>
#include "DHT.h"
#define COMMON_ANODE 0
#define DHTPIN A0     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value
SevSeg sevseg;

void setup(){

byte numDigits = 3;
byte digitPins[] = {1,2,3};
byte segmentPins[] = {4,5,6,7,8,9,10,11};
sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
 dht.begin();
}

void loop(){
   temp= dht.readTemperature();

   sevseg.setNumber(temp,1);
   sevseg.refreshDisplay();
}

A good way to avoid display flicker is to only update the display when needed.  The display update is what causes it to flicker.  If you change your main loop as below, the display will only update when needed (when the current reading is different than the last reading).  It's probably also a good idea to only read the temperature every 2 seconds or so which can be controlled with a simple delay().
float temp, last_temp = 0;

void loop() {
    temp = dht.readTemperature();
    if (temp != last_temp)
    {
        sevseg.setNumber(temp,1);
        sevseg.refreshDisplay();
    }
    last_temp = temp;
    delay(2000);
}

SevSeg library author says "Your program must run the refreshDisplay() function repeatedly to display the number", he even warns that delays will produce undesirable effects... I tried this and it didn't work.

You have a multiplexed display. Multiplexed displays have to be constantly updated, or they display the last displayed digit (if there was one) for an extended period.
The reading from the DHT will take time. That time will interrupt the display updates causing it to stop for a while as it reads.
Why does it do it every few seconds? All I can suggest is that the DHT library you are using limits the actual readings to every few seconds - and between those times it just returns the previously stored value.
To get around it you should consider doing your display updates from within a timer interrupt (assuming your DHT library doesn't disable interrupts).

Many thanks Majenko, can you send a sample code to solved

many thanks,i would like to share my idea which i try it this week with all my friends, i just repair DHT22 library and decrease the delay time in, and then the 7 segments blinking every 2 seconds will disappear .


text:
Analog thermistor readings are wrong
There are some discrepancies between what is read by the analog channel for a thermistor, ohms values directly obtained on the thermistor using an ohmmeter, and another digital temperature sensor.

Figure 1: Left column (y axis) is degree Celcius; x axis is time (minutes). Orange is what was read by the analog channel (thermistor); in yellow the reading by a commercial digital sensor; and in green, manual readings of the thermistor using a ohm-meter.
A bit more context, we are building a simple system to read the temperature from a thermistor via an analog channel. Code algorithm is very similar to what is found here and the electronic layout inspired from here. When we ran into problems,  we just went back to the working basics as instructed by those two above-mentioned references.
Pad resistor is 7K Ohms @ +/-1%, measured resistance was 6690 ohms
Thermistor is 2252 Ohms @ 25 degree Celsius. Coefficients are as follow, coefficient were solved following a calibration in a thermal bath:

COEFF_A = 0.0014644
COEFF_B = 0.00023888
COEFF_C = 9.8996E-08

Specs from vendor are here (PDF) factory coefficient are about the same. I tried to calculate with either factory and in-house calibrated and there is a few thousandth of a degree of difference between the two - not enough yet to explain the current problem
While investigating I saw some sketch with the same resistance for pad resistor and thermistor, but have seen other differing thus assume this is not an issue.
To troubleshoot and isolate the origin of the discrepancies of the orange line VS other reading, we used

other thermistors (every single one behave similarly as the orange line in the figure 1)
other digital temperature sensors (every single one behave similarly as the yellow line in the figure 1)
we try to put 2 analog thermistors and 2 digital temperature sensors on the same arduino - analog were consistant between each other (discrepancies) and the digital one were behaving as expected (correctly)
we switched the pad resistor, no effect
other arduinos (did not changed anything, every single one was repeatedly demonstrating the same behaviour )
used the system in a temperature controlled room and the discrepancy was still present for the analog channel and absent for the digital sensor.

To be clear, green and yellow are what we think is the 'real' temperature; and the orange is the discrepancy. About 1 - 2 degree differences
We used the raw analog value read by the arduino as an input to manually feed and solve the Steinhart–Hart equation (like using IPYTHON and by hand) and output is the same as the orange line. Did the same with the thermistor obtained by the ohm-meter (Green dots on figure).
What should be investigated next to solve the discrepancy between what is read by the analogue channel connected to a thermistor and what the same thermistor provide to the ohm-meter?
Sketch follows
#define THERMISTORPIN_0 0               // analog pin 0 on the board
#define SERIESRESISTOR_0 6990             // balance/pad resistor value (ohm)
#define THERMISTORNOMINAL 2252          // resistance at 25 degrees C
#define ZEROABS -273.15                 // zero Kelvin (Celsius)

#define COEFF_A 1.4644E-03          // Coefficient A for Steinhart-Hart eq.
#define COEFF_B 2.3888E-04          // Coefficient B for Steinhart-Hart eq.
#define COEFF_C 9.8996E-08          // Coefficient C for Steinhart-Hart eq.

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

void loop()
{
    float temp1;
    temp1 = Thermistor(analogRead(THERMISTORPIN_0),SERIESRESISTOR_0);
    Serial.println(temp1);
}

float Thermistor(int RawADC, long padResistance) {
  long Resistance;
  float Temp;
  Resistance = padResistance / ((1023.0 / RawADC) - 1);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp,3)));
  Temp += ZEROABS;

  return Temp;
}

try plotting VREF over same timeframe as read with a dmm, do you see distortion?

@dandavis OK I will try this thank you for suggestion, will post an update when done

What is the exact value of the 7k resistor ? Do you know the type of the resistor, to be able to find the A, B, C and β values in the datasheet. This online calculation might be useful: http://www.thinksrs.com/downloads/programs/Therm%20Calc/NTCCalibrator/NTCcalculator.htm Please show your sketch.

@Jot yes I have the exact values for this, I will update my post with the relevant info. This site is awesome isn't it (thinksrs). Will check for the sketch too

Are your calculations assuming a VREF of 5V, or do you know the real reference (VCC by default) voltage?  2. Is your thermistor at the end of a long wire?

@Majenko (1) Assuming 5V, measured 4.91ish; but in my sketch (working on it) I don't seem to reference the VREF at all, like example sketches -  maybe I should check it out in greater depth; (2) Good point, yes the thermistor is at the end of a long wire. But yet, if I measure using the ohmmeter directly on the cable, (fig 1, result in green) the thermistor is still at the end of the same long wire, like when the arduino read (fig 1 in orange)

You must be referencing VREF somewhere in order to calculate the resistance. After all, the resistance is measured by the voltage drop across it, and to convert the raw 0-1023 value of the ADC to a voltage you need to calculate it with respect to VREF. If you use the wrong value you will get the wrong result. 5V is not 4.91V.

@Majenko thank you for confirming this possible path for resolution; I suspected this for a while but since it was not really defined in examples, I tried to look for other issues I guess. It was overviewed in examples because the calculation cancels out; for example ADC value = R / (R + 10K) * Vcc * 1023 / Vcc
become
ADC value = R / (R + 10K) * 1023

True, that is...  Don't forget 10K should be 6690, of course...

@Majenko if you wish to summarize your intervention as an answer, I would choose your answer to close the question

@Majenko, for a thermister plus resistor the VCC drops out the calculation. It is relative to VCC. In the calculation the 5.0 could be used, and the actual voltage may vary, it may be 4.0 or 5.5V, it does not matter. That's the beauty of a thermistor. However, the slightest deviation in the calculation and the curve will change. EtienneGodin, where is the sketch ? (it is 1024 ADC steps, not 1023).

@Jot Sketch was added

@Majenko - comments under questions are for clarifying the question. If you think you have an answer it is preferable to post it, so it can be accepted and/or commented on.

@NickGammon it is pure supposition at the moment. It looks to not be the correct answer so far, so doesn't deserve to be an answer.

@Majenko - the OP has asked you to post your supposition as an answer. It can't get much clearer than that. :)

@NickGammon even after he negated (correctly) my supposition. The thing about VCC is wrong and cannot be the answer. The mentioning of the wrong resistor value in a calculation I take as a copy and paste from original source not his modified source. With no clarification on if that actually is incorrect in his code I have no valid answer to post.

@NickGammon Looking at the edited question with the code included it is plain that the resistor is not the problem either - so there is nothing about my comments that can be converted into a correct answer, and I won't post an answer I know to be blatantly incorrect.

Looking at your referenced diagram, you are connecting AREF to 3.3V, but don't have an analogReference(EXTERNAL)  in your code.  https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/ says not to do that since it shorts the external and internal references together during the analogueRead().  Maybe that could be causing some odd transients during the ADC switching?

One possibility that has not been mentioned yet: the issue may be
the calibration of your ADC converter. Your code carries the implicit
assumption that the voltage you measure is
V = Vref × RawADC ÷ 1023

The correct formula is
V = Vref × (RawADC + offset) ÷ scale

where offset is ideally 0 and scale is ideally 1024 (and not 1023,
as you are assuming). Since you are looking at relatively small
discrepancies, the “ideal ADC” assumption may not be a good enough. I
have calibrated 3 Arduino ADCs and found offsets between 2.2 and
2.4, and scale factors between 1026.1 and 1026.3. Thus, if you have an
accuracy issue, I recommend you calibrate your own ADC.
As a side note, you could expect slightly better accuracy if the
thermistor and the resistor are closer in resistance. Right now you have
a factor 3, which is not that bad, but you could use a 2.2 kΩ
resistor, which is a very standard value.

I was able to  figure out a function to calculate the offset - since there is an acceptable relation between measured and expected, whatever thermistors, Arduino boards, cables/wire or breadboards we are using. Your range suggestions for the offset helped to calibrate our curves.

So far I can see nothing wrong.
This is all about accuracy and being precise. That is how to deal with this problem. This is not a quick fix.
For example the resistor value has been: 10k, 7k, 6690 and 6990. That's too sloppy.
I think that you have not told us that the thermistor is at GND (I prefer it being at GND, that's good).
Test: At 25 °C the thermistor and resistor result in a ADC value of 249.5, and with that in the sketch the result is 25 °C. Very nice. Around 25 °C the sketch is accurate.
Instead of a short minimalistic calculation you could calculate everything. For example the resistance of the thermistor and the voltage at the analog pin. That would make it easer to check those values with a multimeter.
I prefer to let the Arduino do the calculation, and not trying to be smart and optimize something. Let the compiler to the optimizations.
We have to look further than the thermistor, the Arduino and the sketch.

How long is a long wire ? What kind of cable ? Shielded cable ? Is one wire connected to GND ? and at the end is only the thermistor ? The GND is not used for something else ? Are the wires of the thermistor or the cable touching a metal object or water ? A multimeter is not connected to something, but an Arduino is connected via the usb to the computer and perhaps to earth ground. With a power supply, there is a small capacitive coupling to the mains. What happen if the Arduino is battery powered and not connected to something ?
How well is the wire connected to the Arduino. Try to solder it if possible. If it is already soldered, was it a good weld ?
What else is going on with the Arduino board ? It could be GND offset caused by something that pushes current through the GND. A LCD display with its background light connected in the wrong way could cause this. Is the thermistor connected via a breadboard, and there is something else on that breadboard ? Then you have almost certainly a DC offset.
Could you try with another Arduino board and another computer ? Only the Arduino board, the thermistor + resistor and a USB cable to the computer. Without the long wires. Try a desktop computer, not a laptop (the usb 5V of a laptop could be less reliable). You are now caught in some kind of trap, and you get out by making a second test setup with a new set of components and not even using a single wire from the first setup.
The NTC could cool down via the metal legs.
Perhaps averaging a number of samples would help. When the final average     calculation is done with float, you could even increase the resolution beyond 10 bits of the ADC.

For now, I think that the problem is between the thermistor and the microcontroller on the Arduino board. Could you try to eliminate any DC offset of the GND and be sure to isolate the thermistor (from metal objects and water)

there seems to be two problems:
1) calibration: the digital sensor / analog sensor may not be calibrated properly - this can account for the gap between the two curves.
2) response time: the digital sensor seems to react much faster than the analog sensor. that could be due to placement, physical attributes (smaller thermal mass for example), ...


text:
ESP8266 not working properly
It's the first time I use an ESP8266 and I didn't manage to get a proper response in the Arduino serial monitor. I only see weird characters, when I move the 3.3V wire.
You can see the connections in the following picture:

The code I run is the following one:
#include <SoftwareSerial.h>
SoftwareSerial BT1(3, 2); // RX | TX

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

void loop()
{
    String B= ".";
    if (BT1.available())
    {
        char c = BT1.read();
        Serial.print(c);
    }
    if (Serial.available())
    {
        char c = Serial.read();
        BT1.print(c);
    }
}

Maybe it's something really stupid. I am a total beginner, so I appreciate any help.
EDIT: I think power supply is 3.3V
SOLUTION: the problem was the power supply. I tried exactly the same using the 3.3V from the arduino instead of the power supply and it works perfectly!

where is the logic level shifter?

@Juraj ESP8266 GPIO pins are 5V tolerant.

You might want to put the breadboard power supply on the other end, so the + an - markings actually match and doesn't look like you just shorted everything.

Also that breadboard might have a split in the middle of the side rails.

Do a sanity check, connect pin 2 - 3 and see if the Arduino terminal echo back a char that you send.

@MatsK do you mean take off all the wires and connect ports 2 and 3 of arduino with the same code? Sorry for the beginner question!

I found the problem. It was the power supply. I tried the same with the 3.3 V from the Arduino. I´ve read that this is not recommended. Is there something extra I need to connect in order to avoid any problems?

Nice that you found the problem. But what I mean is by removing the wires from pin 2 and 3 on the Arduino and place a jumper directly from pin 2 to pin3 on the Arduino will verify that the softserial is working.

These are probably really stupid questions.  1. From the picture it doesn't look like the Arduino has any power?  Does it have power and is it 5v?  I had one of these power boards and it required 12V input to generate 5v and 3.3v.  If I gave it 5vIn it gave me 3.3V and 1.8V out.  Is your 3.3V really 3.3V?

I believe the reason you are not supposed to run the ESP off the Arduino is you might exceeded the current that the Arduino can supply, which will cause the ESP to reset.  The biggest current draw will be when the radio is transmitting, so you might get away with it.

In this website it is explained in step by step how to give connections and how to flash esp8266 to avoid garbage values 1. To flash ESP8266: https://mybtechprojects.tech/microcontrollers/esp8266/flash-esp8266-with-arduino/ 2. To connect esp8266 with arduino: https://mybtechprojects.tech/microcontrollers/esp8266/interface-esp8266-01-with-arduino/

You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.
Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.
[Edited to be less accusational, which was not the original intent]
[Update]
Please see the datasheet here:
https://www.mikrocontroller.net/attachment/231858/0A-ESP8266_Specifications_v4.pdf
The table in section 8.4.4 says that the maximum input voltage is 3.6V
Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V.  So does that mean the GPIO are safe up to 6V?
(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).

To me, it looks like the jumpers on his power supply are set to 3.3V.

SoftwareSerial: 115200 is valid. Ref.: https://www.arduino.cc/en/Reference/SoftwareSerialBegin

I´ve edited the post with a picture of the power supply. I´ve also tried changing the code to 9600 but still not working.

@MatsK - Sorry I worded that badly.  I have seen plenty of comments on here about comms between an Arduino and ESP failing at high board rates when using Software Serial.  I didn't mean to point a finger :)

@gre_gor - Are the Tx and Rx pins on the ESP 5v tolerant?  I know they are on NodeMCU type boards, but I don't know on the bare board.

No problem @CodeGorilla, I think the politically correct is to say"To use higher baud rates with Softserial isn't recommended!".

Regarding 5volt tolerant or not, this is a quite comprehensive article about it, https://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/

@MatsK - That's long :(  So in summary the official data sheet says that the GPIO pins work at 3.3v Max, an unofficial early datasheet reportedly says 5v, some people say 3v, some 3.6v, some 5v and one thinks it could be 6v.  There is a Facebook post reportedly from the CEO that says 5V (but I can't see this).  Personally I will stick to using level convertors, because an ESP may only be $2 but a lvlconv is only $0.2.
BUT don't use 5V for the power, that will smoke the flash chip. :)

Step 1: Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.
Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX.
Click Here for Necessary At Commands

I think you mean the 3.3V may not supply enough CURRENT (voltage is fine) for the ESP8266, especially if you try to use the WIFI on it.


text:
Software Interrupts in Arduino or nodeMCU
The code given below is an example code I found on the internet. This is to use my nodeMCU as a server. For my application, I believe that these lines of code...:
if (request.indexOf("/LED=ON") != -1)  {
            digitalWrite(ledPin, HIGH);
            value = HIGH;
          }
          if (request.indexOf("/LED=OFF") != -1)  {
            digitalWrite(ledPin, LOW);
            value = LOW;
          }

... from the below program should run thereby interrupting every processes.
 #include <ESP8266WiFi.h>

    const char* ssid = "Linux"; // SSID i.e. Service Set Identifier is the name of your WIFI
    const char* password = "0123456789"; // Your Wifi password, in case you have open network comment the whole statement.

    int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
    WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

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

      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP()); //Gets the WiFi shield's IP address and Print the IP address of serial monitor
      Serial.println("/");

    }

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

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

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      // Match the request

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

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one
      client.println("<!DOCTYPE HTML>");
      client.println("");

      client.print("Led pin is now: ");

      if(value == HIGH) {
        client.print("On");
      } else {
        client.print("Off");
      }
      client.println("

");
      client.println("<button>Turn On </button>");
      client.println("<button>Turn Off </button>
");
      client.println("");

      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");

    }

How can we achieve this kind of software Interrupt(s)?
PS: Timer Interrupt won't work -- I believe.

That doesn't need an interrupt.  Think about it, just check it right after you read it from the client.  So the response will be immediate.  It's not like it can suddenly become true at some other point without being read from the client.  You're already using a blocking read so if the first part of the message has arrived you'll stop right there and wait for it.  The loop should turn over really fast, keep it fast and non-blocking anywhere else and you can count on even if the message starts coming in immediately after your read the loop will make it back around to read again before the end of the message gets there.

+Delta_G I think I couldn't make my problem clear. When there are some other additional code (which are not shown here) within loop(), I think we do need interrupt. That's why we need a software interrupt.

Why do you think that?  How will either of those conditions ever become true except in concert with a read from the client?  If you think this other code causes some problem then please edit the question and post it.  But I stand by this answer.  The stuff coming in from the client is very very slow.  You have a lot of time between the time that the message starts the arrive and the point where it ends that you could do a lot of other things in that long time.

As long as you get back to the point where you read at some point during your message, your code will stop there and not do the other things until the message is complete since you use readString.  So the only thing that your interrupt could possibly ever interrupt is the next line after the readString command which is the section that you want to put in the interrupt.  If you think about the overhead of an interrupt vs just letting the code hit that next line, the interrupt would actually make your code slower and add more lag.

+Delta_G Thank you that seemed to work. But I still have one more problem: Because of these lines
if (!client) {
return;
}
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

the rest of embedded system project has become so slow. How can I run these code alongside my actual embedded system project?

The while(!client.available()) line says, stop right here and do absolutely nothing until we get some message from the client.  Then you use readString() which also waits until the transmission ends.  That's blocking code, it stops the program to wait on something.  If you don't want it to work like that you'll have to do a lot of rewriting.


text:
How can I send a number from a master and make the slave read it?
I am building a fan controller using an Arduino and a Raspberry Pi (the Pi is the master and the Arduino is the slave). The Raspberry Pi generates random numbers and I want the slave (Arduino) to be able to read the string of numbers and increase the current speed of a pwm fan by the amount read.
How I can read the bits sent over I2c as numbers to allow me to do what I want to do?

See I2C Anything.

If you are only going to send "random number" why not let the Arduino generate them instead and remove the Pi all together. https://www.arduino.cc/reference/en/language/functions/random-numbers/random/


text:
Serial input values only working for very short seconds
I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?
int light=9;

void setup() {
  Serial.begin(9600);
  pinMode(light, OUTPUT);
  }

void loop() {
  Serial.println("How long do you want the light on for (in seconds)?");
  while(Serial.available()==0){}
  int on_time = (Serial.parseInt() * 1000);
  digitalWrite(light, HIGH);
  delay(on_time);
  digitalWrite(light, LOW);
  Serial.print("The light was just on for ");
  Serial.print(on_time/1000);
  Serial.print(" seconds. ");
}

please include all information .... your code prints to the serial console ... what do you see printed out?

What Arduino do you have? On an Uno, an int has values -32,768 to 32,767. An unsigned int is from 0 to 65,535 (ie. it's only 16 bits). Try using an unsigned long instead of int to see if that helps.

Ok, that makes a lot of sense. I'll try that. Thanks so much! And yeah i have an Uno btw

It completely fixed my program, thanks so much!

"the LED never turns off" is not exactly true. It will turn off, but after a very long delay.

If you add Serial.println(on_time); right after int on_time = (Serial.parseInt() * 1000); you will see the problem. Once you enter the number 33 for example, the integer value printed is -32536. The Allowed data type for delay() is unsigned long, so the negative number is causing a problem.
Using Serial.println() judiciously can be very helpful when you are trying to debug a sketch.

Hi! Thanks for taking the time to help! I've just done as you suggested an yeah i saw the negative number. 2 questions: 1) Why is this happening? Shouldn't it just be 33x1000? I'm a total noob so i don't understand what "unsigned long" is. 2) How can i go about fixing this/avoiding this problem in the future?

On an UNO, the largest "number" you can store in a integer is 32767. 33 seconds times 1000ms = 33000, which is over the 32767 maximum, so the integer becomes a negative "number". Anunsigned long variable can hold a "number" up to 4,294,967,295. 2) To avoid this type of problem, arm yourself with knowledge. I found the examples that came with the IDE were very helpful to determine what variable types to use, and how to use them. Another source of information about variable types, functions, etc. is the Language Reference found here: https://www.arduino.cc/reference/en/.

That all makes sense. Thanks again!

@ThisUsernameHasBeenTaken: Re “Why is this happening?”: Since you are using a signed number, the most significant bit is interpreted as a sign bit. This is how two's complement arithmetic works.


text:
LED dimmer not fading out
I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?
int blue_led=10;

void setup() {
  pinMode(blue_led,OUTPUT);
}

void loop() {

  int voltage=0;

  for(int i=0;i<=255;i+1){

    analogWrite(blue_led,voltage);
    voltage=voltage+1;
    delay(8);
  }
   int volts=255;

   for(int i=0;i<=255;i+1){

    analogWrite(blue_led,volts);
    volts=volts-1;
    delay(8);
   }

}

your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)

i could be used instead of voltage and volts, couldn't it? I mean, is max voltage 255?

Sure, 'i' could be used, because 255 is indeed the maximum allowed value for the  PWM pins. But again, the 'i' in the OP's code will never go past '0', until the for() loop is fixed.
Here's a handy article about it...
https://www.allaboutcircuits.com/projects/using-the-arduinos-analog-io/

Ah i understand. I just made the changes and it works perfectly! Thanks so much!

Thanks for the explanation, Randy. @ThisUsernameHasBeenTaken, if the answer solved your problem you can mark it as accepted (see help center)

Just done :) Thanks

Also note that using delay is generally a bad idea. (Your code freezes until the delay time passes, so your Arduino can't do anything else during that pause.) You should get used to writing code that records the current value of millis() and waits for it to increment to a desired end value. Do a Google search on "Arduino blink without delay" for an explanation of that.