text:
ESP32: nRF24L01 receives no data
Using two, nRF24L01 with two, ESP32 DEVKIT V1. Trying to setup RF24 Library example, "Getting Started". Able to transmit on both nodes, however, there is no payload received when switching to receive while transmitting on both nodes.
SPI pins used:
MOSI = GPIO23,
MISO = GPIO19,
SCK  = GPIO18,
CE   = GPIO21,
CSN  = GPIO5,
IRQ  = No connection,
Vcc  = 5.0 V using piggyback adapter with 3.3 V regulator,
GND  = Ground.
Are the SPI pins used correctly for the ESP32 DEVKIT V1?
<script src="https://gist.github.com/Tech500/b57d4d356baaec48adc41196117c02aa.js"></script>
nRF24L01 Project for use with ESP32 DEVKIT V1
Details.txt
//Getting Started exammple:  Details Radio_0 and Radio_1.

RF24/examples/GettingStarted
Which radio is this? Enter '0' or '1'. Defaults to '0'
radioNumber = 0
*** PRESS 'T' to begin transmitting to the other node
SPI Frequency       = 10 Mhz
Channel         = 76 (~ 2476 MHz)
Model           = nRF24L01+
RF Data Rate        = 1 MBPS
RF Power Amplifier  = PA_LOW
RF Low Noise Amplifier  = Enabled
CRC Length      = 16 bits
Address Length      = 5 bytes
Static Payload Length   = 4 bytes
Auto Retry Delay    = 1500 microseconds
Auto Retry Attempts = 15 maximum
Packets lost on
    current channel = 0
Retry attempts made for
    last transmission   = 0
Multicast       = Disabled
Custom ACK Payload  = Disabled
Dynamic Payloads    = Disabled
Auto Acknowledgment = Disabled
Primary Mode        = TX
TX address      = 0x65646f4e31
pipe 0 ( open ) bound   = 0x65646f4e31
pipe 1 ( open ) bound   = 0x65646f4e32
pipe 2 (closed) bound   = 0xc3
pipe 3 (closed) bound   = 0xc4
pipe 4 (closed) bound   = 0xc5
pipe 5 (closed) bound   = 0xc6

-------------------------------------

radioNumber = 1
*** PRESS 'T' to begin transmitting to the other node
SPI Frequency       = 10 Mhz
Channel         = 76 (~ 2476 MHz)
Model           = nRF24L01+
RF Data Rate        = 1 MBPS
RF Power Amplifier  = PA_LOW
RF Low Noise Amplifier  = Enabled
CRC Length      = 16 bits
Address Length      = 5 bytes
Static Payload Length   = 4 bytes
Auto Retry Delay    = 1500 microseconds
Auto Retry Attempts = 15 maximum
Packets lost on
    current channel = 0
Retry attempts made for
    last transmission   = 0
Multicast       = Disabled
Custom ACK Payload  = Disabled
Dynamic Payloads    = Disabled
Auto Acknowledgment = Disabled
Primary Mode        = RX
TX address      = 0x65646f4e32
pipe 0 (closed) bound   = 0x65646f4e32
pipe 1 ( open ) bound   = 0x65646f4e31
pipe 2 (closed) bound   = 0xc3
pipe 3 (closed) bound   = 0xc4
pipe 4 (closed) bound   = 0xc5
pipe 5 (closed) bound   = 0xc6
Radio_0.ino

RF24 Library example "Getting Started":
/*
 * See documentation at https://nRF24.github.io/RF24
 * See License information at root directory of this library
 * Author: Brendan Doherty (2bndy5)
 */

/**
 * A simple example of sending data from 1 nRF24L01 transceiver to another.
 *
 * This example was written to be used on 2 devices acting as "nodes".
 * Use the Serial Monitor to change each node's behavior.
 *
 *  TX Code --Radio 0
 */

/*
  Coded for a ESP32 DEVKIT V1 board type to make use of a pair of
  nRF24L01+ 2.4 GHz. Transceivers
  SPI Pins used MOSI = 23, CE = 21, MSIO = 19, SCK = 18, CSN = 4
  This code is for Radio 0.
  William Lucid
*/

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

#define CE_PIN 21
#define CSN_PIN 5

// instantiate an object for the nRF24L01 transceiver
RF24 radio(CE_PIN, CSN_PIN);

// Let these addresses be used for the pair
uint8_t address[][6] = { "1Node", "2Node" };
// It is very helpful to think of an address as a path instead of as
// an identifying device destination

// to use different addresses on a pair of radios, we need a variable to
// uniquely identify which address this radio will use to transmit
bool radioNumber = 0;  // 0 uses address[0] to transmit, 1 uses address[1] to transmit

// Used to control whether this node is sending or receiving
bool role = true;  // true = TX role, false = RX role

// For this example, we'll be using a payload containing
// a single float number that will be incremented
// on every successful transmission
float payload = 0.0;

void setup() {

  Serial.begin(115200);
  while (!Serial) {
    // some boards need to wait to ensure access to serial over USB
  }

  pinMode(CE_PIN, OUTPUT);
  pinMode(CSN_PIN, OUTPUT);

  // initialize the transceiver on the SPI bus
  if (!radio.begin()) {
    Serial.println(F("radio hardware is not responding!!"));
    while (1) {}  // hold in infinite loop
  }

  //radio.setAutoAck(false);

  // print example's introductory prompt
  Serial.println(F("RF24/examples/GettingStarted"));

  // To set the radioNumber via the Serial monitor on startup
  Serial.println(F("Which radio is this? Enter '0' or '1'. Defaults to '0'"));
  while (!Serial.available()) {
    // wait for user input
  }
  char input = Serial.parseInt();
  radioNumber = input == 1;
  Serial.print(F("radioNumber = "));
  Serial.println((int)radioNumber);

  // role variable is hardcoded to RX behavior, inform the user of this
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

  // Set the PA Level low to try preventing power supply related problems
  // because these examples are likely run with nodes in close proximity to
  // each other.
  radio.setPALevel(RF24_PA_LOW);  // RF24_PA_MAX is default.

  // save on transmission time by setting the radio to only transmit the
  // number of bytes we need to transmit a float
  radio.setPayloadSize(sizeof(payload));  // float datatype occupies 4 bytes

  // set the TX address of the RX node into the TX pipe
  radio.openWritingPipe(address[radioNumber]);  // always uses pipe 0

  // set the RX address of the TX node into a RX pipe
  radio.openReadingPipe(1, address[!radioNumber]);  // using pipe 1

  // additional setup specific to the node's role
  if (role) {
    radio.stopListening();  // put radio in TX mode
  } else {
    radio.startListening();  // put radio in RX mode
  }

  // For debugging info
  printf_begin();  // needed only once for printing details
  // radio.printDetails();       // (smaller) function that prints raw register values
  radio.printPrettyDetails();  // (larger) function that prints human readable data

}  // setup

void loop() {
  if (role) {
    // This device is a TX node

    unsigned long start_timer = micros();               // start the timer
    bool report = radio.write(&payload, sizeof(float)); // transmit & save the report
    unsigned long end_timer = micros();                 // end the timer

    if (report) {
      Serial.print(F("Transmission successful! "));  // payload was delivered
      Serial.print(F("Time to transmit = "));
      Serial.print(end_timer - start_timer);  // print the timer result
      Serial.print(F(" us. Sent: "));
      Serial.println(payload);  // print payload sent
      payload += 0.01;          // increment float payload
    } else {
      Serial.println(F("Transmission failed or timed out"));  // payload was not delivered
    }

    // to make this example readable in the serial monitor
    delay(1000);  // slow transmissions down by 1 second

  } else {
    // This device is a RX node

    uint8_t pipe;
    if (radio.available(&pipe)) {              // is there a payload? get the pipe number that recieved it
      uint8_t bytes = radio.getPayloadSize();  // get the size of the payload
      radio.read(&payload, bytes);             // fetch payload from FIFO
      Serial.print(F("Received "));
      Serial.print(bytes);  // print the size of the payload
      Serial.print(F(" bytes on pipe "));
      Serial.print(pipe);  // print the pipe number
      Serial.print(F(": "));
      Serial.println(payload);  // print the payload's value
    }
  }  // role

  if (Serial.available()) {
    // change the role via the serial monitor

    char c = toupper(Serial.read());
    if (c == 'T' && !role) {
      // Become the TX node

      role = true;
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      radio.stopListening();

    } else if (c == 'R' && role) {
      // Become the RX node

      role = false;
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
      radio.startListening();
    }
  }

}  // loop

Radio_1.ino:
/*
 * See documentation at https://nRF24.github.io/RF24
 * See License information at root directory of this library
 * Author: Brendan Doherty (2bndy5)
 */

/**
 * A simple example of sending data from 1 nRF24L01 transceiver to another.
 *
 * This example was written to be used on 2 devices acting as "nodes".
 * Use the Serial Monitor to change each node's behavior.
 */

 /*
  Coded for a ESP32 DEVKIT V1 board type to make use of a pair of
  nRF24L01+ 2.4 GHz. Transceivers
  SPI Pins used MOSI = 23, CE = 21, MSIO = 19, SCK = 18, CSN = 4
  This code is for Radio 1.

*/

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

#define CE_PIN  21
#define CSN_PIN  5

// instantiate an object for the nRF24L01 transceiver
RF24 radio(CE_PIN, CSN_PIN);

// Let these addresses be used for the pair
uint8_t address[][6] = { "1Node", "2Node" };
// It is very helpful to think of an address as a path instead of as
// an identifying device destination

// to use different addresses on a pair of radios, we need a variable to
// uniquely identify which address this radio will use to transmit
bool radioNumber = 1;  // 0 uses address[0] to transmit, 1 uses address[1] to transmit

// Used to control whether this node is sending or receiving
bool role = false;  // true = TX role, false = RX role

// For this example, we'll be using a payload containing
// a single float number that will be incremented
// on every successful transmission
float payload = 0.0;

void setup() {

  Serial.begin(115200);
  while (!Serial) {
    // some boards need to wait to ensure access to serial over USB
  }

  pinMode(CE_PIN, OUTPUT);
  pinMode(CSN_PIN, OUTPUT);

  // initialize the transceiver on the SPI bus
  if (!radio.begin()) {
    Serial.println(F("radio hardware is not responding!!"));
    while (1) {}  // hold in infinite loop
  }

  radio.setAutoAck(false);

  // print example's introductory prompt
  Serial.println(F("RF24/examples/GettingStarted"));

  // To set the radioNumber via the Serial monitor on startup
  Serial.println(F("Which radio is this? Enter '0' or '1'. Defaults to '0'"));
  while (!Serial.available()) {
    // wait for user input
  }
  char input = Serial.parseInt();
  radioNumber = input == 1;
  Serial.print(F("radioNumber = "));
  Serial.println((int)radioNumber);

  // role variable is hardcoded to RX behavior, inform the user of this
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

  // Set the PA Level low to try preventing power supply related problems
  // because these examples are likely run with nodes in close proximity to
  // each other.
  radio.setPALevel(RF24_PA_LOW);  // RF24_PA_MAX is default.

  // save on transmission time by setting the radio to only transmit the
  // number of bytes we need to transmit a float
  radio.setPayloadSize(sizeof(payload));  // float datatype occupies 4 bytes

  // set the TX address of the RX node into the TX pipe
  radio.openWritingPipe(address[radioNumber]);  // always uses pipe 0

  // set the RX address of the TX node into a RX pipe
  radio.openReadingPipe(1, address[!radioNumber]);  // using pipe 1

  // additional setup specific to the node's role
  if (role) {
    radio.stopListening();  // put radio in TX mode
  } else {
    radio.startListening();  // put radio in RX mode
  }

  // For debugging info
  printf_begin();             // needed only once for printing details
  // radio.printDetails();       // (smaller) function that prints raw register values
  radio.printPrettyDetails(); // (larger) function that prints human readable data

}  // setup

void loop() {

  if (role) {
    // This device is a TX node

    unsigned long start_timer = micros();                // start the timer
    bool report = radio.write(&payload, sizeof(float));  // transmit & save the report
    unsigned long end_timer = micros();                  // end the timer

    if (report) {
      Serial.print(F("Transmission successful! "));  // payload was delivered
      Serial.print(F("Time to transmit = "));
      Serial.print(end_timer - start_timer);  // print the timer result
      Serial.print(F(" us. Sent: "));
      Serial.println(payload);  // print payload sent
      payload += 0.01;          // increment float payload
    } else {
      Serial.println(F("Transmission failed or timed out"));  // payload was not delivered
    }

    // to make this example readable in the serial monitor
    delay(1000);  // slow transmissions down by 1 second

  } else {
    // This device is a RX node

    uint8_t pipe;
    if (radio.available(&pipe)) {              // is there a payload? get the pipe number that recieved it
      uint8_t bytes = radio.getPayloadSize();  // get the size of the payload
      radio.read(&payload, bytes);             // fetch payload from FIFO
      Serial.print(F("Received "));
      Serial.print(bytes);  // print the size of the payload
      Serial.print(F(" bytes on pipe "));
      Serial.print(pipe);  // print the pipe number
      Serial.print(F(": "));
      Serial.println(payload);  // print the payload's value
    }
  }  // role

  if (Serial.available()) {
    // change the role via the serial monitor

    char c = toupper(Serial.read());
    if (c == 'T' && !role) {
      // Become the TX node

      role = true;
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      radio.stopListening();

    } else if (c == 'R' && role) {
      // Become the RX node

      role = false;
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
      radio.startListening();
    }
  }

}  // loop

Video confirming transmission; both radios

SPI pins are correct for ESP32 DEVKIT V1; I have it both transmitting and receiving now.
I swapped out all Dupont wiring longer than 10 cm, changed the channel with the radio.setChannel function to 125 on both transmitter and receiver, and added a 100 μF, 16 V electrolytic capacitor between the 5 V rail and ground.
Transmission successful! Time to transmit = 403 us. Sent: 5.96
Transmission successful! Time to transmit = 403 us. Sent: 5.97
Transmission successful! Time to transmit = 403 us. Sent: 5.98
Transmission successful! Time to transmit = 403 us. Sent: 5.99
Transmission successful! Time to transmit = 403 us. Sent: 6.00
Transmission successful! Time to transmit = 403 us. Sent: 6.01
Transmission successful! Time to transmit = 403 us. Sent: 6.02
Transmission successful! Time to transmit = 403 us. Sent: 6.03
Transmission successful! Time to transmit = 403 us. Sent: 6.04

Received 4 bytes on pipe 1: 6.25
Received 4 bytes on pipe 1: 6.26
Received 4 bytes on pipe 1: 6.27
Received 4 bytes on pipe 1: 6.28
Received 4 bytes on pipe 1: 6.29
Received 4 bytes on pipe 1: 6.30

Code Gists for nRF24L01, transmit and receive radios


text:
Two Arduino boards with I2C sensors
I have been searching the internet about how to transfer data from multiple sensors from one Arduino to another using I2C, but no luck. All the code and tutorials online focus on multiple slaves with one sensor.
The attached Fritzing is not my project, but my project involves 22 pressure sensors and I need to log their readings in Excel using plx, so the picture is just for demonstrating the idea.
The main idea is to transfer the sensors' data from the slave to the master over I2C.
Is this doable?

Do you know how to transfer one sensor's data over I2C?

yes i did it for one sensor

Then you can do it with more sensors. Just request (and send) more data.

if it is not too much to ask is there any example u can send me to follow?

Take your code. Where you request the data for 1 sensor, change that to request the data for more than 1 sensor. Where your code responds with the data for 1 sensor, change it to respond with the data for more than 1 sensor.

Your code is the example.

There's two basic ways of doing it.

Send a byte from the master to the slave first to select which sensor you want, then request the data for the currently selected sensor, or
Request lots of bytes from the slave and fill them in one at a time as the requests arrive.

The first way is the slow, but "I2C" way of doing it - basically each sensor is its own register in the slave, and you select which register you want to read from.
The second way is faster, but you have to keep track internally of where you are.
A good compromise is to implement "auto increment" which does both scenarios: if you send a byte it sets the current sensor to read from. Then each read returns the current sensor and increments the sensor number internally in the slave, so the next read will get the next sensor.
That way you have a way to "reset" the sensor index that you are reading from, and it's reasonably quick to get all the sensors, since you just need to do multiple reads after a single write.

Wire.begin(9);//9 here is the address(Mentioned even in the master board code)
Wire.onReceive(xxx);
void xxx(int bytes)
{
l = Wire.read();//Receive value from master board
Serial.print("Pressure 12= ");
Serial.print(l);
Serial.println(" PSI ");
}
this is the code i used to read data from slave for one sensor which is working fine
how to add registory for each sensor?

That looks like you're sending from the master to the slave, not from the slave to the master. You have it backwards.

Wire.begin(9);
Wire.beginTransmission(9);
Wire.write((byte)l);
Wire.endTransmission();
this is the code i send data from salve board to master

You are showing me code that is the complete opposite of what you are claiming in your question.

Is there any specific reason why you feel you need to do it with I2C? It's probably the hardest protocol to implement.

are there any alternatives?

Plenty. Probably the simplest to implement is using one of the UARTs on each board.  Serial1.print(analogRead(0)); Serial1.print(","); Serial1.print(analogRead(1)); Serial1.print(","); ... Serial1.println(analogRead(10));

will research on UART and how to use it Thank you

on the receiving end of ur code, how is it gonna look to store each sensor data?

https://majenko.co.uk/blog/reading-serial-arduino | https://majenko.co.uk/blog/splitting-text-c

Why not put all the sensors on one Arduino?

source: Stack Exchange

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

sort: votes


text:
utility/spi_com.h error when compiling Marlin for Arduino mega with Ramps 1.4
I am using win 8.1 and trying to load Marlin 2.0.x onto Arduino Mega with an attached Ramps 1.4 board fitted with 3 8825 Drivers. Unfortunately everytime I try to compile It concludes with the following error. Can anyone please help.
Alternatives for utility/spi_com.h:
[]ResolveLibrary(utility/spi_com.h)  -> candidates: []In file included from C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.cpp:23:0:C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.h:28:12: fatal error: utility/spi_com.h:
No such file or directory   #include <utility/spi_com.h>

compilation terminated.
Using library SPI at version 1.0 in folder: C:\Users\Dad\Downloads\arduino-1.8.13-windows\arduino-1.8.13\hardware\arduino\avr\libraries\SPI
exit status 1
Error compiling for board Arduino Mega or Mega 2560.

trying to load Marlin 2.0.x onto Arduino Mega

I have no specific knowledge of Marlin.
For the moment, I'm ignoring the fact that it seems to be looking for STM32 files which would seem to play no role on an Arduino Mega.
I cloned the Marlin github repo and found no mention of a file "MarlinSPI.h" in the 2.0.x branch.  There is however a MarlinSPI.h in tag 1.1.9.1
You appear to be working with the code for the wrong version (or branch) of Marlin.

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


text:
433MHz sending not receiving
I'm trying to send data using these cheap parts.
When I check the voltage on the data port of the transmitter, I see what I expect, 1.2 and 0.6 fluctuating while sending.
But when I check the receiver I get 0. I've got 3 of the sets and tried them all. Also tried it with running the transmitter on 11V for some extra power. I've added a LED to the transmitter to see when it transmits and I've added a not-so-good antenna to both while they are only 5cm apart during my tests.
Any advice would be appreciated.
Receiver
FS1000A with a LR433A
#include <VirtualWire.h>

const int led_pin = 6;
//const int transmit_pin = 12;
const int receive_pin = 11;
//const int transmit_en_pin = 3;

void setup()
{
    delay(1000);
    Serial.begin(9600);  // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    //vw_set_tx_pin(transmit_pin);
    vw_set_rx_pin(receive_pin);
    //vw_set_ptt_pin(transmit_en_pin);
    //vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(1000);  // Bits per sec

    vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    if (vw_get_message(buf, &buflen)) // Non-blocking
    {
  int i;

        digitalWrite(led_pin, HIGH); // Flash a light to show received good message
  // Message with a good checksum received, print it.
  Serial.print("Got: ");

  for (i = 0; i < buflen; i++)
  {
      Serial.print(buf[i], HEX);
      Serial.print(' ');
  }
  Serial.println();
        digitalWrite(led_pin, LOW);
    }
}

Transmitter
#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;

void setup()
{
  // Initialise the IO and ISR
  vw_set_tx_pin(transmit_pin);
  vw_set_rx_pin(receive_pin);
  vw_set_ptt_pin(transmit_en_pin);
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(1000);   // Bits per sec
}

byte count = 1;

void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','#'};
  Serial.println("sending");
  msg[6] = count;
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(1000);
  count = count + 1;
}

bro based on (You should be able to power the receiver + and GND I have one, which ran on 5v, I can't see if these are the same, and put a multimeter from GND to Data, and you should get about half of Vcc, ) he say
the problem is not with the module the problem is with the library

What I thought was the receiver turned out to be the transmitter. I've earned my noob medal now :)
The chip with the LR433A on it is the sending unit.
The code above and the wiring is all good!

I will, I have to wait a day to do that :)

Congratulations on your medal - I have a a pile of them this high ^

If you are not getting anything on the receiver, then the receiver is definitely the problem. These units will boost the gain until it get some signal, any signal.
You should be able to power the receiver + and GND (I have one, which ran on 5v, I can't see if these are the same), and put a multimeter from GND to Data, and you should get about half of Vcc, probably fluctuating a bit. If you look at the same with an oscilloscope, it should fluctuating wildly between 0 and Vcc volts. All of this should work without a transmitter, and without an Arduino (you will need a power supply for the receiver).
Note: this is from memory, I don't have mine here to test.
Once you are getting "random data" (background noise), you can progress to sending a signal.
Note that you should keep your "1"s and "0"s balanced to get a clear signal - check out Manchester encoding (this encodes a "1" as "1,0", and a 0 as "0,1", so there will be a perfect balance). You might also want to send a 1010101010 at the start - this gives the receiver a chance to adjust the gain to the correct level. Or, you can use some width-based encoding (e.g. "slow 1, slow 0" for a "1", and "fast 0, fast 1" for a "0").

When I put the multimeter to Data and GND on the receiver, the result is 0 fluctuating to -0 and you expect to see 50% of the Vcc input so around 2.5 Volts? I'll ask around for an osciloscope as I don't have one myself. Thanks for the advice on the signal encoding, I hope I can get to that soon.

I made a noob mistake as you can read below. Just wanted to let you know you are right about the half Vcc on the receiving Data+GND and thanks for your help.

In case anyone else sees your above comment, -0 means there is 0 volts flowing in the other direction. This is not uncommon when there is no power flowing through the wires, little random fluctuations will cause this. If there are less than -0 (e.g. -2.5volts), it means the power is flowing in the other direction (or you have the probes on your multimeter around the wrong way).

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


text:
Interrupt handler in library
This is my first library so feel free to burn me and vote this down :D
This is a library that provides me with Watchdog deep sleep on my ATtiny85 projects.
In the test sketch I use the watchdog timer's interrupt vector but I want to place this within the library. How can I do this?
I have tried to add this to the init method but that did not work out;
powernap.h:26: error: expected unqualified-id before string constant
     ISR(WDT_vect) {
Also; feel free to shoot at the rest of the library, I am here to learn.
Test Sketch
#include "powernap.h"

#define LED 0

Napper napper = Napper();

volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

void setup() {
  delay(2000);
  napper.setup(8); // configure watchdog timer
}

void loop() { // blink
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  delay(200);
  digitalWrite(LED, HIGH);
  delay(200);
  digitalWrite(LED, LOW);
  delay(200);

  napper.sleep(); // deep sleep
}

powernap.cpp
#include "powernap.h"

 #ifndef cbi
   #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 #endif
 #ifndef sbi
   #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

Napper::Napper() {

}

void Napper::init(float initial) {
//  volatile boolean f_wdt = 1;

//  ISR(WDT_vect) {
//  f_wdt=1;
//  }
}

void Napper::setup(int cycle) {
    byte bb;
    int ww;
    if (cycle > 9 ) cycle=9;
    bb=cycle & 7;
    if (cycle > 7) bb|= (1<<5);
    bb|= (1<<WDCE);
    ww=bb;

    MCUSR &= ~(1<<WDRF);
    // start timed sequence
    WDTCR |= (1<<WDCE) | (1<<WDE);
    // set new watchdog timeout value
    WDTCR = bb;
    WDTCR |= _BV(WDIE);
}

void Napper::sleep() {
    cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
    sleep_enable();

    sleep_mode();                        // System sleeps here

    sleep_disable();                     // System continues execution here when watchdog timed out
    sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

powernap.h
#ifndef Fader_h
#define Fader_h

#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
  #include "pins_arduino.h"
  #include "WConstants.h"
#endif

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <util/delay.h>

class Napper {
    public:
        Napper();

        void init(float initial);
        void setup(int cycle);
        void sleep();

    private:
        int flag;

};

#endif

To answer your actual question, you just have to define ISR(WDT_vect)
outside any function.
Now, for the general critique, let me start by quoting Antoine de Saint
Exupéry: “It seems that perfection is attained not when there
is nothing more to add, but when there is nothing more to remove.”
There are quite a few things to remove from your code, like unused
variables, parameters or methods. I understand that you may be tempted
to leave useless stuff in there anticipating that you may need it in a
future, extended version. But please, don't do that. Try to keep clean
and lean any code that you post in public, and only add extra stuff when
you actually need it.
I would remove most of the #includes from powernap.h. If the compiler
needs one of these to understand your .h, then live it there. If it's
only needed to compile your library, then it belongs to your .cpp.
Also, there is no point in making your library dependent on the Arduino
core, as you are using no core functionality. By removing this
dependency, you can make your library more versatile, as it can be used
both for Arduino and non-Arduino projects.
The line #ifndef Fader_h looks weird. Standard practice is to use the
name of the .h file, capitalized. Don't depart from common practice
unless you have some reason to do so.
I would also add static to your methods, this way they can be used
without having to instantiate an object, like in
Napper::setup(WDTO_4S);.
You are using three different syntaxes for setting and clearing bits in
I/O registers. Your code will look more consistent if you choose one and
stick with it.
I almost forgot... you have to make sure the timed sequence is done
atomically, i.e. it's not interrupted.
Below is a version of the library that implements the suggestions above:
powernap.h
#ifndef POWERNAP_H
#define POWERNAP_H

#include <stdint.h>

class Napper {
    public:
        Napper() {}
        static void setup(uint8_t cycle);
        static void sleep();
};

#endif  // defined(POWERNAP_H)

powernap.cpp
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/atomic.h>
#include "powernap.h"

// This interrupt is used only as a wakeup source.
EMPTY_INTERRUPT(WDT_vect);

// Configure the watchdog as an interrupt source.
// `cycle' should be an integer from 0 to 9, or one of the constants
// WDTO_XXS from <avr/wdt.h>.
void Napper::setup(uint8_t cycle) {
    uint8_t prescaler;         // prescaler bits in WDTCR
    if (cycle > 9) cycle = 9;  // largest supported value
    prescaler = cycle & 7;     // bits WDP2:WDP0 are right aligned in WDTCR
    if (cycle > 7) prescaler |= _BV(WDP3);

    MCUSR &= ~_BV(WDRF);  // clear this bit: it overrides WDE
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        WDTCR |= _BV(WDCE)    // start timed sequence
              |  _BV(WDE);
        WDTCR =  prescaler    // set new watchdog timeout value
              |  _BV(WDIE);   // enable watchdog interrupt
    }
}

void Napper::sleep() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();
}

Awesome, I will improve my library, thank you for being thorough.

It is hard to help you improve your library or code if you don't tell others what your code pieces are trying to do.
In general, you will have a piece of code that sets up the whole thing, a piece of code that will be executed in the isr, and other helper code pieces, like getting status and clear status, as appropriate.
I often use a function pointer that the user can hook to the user handler so my isr portion of the code is fixed. Just hook to different functions in the user space and you are ready to go.
Obviously other ways exist, each with their pros and cons.

Your general directions are all in the code. I do not know what a user hooking function pointers to handlers is..

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


text:
USB Driver for LGT8F328P Arduino clone
Where is the USB driver for LGT8F328P Arduino Nano clone downloaded from for Windows 10 64-bit?
When I plug in the LGT8F328P into USB, using IDE 1.8.13, it does not detect it. I think it is because there is no HOLTEK driver - wherever that is.
If you got this clone working on Windows 10 can you also mention what version of the Arduino IDE and what boards package (there's more than one for the LGT8F328P) you used and what Windows version you used.
The USB chip on the LGT8F328P clone board is a Holtek HT42B534 which is used as a  USB to serial interface

I don't have one of these, but I found a tutorial about them (though only in german), which used this board package.

the USB is not in the 328p. as with ATmega, there must be an USB chip on board. I guess it is the CH340 as on clones with ATmega

@Juraj it uses a holtek for the USB to serial interface-I added a bit more info to the question regarding your comment

So you need a driver for the HT42B534 for Windows 10? Doesn't the OS detect the chip automatically? (I would expect this from a serious OS.) What does the hardware manager say?


text:
Programming Arduino Uno R3 to trigger a relay once every 24 hours
I programmed an Arduino Uno R3 to trigger a relay once every 24 hours from the moment it is powered on.
I calculated milliseconds and used the function delay().
24 hours * 60 minutes each hour * 60 second every minute * 1000 milliseconds every second
so I used :
delay(86400000)

for 86 million and 400 thousands milliseconds.
Currently, I'm still testing it...
Will this work? If not, is there a better built-in function/library or even external library to do it?
The relay trigger doesn't have to be very accurate at the very exact time each day.
I don't need it to be very accurate, it can shift few minutes every few months or so, thats okay with me.
But how about after few months or years of use ? Will it shift the timing much?
I read somewhere about using millis() function
and others use an RTC (Real Time Clock) module.
I don't want to use anRTC module, I am looking for a programmatical solution.
OR will my previous method using delay() work for such a very high number of milliseconds?

“Few minutes every few months” is about 20 ppm. You can expect close to 1,000 ppm clock drift on the Uno. Even if you calibrate out the drift, frequency wander will likely defeat your calibration to worse than 20 ppm in a day or so. You really need an RTC for meeting your accuracy requirement. See Arduino clock frequency accuracy for a detailed experimental analysis on the frequency stability of the Arduino (the Uno has a resonator similar to the one on the Pro Mini).

So, No programmatical solution, it must be a hardware solution for this, by using an RTC external module or maybe by making my own pcb circuit installing a crystal oscillator on it and connecting it to the arduino digital pin output ?
And the link you posted is very useful thank you, I'm going to read it.
I don't want to use an RTC so i don't have to change the battery every while, Or can i just connect the battery socket to the arduino 3.3v dc power pin?
Thank you very much Edgar, Greatly Appreciated

The 3.3V pin of the Uno is a power output, you cannot power your Arduino through it. If you replace the Arduino by a bare ATmega on your own PCB, you can replace the resonator by a 16 MHz crystal oscillator. It may still drift too much, but the drift rate will be consistent and you can calibrate it out. Alternatively, clock the ATmega off its internal RC oscillator, and plug a clock crystal into the TOSC pins of its asynchronous timer. Used this way, the asynchronous timer is like an RTC built into the ATmega.

Thank you Edgar for your very informative inputs, contributions and your very kind help.
I will research your idea more deeply and try to apply it practically soon. and yes the 3.3 v arduino pin is power output i mean to use it to power the RTC module not to power the arduino, I found a local supply that have 3 different models of RTC modules, PCF8523, DS1307 and DS3231 and DS1302 IC only and DS1307 8 dip package IC, I made some research and found that DS3231 is the most accurate with high precision because it has temperature sensor that adjust any timing drift/shift periodically

Yes, the delay() will work, as will other methods based on the millis() counter. However, delay() will make it impossible to do something else in the meantime.
Look up Blink without delay for an example of how to accomplish such a delay while being able to do other things in your code while waiting.
Casting
When dealing with large numbers such as your 24-hour delay, make sure to explicitly cast those numbers as unsigned long, or expressing them with the "UL" extension (like for example 86400000UL). This explicitly tells C++ to expect an "unsigned long" (which in Arduino Uno terms is a 32-bit unsigned number).
In your case (with such an obviously large number), the compiler will automatically choose the right type. In other cases (for example, if you change the expression to 24*60*60*1000), the compiler will not automatically generate an unsigned long and you need to force it by changing the first part of the expression to an unsigned long: 24UL*60*60*1000 or, alternatively (unsigned long) 24*60*60*1000.
Accuracy
The accuracy of the timing will be dependent on the type of oscillator on your particular Arduino board. Many Arduinos or their clones use a Ceramic Oscillator that generally have an accuracy of about 0.1 to 0.5%, meaning a possible deviation of 43 seconds per day and as such maybe too inaccurate for your purposes. If your Arduino has a Crystal oscillator, it will be much more accurate (to something like 150ppm, meaning a maximum deviation of about 1 second per day under normal conditions).

Thank you very much StarCat
I have arduino uno R3 (revision three) and I see a rectangular crystal on the board, So I guess its as accurate as you described....1 second per day thats around 365 seconds ( 6 minutes) per year...so thats fine.
And I will use the UL Unsigned Long extension on my code..better, Even if it works with normal delay() without assigning this data type.
I Appreciate your input
And the article link you posted about doling multiple things at once while program wait is very helpful, Thank you very much

The "UL" suffix is not needed, as the compiler will pick a data type large enough to hold the value. It is needed though, at least for the first factor, if you want to write an expression like 24UL * 60 * 60 * 1000.

@EdgarBonet, That's true of course. My opinion is that explicitly casting, where appropriate, doesn't hurt and will prevent hard to find errors in cases where it's not so clear-cut (like in your example). I've expanded the explanation in the answer.

Update: I tested the project for a full 24 hours from 9:03 PM Wednesday evening since i powered the arduino on to the next day thursday evening and i noticed it shifted/delayed around 3 minutes, cause it triggered the relay at around 9:06 PM (so thats around 3 mins delay) so 3 mins shift * 30 days a month = 90 mins (an hour and a half timing shift each month) I'm going to test it for another 24 hours now and see...

delay() takes an unsigned long; I think what you do will work.
When in doubt, you could always do something like this:
for (int hours = 0; hours < 24; hours++) {
  for (int mins = 0; mins < 60; mins++) {
    for (int secs = 0; secs < 60; secs++) {
      delay(1000);
    }
  }
}

It will be wildly inaccurate though, because the clock is inaccurate and will also drift with temperature, made worse because a resonator is used instead of a crystal.
You will get nowhere near an accuracy of a few minutes per month this way, whatever "delaying" method you use; the hardware isn't up to it.

Thank you very much ocrdu
I have arduino uno R3 (revision three) and I see a rectangular crystal on the board, So I guess its more accurate?

As far as I know, the UNO R3 also has a resonator on the board for the CPU, and the crystal is used for the USB timing only. This may be different between revisions of the board. Still, even with a crystal, I doubt you will get the accuracy you want.

Hmm, Didn't know that, So the only solution is to use a different arduino board completely?
I just need the relay triggered once each day, thats all...doesn't have to be precise timing.

Well, what I would do is just try it with a time of, say, two hours (or however long you can be bothered to observe the thing), see if it is close enough, and if not, introduce a calibration factor in the code to compensate. Measuring equipment would make this an easier process.
If it turns out you can't properly adjust that way because of clock instability, you can always add a precise RTC module.
Primitive engineering, maybe, but worth a shot.

Re “I think what you do will work”: It will. delay() can handle up to ULONG_MAX milliseconds, which is about 49.7 days. 2. Re “introduce a calibration factor”: if the experiment is performed in just a few hours, this will likely work. But then frequency wander will defeat the calibration at longer time scales. You can expect the clock frequency to “random walk” with a typical √t law at time scales longer than a few seconds.

Hello Edgar, I tested the project for a full 24 hours from 9:03 PM Wednesday evening since i powered the arduino on to the next day thursday evening and i noticed it shifted/delayed around 3 minutes, cause it triggered the relay at around 9:06 PM (so thats around 3 mins delay) so 3 mins shift * 30 days a month = 90 mins (an hour and a half timing shift each month)
I'm going to test it for another 24 hours now and see...

@Felix0004: 3 minutes in one day is 3×60÷86400 ≈ 0.002, or 2,000 ppm. Kind of high, but still within the tolerance of a typical ceramic resonator.

@EdgarBonet, And after another 24 hours, there is another 3 minutes drift, it started @ 9:09 PM...so its kinda constant drift for 3 minutes each day, which equal an hour and a half each month, thats still alot yeah.

You could try enclosing the Uno in a temperature controlled "oven", say a plastic enclosure with a very low power heater (even a suitable resistor might do) and thermo sensor in with it. It should reduce some of the variation in the crystal frequency.

But i can't Apply the heat permanently to the uno, i wanted a permanent solution : )
Thank you JRobert


text:
Separate control unit from LEDs
I am using an adapter (12 VDC, 2A) and I want to be able to power an LED strip with it plus the control circuit.
The problem is that the Atmega328 reboots, but when I only power up the LED strip with that adapter and power the control circuit with an independent 5 V adapter everything seems to be alright.
I can't do that in real world; I need to ude the same adapter.
I attached a picture of what I am doing right now. Please help me fix this.
I am using a 7805 regulator to reduce the 12 V to 5 V.

How much current does the LED strip use?

What do you mean by "the Atmega328 reboots"? When exactly does it reset? And have you tried putting a big capacitor between the power lines of the LED strip? Changing the strip state also influences the power draw. When the strip suddenly draws way more power, the power supply might produce a short dip in voltage, which you can smooth out with that capacitor

And what kind of strip are you using? How exactly are you controlling it? Please show your circuit.

what exactly is your question? ... you did not actually ask one ... more than one question could be asked

easy: you need a dc adapter with more amps.

Why not use the barrel input connector and input 12VDC there, the filtering etc on the board will help. Also as dandavis stated you need a bigger power supply or remove about 1/2 of your LEDs.

what barrel input?

Without the "Schematic" (picture) how would you answer it, they were not when I answered it. You might also look at the dates.


text:
Running an Arduino without the computer
I am having trouble getting my Arduino Uno to run my code when I disconnect it from my computer.
I have a 9V battery to power it and it is turning on, however, it is not doing anything at all. What can I do to make it run the code when it is using the battery and not connected to the computer?

You should probably give some indication in the question on how you know it is behaving differently between battery power and usb power.  Also given that 9v are not particularly good batteries beyond their ability to produce 9v, you may want to say what else you have connected to the board.

If you use a 9V block battery, recycle it and buy better batteries. You could use a series of AA batteries

how do you know that the arduino is doing nothing?

Please provide more information. What is the schematics? What is the code?

What components do you have in your project? Specifically, what are you connecting to the 5V line?

I have four DC motors connected to the Arduino. They each have a basic circuit with one transistor, resistor, and a diode for each. As of right now the objective is just to get the motors to run while its not connected to the computer. They run perfectly when connected to the computer but when I try to connect the battery so that it doesn't have to be connected to the computer, which it need to be able to be, the Arduino is on but nothing is happening. Do you have any better batteries that you recommend over the 9V?

To get a useful answer on a power source, you'd need to say more about the motors themselves.  You may find it instructive to put a voltmeter on the 5V line and alternately the VIN pin (or battery directly) and watch what is happening to their voltages when you attempt to operate the motors.

Use a fresh 9V battery, or better, a proper power supply or some AA batteries in series, just to make sure the power supply isn't the problem.
BTW on some Arduinos (though probably not yours) it often pays off to check if there is a while (!Serial); or some such in the code. If there is, it is blocking code execution until the USB is connected and the serial monitor is opened.

A battery a day keeps the environment decay.

"For testing only". I never use primary cells myself.

while (!Serial); would have no effect on an UNO.

@timemage: People with different Arduinos will also read this Q&A without looking at the tag, so I thought it would be a good idea to include it.

@ocrdu: I was looking at more as UNO having been in the question, the while loop is thing is a more of a rabbit hole.  I suppose you could mark it as "for some boards this is also a problem."  I don't have really strong feeling about it really.  In case you're wondering, I didn't vote down your answer.

@ocrdu, Heh, I'd had a follow on this and saw your change come in.  I'm going to upvote this just to cancel out the -1 that, in my opinion, should not have been there anyway.

And Arduino should run the last program installed to it when you apply power to the barrel connector. IT powers up, does a reset, and begins executing the sketch that's installed.
As others have mentioned, the small rectangular 9V batteries have very low current output and total power storage. You will run a fresh 9V battery down to nothing in a short time with just an Arduino, and with other components also drawing power it will happen even faster. I suggest getting a ≥ 1 amp 7V - 9V DC transformer and plugging that into the barrel connector.
You need to tell us what components you are using in your project and their current requirements.
If you are just running a "bare" arduino and very little else then you should get like 24 hours out of a fresh 9V battery, as mentioned by @ocrdu

All pins together can't source more than 150mA. Why should he use a 1000mA power supply?

@Duncan-C: Could be it, but power consumption is not THAT bad; 500mAh will run some Arduinos that aren't doing too much for about 24 hours.

I did find some that are 9V 1200mA batteries would these suffice?

You mean 1200 mAh? (that stands for milliamp-hours. It tells you the total power storage capability of the battery. A 1200 mAh battery can put out 1200 milliamps for an hour. (Or 120 milliamps for 10 hours. You just multiply current by time).


text:
Weak Arduino output pins
I've been learning Arduino for a while, and for my next project I'm attempting to build a drone. When I tested the motors that I purchased before, they seemed to work fine using the PWM pins and I saw no need for a motor driver.
However, now, a week later, the PWM pins are much too weak. I've set them to OUTPUT mode and HIGH.
Should the basic digital output pins be able to run fairly small drone motors like mine?

"Should the basic digital output pins be able to run fairly small drone motors like mine?" -  lol, no, I don't think so. Before powering any electronic component, you should make really sure, that you don't exceed current limits. I guess you haven't checked, how much current your motors draw? It will save you a lot of frustration to be very careful and always check current limits first. And ocrdu is also right with the flyback diode.

The Absolute Maximum is 40 mA per pin, but you shouldn't go even close to that; max. 20 mA per pin is about where you want to be. Total current (all pins) shouldn't exceed 200 mA.
Only you know what current your "fairly small" motors pull, but you may have fried a few IO pins.
Also, you need flyback (or maybe bidirectional TVS) diodes and a few capacitors on your motors to keep noise and inductive kick-back away from your pins. Motor driver modules often have these installed, but your Arduino pins don't. Inductive kick-back can easily kill IO pins also.

Time to purchase another Arduino or use the other pins. Before you connect the new one you need to get a method of driving the motors. Keep in mind they are inductive and will reverse polarity and kick back a voltage that will keep rising until adsorbed. If you will be reversing them pick a MOSFET bridge to drive them. If just on/off/PWM pick a Logic rated avalanche rated N-Channel MOSFET with a high enough voltage and current rating. If your Arduino is 3V3 you need to be sure the gate will be on at about 2.5V. Connect all the grounds together and connect the source of the MOSFET to ground as well. Place something in the 25-50 Ohm resistor from the Arduino pin to the Gate of the MOSFET. Then connect the motor to the drain and the appropriate + supply. No diodes need as it has one built into the MOSFET designed for this. If you want the MOSFET off place something like a 10K resistor from the Arduino pin to ground. Remember a Power Supply the Arduino is NOT! While you are waiting on the parts go through several tutorials on the arduino and motors. There are some good ones and some not so good.


text:
PT2257 only gives me heavy buzzing sound
I have this project where I control a bluetooth audio module with an arduino. In this case, I have used an arduino nano. But then, I have been meaning to add volume control to the project so I use a pt2257. But the sounds that it gives to me is my audio plus heavy buzzing sound and no matter how much attenuation that I set the volume doesnt seems to change. Can anyone help me?
Here is the schematics that I use for the PT2257:

I have tried giving Vdd 5V from arduino, and also 5V from a seperate power supply. But it seems there is no difference.
Here is the code that i use:
    void setup() {
      delay(1000);
      Wire.begin();
      Serial.begin(115200);
    }
    void loop() {
      Wire.beginTransmission(Volume_address);
      Wire.write(0b011100000);    // set low attenuation
      Serial.print("result 1: ");
      Serial.println(Wire.endTransmission());
      delay(2000);
      Wire.beginTransmission(Volume_address);
      Wire.write(0b11111111);  // set full attenuation
      Serial.print("result 2: ");
      Serial.println(Wire.endTransmission());
      delay(2000);
    }

Here is the link to PT2257 datasheet if you need it
EDIT:
Here is how I connect CSR8645 Output to my active speaker, before I add a attenuation IC. It works like a charm like this, but I need to add a volume control.

Did you connect the ground of the PT2257 and your audio to the ground of your Nano?

I have connected my pt2257 ground to arduino ground. But i didnt connect the audio ground to arduino ground. Since I have csr8645 as the audio source and it has Lp, Ln, Rp, and Rn, which one should i connect to the ground? I use Lp as left audio signal and Rp as right audio signal, Ln as audio ground. So does that mean I have to connect Ln to the ground?

Yes, I would connect the audio Ln, Rn to ground. Not having them connected to a (common) ground would explain the buzzing sound (50 or 60Hz interference from the power grid, depending on where you lvie).

Connecting any output direct to ground is very bad. Do not do it. You would normally connect the Ln and Rn inputs of a differential amplifier to ground through capacitors if you are using a single ended source. You would never connect the output to ground! Using Rp and GND will give you half the amplitude of using Rp and Rn. Leave Rn and Ln disconnected.

So how should I connect the audio attenuation ICs with CSR8645 output? I have single ended active speaker to connect it to. So, without the attenuation IC I connect it like the schematics I add in the edits

many amps and BT audio chips use differential input/outputs. none of the inputs nor outputs are considered grounds.
the Lp(left,postivie) Ln, Rp and Rn on your audio chip should be connected to loads directly. Ln or Rn are not audio grounds. so you can't use simple POT volume controls or any processor or amplifier chip that doesn't support differential IOs. so, you can't use PT2257 in this circuit.
for better understanding here are two audio signal types:

the simple, well known one, which consists of GND and an audio IN per channel. you can use many amplifiers, processors (e.h. PT2257) and POT volume controls. and one end of the output (e.g. speaker) is connected to GND.
the differntial audio signal which consists of a GND and a pair of IN+,IN- per channel. you can't use the soulutions mentioned above. for example, if you wanted to amplify the output signal of the bluetooth chip, you have to use something like PAM8302, 2.5W mono class D audio amp per channel. note the IOs:

Firstly, thanks for your kind explanation. Secondly, if i want to do volume attenuation which IC/Module do you suggest me to use? I have been searching for attenuation ICs  that uses differential input. But I can't seem to find any that suits my usage.


text:
Which arduino will be suitable with bill acceptor
I want to connect a bill acceptor (protocol ID003) and 3 switches and an Ethernet shield to Arduino. I am building a system that accepts bill and pass on the information to our software. Which Arduino will be the best choice, we need something which will have lot of code and also communication should be fast.

ARDUINO MEGA 2560 REV3
ARDUINO DUE
Arduino Uno REV3

--Edit--
This is I want to create:
A bill acceptor connected with arduino. Arduino has 3 buttons. (1. Play button, 2. redeem cash button. 3rd is not necessary).
When user login on machine, I get the details of user account through an API.
When user inserts money in bill acceptor, it enables the play button and add money in users account (If user already has money in account, button will be enabled). User can play until his account is not empty (i.e. if user has 200 in account, he can play 10 times). User can earn or lose money.
I have to send this transaction detail through an API.
If user press redeem button, it will print a slip of account details (Total money in account)
I am using Python.
I need to know which arduino is suitable for this, Ethernet shield compatible with that arduino (I think I am going to use ARDUINO MEGA 2560 REV3, but I don’t know Ethernet shield compatible with this model).
Also I need some Idea how can I make this. This is first time I am using arduino and bill acceptor.

A "lot of code" isn't very specific; it's pretty hard to advise which board has enough memory. Same with "communication should be fast". Can you put any numbers to those? The Uno has about 28K of code space (at the assembly language level); it may be possible to translate that - very roughly - into lines of C++. They've shown serial speeds of 2M baud. On the other hand, a Mega isn't that expensive, has much more memory but probably similar serial capability. More details can get you a better answer.

Hi @JRobert, thanks for comment. I have edited question. Can you suggest something?

Is your board talking to Python on a PC or other device? Or do you mean to run Python on the Arduino board? If the latter, I expect you'll need more than an Uno. I use AtTinys, and Unos but keep one Mega available by for just this kind of project, where I don't know yet what resources I'll need. The Mega always has more than enough (for me, so far :), so I can get my project working right away, and decide later whether to port it to a smaller MCU.

Define 'lot of code', the Arduino Uno has 32 KB Flash, the Mega 256 KB.
Define 'fast', the Uno/Mega are 16 MHz, the Due 48 MHz
Three switches use 3 GPIO's, shouldn't be a problem on neither of them; the Mega has more GPIOs than the Uno, but both have plenty for your needs.
The Ethernet shield are available for all three
I don't know the 'bill acceptor', add a datasheet.

Conclusion: it depends on what is lot of code, and what is fast.

Hi, thanks for response, I have edited question. Can you suggest something?


text:
ATTiny85 433Mhz with sleep
I would like to micromize my Arduino project and move it to ATTiny85. The first step was using sleep functions because I just want it to run once a day. Now I need to connect the 433Mhz stuff but I'm getting into a fight with cores vs. libraries vs. missing functions.
No matter what core and library combination I pick, there always seems to be something missing.
/home/thijs/Documents/Arduino/libraries/VirtualWire/VirtualWire.cpp:260:18: error: 'WGM12' was not declared in this scope
     TCCR1B = _BV(WGM12) | _BV(CS10);

I have tried Tiny cores, high lowtech cores and Manchester and VirtualWire libraries. I don't want to dive into the libraries and make them 'suitable' for ATTiny because I have more than one project.
How do I approach this dependency problem?
[edit]
Found a better core here:
https://github.com/SpenceKonde/ATTinyCore

Did you check the error line? That is actually not for ATtiny85 as it does not have that Timer. It looks like there is something wrong in your setup of the IDE.

The error you posted has nothing to do with an Arduino core. This is just plain avr-libc stuff. In order to use this kind of functionality, you need to
#include <avr/io.h>

In the Arduino core, it is common to have this done by default. But if this is not the case with your chosen core, just add the #include yourself in the program.


text:
analogRead() hangs
With this code I try to send a measurement over 443MHz using RadioHead. All parts work but when combined they fail. This chip used is an ATtiny85.
The function 'measure' torpedoes the entire program. If it is used, it will compile but it will never run Setup or Loop. I know this because I use a Logic Analyzer and Software Serial. I can see the Serial Port, PB1, hanging high.
I would like to know what is so wrong about function measure that it undermines all code..
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <RH_ASK.h>   // local libs at
#include <powernap.h> // /home/thijs/.platformio/lib

#define TICKLE_ID 192

#define SENSOR1_PIN 2
#define SENSOR1_PWR 4
#define SENSOR2_PIN -1
#define SENSOR2_PWR -1

#define SOFTWARE_SERIAL_TX_PIN 1
#define SOFTWARE_SERIAL_RX_PIN -1

#define RADIOHEAD_BAUD 2000
#define RADIOHEAD_TX_PIN 0
#define RADIOHEAD_RX_PIN -1

struct tickle {
  uint16_t id = TICKLE_ID;
  uint16_t value1;
  uint16_t value2;
};

Napper napper;
SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);
RH_ASK driver(RADIOHEAD_BAUD, RADIOHEAD_RX_PIN, RADIOHEAD_TX_PIN);

void senddata(int hygro) {
  mySerial.print("Senddata");
  struct tickle package; // make a Tickle package
  package.id = TICKLE_ID; // hard-coded device ID
  package.value1 = 0; // any positive int up to 2^16
  package.value2 = hygro; // any positive int up to 2^16
  driver.send((uint8_t *)&package, sizeof(package));
  driver.waitPacketSent(); // wait for it ~Barney
}

int measure() {
  mySerial.print("Measure");
  pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
  pinMode(SENSOR1_PWR, HIGH); // turn on sensor
  delay(100); // wait for sensor to settle

  int i; // int for counter
  int data = 0; // data container

  for (i = 0; i < 5; i++){ // cumulate 5 measurements
    data = data + analogRead(SENSOR1_PIN);
  }

  data = data / 5; // avg of measurements
  pinMode(SENSOR1_PWR, LOW); // turn off sensor
  pinMode(SENSOR1_PWR, INPUT); // disable sensor
  mySerial.print(data);
  return data; // return avg measured value
}

void setup() {
  mySerial.begin(600); // 600 baud serial
  mySerial.print("Setup"); // logging the start
  driver.init(); // initialize the RadioHead library
  napper.setup_sleep(); // initialize the Napper library
}

void loop() {
  mySerial.print("Loop"); // start of loop
  int measurement = measure(); // measure data
  senddata(measurement); // send data
  napper.napminutes(1); // deep sleep for 1 minute
}

[EDIT]
I thought the problem to be this, and then to be that. This is how I debug, I start somewhere and work my way back. Currently it looks like my own library PowerNap is the culprit, I have tested with other Sleep code and it works. I can only be sure after more tests and isolated code running.

My guess is that whatever is attached to pin 4 causes the chip to overload?

thanks for the quick reply! I removed the sensor, should return floating analogue value now, still nothing, SoftwareSerial returns complete jibberish whenever I use the function.

@Majenko It might, if he'd actually turned it on. But there are just bunch of pinMode calls and no digitalWrite.

@KIIV So there is. I completely blanked those and just read the OUTPUT and HIGH parts ;) Brains are strange things...

With only 512B of SRAM you really really need to have all string constants in flash. Use the F() macro on all your strings.

DO you think it fails over my mistake of using pinMode where it should read digitalWrite?

I moved the Strings to Flash with the macro but I think there is some incompatibility somewhere because softwareserial now returns nothing. Changing the pinMode to digitalWrite starts the sensor now but it hangs during measurement..

The change you are seeing shows that memory certainly was an issue - maybe it still is. Reduce your program down to the bare minimum. I'd suggest removing the serial comms completely unless you really really really need them.

that did not help, now my code is not working AND I'm blind because of removing SoftwareSerial, which was also broken because I used the F() macro. Time to start over, again. I am uploading the Blink Example code now.

Let us continue this discussion in chat.

I'm voting to close this old abandoned question as incomplete and unanswerable because the asker has posted that their prime suspicion is now with code which is not included in the question but only linked at an external site, which is not in keeping with the rules of this site which require questions to stand on their own without relying on external references for the key parts.

Fine by me, it has been some time since I worked on this. I do not know what to do with my 'old' unanswered questions.

Interesting question but nothing seems wrong in the measure() function unless the mistake pinMode is used instead of digitalWrite. I suggest in the for loop keep a slight interval between the measurements. lets say about 50ms. if the problem still presets lets start the debugging. set a serial message in every critical point and pin point the exact location the code hangs.

analogRead() hangs

you started this journey thinking a particular routine (measure()) is the problem and you now are blaming analogRead() to be the source of your ills.
it will serve you much better for you to step back and ask yourself if your thought process is at fault here.
while you haven't provided much information on what it is that's not working, you have provided more than enough information to suggest that the issue is not measure() nor analogRead().
you may find this hard to understand now but debugging is far less about convincing yourself where the wrongs are. instead, it is about convincing yourself what you think right is wrong.

Offcourse my thought process is wrong, otherwise I would file a bug at ATMEL or Arduino :D I am not here to find a problem in the tech, I am here to identify the mistake I am making myself. Yes I am the weakest link. This is nice to know but it does not help regarding the question at hand.

Personally I think its a memory size issue, but the only real changes you need to make to measure is change pinMode to digitalWrite (as you have spotted) and personally I think you should remove the other pinMode statements and leave the pin setup the whole time, unless you are using it for something else.
int measure() {
  mySerial.println("Measure");
  pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
  digitalWrite(SENSOR1_PWR, HIGH); // turn on sensor
  delay(100); // wait for sensor to settle

  int data = 0; // data container

  for (int i = 0; i < 5; i++){ // cumulate 5 measurements
    data = data + analogRead(SENSOR1_PIN);
  }

  data = data / 5; // avg of measurements
  digitalWrite(SENSOR1_PWR, LOW); // turn off sensor
  // pinMode(SENSOR1_PWR, INPUT); // disable sensor - If you do this the "sensor" floats.
  mySerial.println(data);
  return data; // return avg measured value
}

if I replace the function measure() by '17' it works. But the function still does not produce a valid repsonse. The int from analogRead goes to uint16_t for the 'tickle' struct and then goes over the air as uint8_t? Maybe it gets lost in this type jungle?

It really sounds like you are just over the maximum memory you can use.  Remove myserial and call and it should work.  There doesn't appear to be anything wrong with your code.

it hangs on analogRead(), I can see it not hitting the sleep routine by watching my multimeter. something must be in the way of analogRead()

Put a delay of 10ms after the analogRead() call.

Did not help, it still does not hit the sleep function. Maybe I made a mistake in my Deep Sleep code in this lib; https://github.com/Thijxx/PowerNap

Print a serial message right after going into the for loop. just to make sure it executed the for loop and hanged on the analogueRead itself. If so try declaring the i and data variables out of the function.

@danialweaber - I'm not disagreeing with you, but why would declaring the variables outside the function make any difference? (Just want to learn.)

@CodeGorilla Theres no thumb of rule to use global variables or local variables one over the other. Regardless of the language here we are writing to a device whose memory is limited(few kbits). In these cases more likely so many global variables when accessed from several routines may lead to unexpected side effects. I just suspected if it was a a such issue because I didn't check his napper library for memory leaks. OP makes sure it hangs in the particular routing, So it was just a suggestion from me for testing.


text:
Arduino TFMini Lidar sensors and speaker
I have this code for the TFMini Lidar sensors and Speaker. I Need help figuring why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement? (see below plz).
And my code now it's only one sensor is working pins (4,5) I don't know why the three of them don't work together.   Thanks in advance.
I took this code from the internet My coding experience is basic .
rx[i] = TFMiniOne.read();
if (rx[0] != 0x59) {
  i = 0;
} else if (i == 1 && rx[1] != 0x59) {
  i = 0;
} else if (i == 8) {
  for (j = 0; j < 8; j++) {
    checksum += rx[j];
  }
  if (rx[8] == (checksum % 256)) {
    *distance = rx[2] + rx[3] * 256;
    *strength = rx[4] + rx[5] * 256;
  }
  i = 0;
} else {
  i++;
}

Here is the complete code:
#include "Talkie.h"
#include "Vocab_US_Large.h"
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfminiOne;
TFMini tfminiTwo;
TFMini tfminiThree;

Talkie voice;
const int Speaker = 3;

//Declaring variables and constants

SoftwareSerial TFMiniOne (4,5);    //(RX, TX)
SoftwareSerial TFMiniTwo (6,7);
SoftwareSerial TFMiniThree (8,9);

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if (TFMiniOne.available()) {
    // Serial.println( "tfmini serial available" );
    rx[i] = TFMiniOne.read();
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) {
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if (rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else {
      i++;
    }
  }
}

void setup() {
  pinMode(Speaker, OUTPUT);

  //Initializing
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  TFMiniOne.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
  tfminiOne.begin(&TFMiniOne);
  tfminiTwo.begin(&TFMiniTwo);
}

void loop() {
  int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while (!distance) {
    getTFminiData(&distance, &strength);
    if (distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
  }

  delay(100);

  if (distance > 30) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_F);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance > 20) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_L);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance < 15) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_R);
  } else {
    digitalWrite(Speaker,LOW);
  }
  delay(300);

Already asked on Stack Overflow: https://stackoverflow.com/questions/64886565/arduino-and-tfmini-lidar-sensors. Please do not cross post; remove either one.

I don't quite understand what you're asking. You seem to be asking "If I remove this code, why doesn't it work?" where the answer is simply "because you removed the code?"

I don't know why the three of them don't work together.

I already answered that question in my answer to your previous question.

why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement?

That code part is reading the data from the first SoftwareSerial interface. If you don't read this data (by removing this code part) you are not reading any data from the TFMini, thus you don't have any measurement. If you want measurements from the lidar sensor, don't remove the code part, that actually reads the measurements.
Besides that I will explain the complete function here in comments to the code. Before that, you should understand what the static keyword means here. Normal variables, that get declared inside a function, (aka local variables) will get destroyed, when the code reaches the end of the function. Variables marked with the keyword static will continue to exist and hold their value also after the function ended. They act a lot like global variables, though their namespace is local to the function (thus you can declare other variables with that name in other parts of your code).
void getTFminiData(int* distance, int* strength) {
  static char i = 0; // this counter variable denotes the position of the next to be received byte in the buffer rx.
  char j = 0; // temporary counter variable
  int checksum = 0; // will be used to calculate the checksum, so that it can be compared to the one send with the data
  static int rx[9]; // this is the receive buffer, where the received data will be put

  if (TFMiniOne.available()) { // When data is available on the serial interface, read one byte
    // Serial.println( "tfmini serial available" );
    // read one byte into the current position in the buffer
    rx[i] = TFMiniOne.read();

    // A valid message starts with two bytes of the value 0x59, so we restart, if the current message doesn't have that. (checking the first two bytes with these two if statements)
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) { // if we received 9 bytes (positions 0 to 8 in the buffer), the message is complete --> process it

      // Calculating the checksum by adding all bytes together
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }

      // Comparing the calculated checksum with the last byte, that was received, (which is the checksum)
      // as the checksum is only one byte, we calculate the modulo with 256, thus only leaving the number range 0-255.
      if (rx[8] == (checksum % 256)) {
        // The checksums are equal, so the data is valid and we can proceed
        // The values for distance and strength have two bytes. Thus we need to put these bytes together into one value.
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }

      // reset the counter, since we have a full message and can now receive the next message
      i = 0;
    } else {
      // increment the counter variable to the next position, if we are currently receiving the bytes of a valid message
      i++;
    }
  }
}

I hope this makes the code clearer. As already said the my previous answer, it doesn't make much sense, to first use the TFMini library (declaring the corresponding objects) and then doing the communication yourself. I would suggest, that you look closer into the TFMini library. Try the examples, that surely come with the library. Use the libraries functions to communicate with the sensors. That will make it way easier for you, since the library will do the communications for you.

I can't answer the first part of your question as I don't understand what you're asking.  However:

I don't know why the three of them don't work together.

That doesn't work for 2 reasons:

Your receiving routine specifically references only one TFMini serial port, and
It is impossible to receive from more than one SoftwareSerial port at a time.

If you want to use multiple units you really should choose a microcontroller that has enough hardware UARTs to do the job. The Uno is not a suitable board.
Try the Mega2560 or one of the myriad of 32-bit ARM or MIPS boards.


text:
Digital pin output voltage drops when driving a relay
I'm trying to trigger eight different 5 V relays using an Arduino Atmega 2560. The relays (70Ω coil) are powered by an external 5 V source, and I'm trying to trigger them through a driving stage which contains for each relay an NPN transistor (2N3904) and a 1 kΩ resistor directly connected to digital pin of the Arduino.
The relays in my application are supposed to be driven 2 by 2, not all of them at once.
My problem is that I don't succeed in triggering the relay with digital pins of my Arduino; once I connect it to the resistor, the voltage of the digital pins drops from 5 V to 0.4 V or less. The transistor needs only 7 mA to be triggered, the output current of the Atmega2560 pins is 20 mA max.
I tried with an external 5 V source, it triggers correctly showing 10 mA maximum of current through the driving stage.

I'm not sure I've followed everything, but I feel like I have to ask: how sure are you that your 1K resistor is really 1K?

@timemage it is 1kohms i did the conception.

A base resistor of 1kOhm at 5V will give you a max base current of 5V/1kOhm = 5mA, which is less than 7mA. That could prevent the transistor from working correctly (as you wrote, that it needs 7mA). have you tried with about 500Ohm? That would give you 10mA. Does the pin correctly output 5V, when nothing is connected to it?

Please show a schematic.

@chrisl i tried 500Ohms does not work either. the test i did with my 5V external source was with an 500Ohms, i got 10mA flowing through the resistance and the relay trigered. I did the test with 1kOhms i got 7mA.
Yes i have 5V ouput when nothing is connected.

Are you setting the pin to OUTPUT? You could be "activating" the pin with the internal pullup resistor otherwise, which would exhibit the symptoms you describe.

@Majenko yes i'm setting the pin to output and sending a digitalwrite high.

Without showing us your schematic (edit the question), you problem is not really understandable. e.g. do you set the resistor direct in series to the relay or did you add it to the base of the NPN transistor. You said the relay sees only 0.4 volt if the resistor is in place. That sounds like you have the following connections:  emiter of the transistor -->  resistor --> relay. That does not work.

@PeterPaulKiefer i just added a schematic in my post please look at it.

What is the value of the base resistor?  It looks like "16 Ohms".

There's a little arrow missing in your transistor.

@jwh20 the base resistor is 1k.

@ocrdu yes its an npn transistor

Yes, I know. There's still a little arrow missing, though. They aren't symmetrical.

@ocrdu yes you are right, but what information you need by this arrow ?

To see where you (think you) connected the emitter. Apart from that, it is missing and should be there in your drawing; it's that simple. Also, what isn't shown: is the ground connected to the ground of the Arduino? What is providing the 5V?

@ocrdu yes the ground is connected to the ground of arduino, and the 5V that is above is provided by an external power supply through a LM7805. the 5V connected to the resistor is provided by the arduino but the problem is that when i connect that 5V to the resistor, the 5V collaps. I made sure i have no short circuit.

You said: "the test i did with my 5V external source was with an 500Ohms, i got 10mA flowing through the resistance and the relay trigered. I did the test with 1kOhms i got 7mA." With 1kΩ and 7mA, 7V would drop across the resistor, plus about 0.7V BE drop, makes 7.7V. Where does that come from?

There is a very important information you gave in the last comment. You use a 7805 to stabilize the input voltage. In order the 7805 can work correct, it's input voltage must be at least about 7.5 Volt. How many volts does you power supply deliver?  That could be the problem. Also,  the Gounds of the arduino, the power supply, the 7805 and the cold end of the relay must be connected. They must all be on the same voltage level. And the little arrow of the transistor should be directed to the GND.

Your circuit will no longer work. The original transistor you used was a NPN, you have changed it to a PNP connected somehow as a low side driver.  It is important to show the emitter, as it tells us what type of transistor it is, leaving it out as you have done causes many of us to assume you have done it correctly ie the emitter is connected to the ground.  Here is a Copy of a circuit from electronics-tutorials that uses a simple MOSFET: https://www.electronics-tutorials.ws/blog/relay-switch-circuit.html Note the 10K resistor from the port pin to ground, that guarantees it will be off during reset and setup.

Good Job, you are right on, the transistor is rated at 200 mA which is adequate for the job. The flyback diode will protect your system and the transistor. the drain source drop would be maybe 0.01V on a bad day depending on the RDSon. You will probably need a little lower value base resistor depending on the gain of your transistor.  I would use something between 220 and 510 ohm. It should work fine. Using a darlington would hurt you instead of the ~.7 volts drop across the collector it would become about 1.4 volts, leaving the relay with 3.6V assuming you are actually getting 5V. My preference would be a small logic level avalanche rated MOSFET. Use a 50 Ohm resistor in the gate circuit and it will be just fine.   Use something like a 10K pull down resistor between the gate and source, that will guarantee that it will be off during reset.

Why do you need any gate resistor at all with a MOSFET? They have capacitive inputs, and draw almost no current.

When the gate pulse starts, the capacitive input will appear as a short to the output pin (for a few nanoseconds). The gate resistor limits the current at that time. There is a lengthy discussion about this on the Arduino Forum which you might find interesting.

To prevent oscillation, it does not happen on all circuits but a good design practice. This happens because of the miller capacitance effect during the time the channel in enhancing.

If the coil is 70 ohms and it's driven by 5V, it should draw about 5/70 = 71 mA.  That's pushing the 2n3904 a bit hard, and doesn't even account for inductive effects. (It's a small-signal transistor.)  Do you have an NPN power transistor to try, just as a test?  If its current gain (beta) is too low, use a Darlington configuration by combining it with your 2n3904.  (2n3904 base from digital out resistor, emitter drives power NPN base directly, both collectors are connected together to the bottom of the coil, and the power NPN emitter is the effective emitter of the just-created "super transistor" with high beta and power handling.)  Be sure to use an anti-kickback rectifier (1n4001)across the relay coil.

sorry i did a mistake, its actually a 5V relay, it means 71mA through the relay. taking in account the 2N3904 gain i would have arround 7mA through the transistor this is why im using a 1k resistor.

Just to be sure:  The relay coil must be between +5 and the collector, with the emitter grounded.

yes i just added a schematic please look at it.


text:
ATtiny85 LM75 I2C
I would like to read temperature from a LM75 using the ATtiny85 running a core by SpenceKonde and utilizing the TinyWireM library.
My Logic Analyzer does not pick up any I2C communication, when I connect it to an Arduino Nano, it works fine. On the Nano, there is no need for TinyWireM so that's a big difference.
Therefore I conclude that the ATtiny85 is not speaking the right I2C slang to the device.
I also use SoftwareSerial and this works fine. It is visible on the Logic Analyzer.

The LM75 library is not made for ATtiny or TinyWireM, I replace the Wire references in-place by TinyWireM reference.
Should it be possible to 'just' replace Wire by TineWireM in the library and could I expect some meaningful data this way?
[updated code]
#include <Arduino.h>
#include <TinyWireM.h>
#include <LM75.h>
#include <SoftwareSerial.h>

#define SOFTWARE_SERIAL_TX_PIN 3
#define SOFTWARE_SERIAL_RX_PIN -1

LM75 sensor;
SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);

void setup() {
  TinyWireM.begin();
  mySerial.begin(2400);
  mySerial.print("Starting..");
}

void loop() {
delay(1000);
mySerial.println("SO");
mySerial.println(sensor.temp());
delay(1000);
}

Could you post your code?

I have added te code I use to test

Looks like the setup() is missing a call to TinyWireM.begin(). Also do not forget pullup resistors.

The TinyWireM.begin() is part of the library and I have the pull-ups, this setup works on an Arduino Nano

i2c is fairly easy to implement, either hardware or software. so you may find it beneficial to just write your own.

@Thijs The setup cannot work on Nano as it does not support USI which is the ATtiny hardware module.

Use LM35 which is analog.

The current ATtiny core includes a Wire library for the USI hardware used in the Tinys. This way you don't need to modify the LM75 library which is error prone.

Thanks, that piece of the code went missing when I edited the question (6 months ago). Problem remains.

Might help if you update the code to what you're actually using. Keep in mind that you won't see anything in the resolution you've chosen in the logic analyzer as I2C is about 50 times faster than the serial.

I updated the six months old question you answered with the code I might have used back then. But please tell me more about the speed of I2C.

Hi and welcome to the Arduino SE community. Please expand on your answer. You have identified some issues but please update your answer with how to resolve these issues. For example you could demonstrate the solution with some snippets of code and an explaination of how it fixes the problems the OP is having.

This is an old post I know but hopefully this information is helpful to someone. I modified the lm75 library by replacing all instances of Wire with TinyWire and as above no go, but turns out a 10k pull up on SCL / SDA is a necessity for the attiny 85. For whatever reason i2c works fine on an arduino UNO without pull ups but not on an attiny 85. So in short, add pull up resistors and it works. Bonus potato grade picture of attiny, LM75 and display module showing temperature.

hi Tom, thanks for the reply and the great picture :D could you please share information about your code? what library and core you used for example. I’ll try it out but I think I had the pullups back then..

I pretty much just used the lm75 and TinyWireM library, made a copy of the lm75 library, renamed it to lm75tiny and replaced any instances of Wire with TinyWireM. Ended up with this:
#include <TinyWireM.h>
#include <lm75tiny.h>
TempI2C_LM75 termo = TempI2C_LM75(0x49,TempI2C_LM75::nine_bits);
Then read temperature like so:
int temp = termo.getTemp();
Only other gotcha is the address of the lm75 needs to be confirmed and updated for whatever sensor you are using. I think the default is 0x48 but my sensor was 0x49.


text:
ATTiny85 VirtualWire AnalogRead 1
My ATTiny85 is connected to a 433 transmitter and an analog sound sensor. The 433 is working fine (using VirtualWire) but when I send the reading from the sensor all I receive is a 1.
What I would like to receive is the value between 0 and 1024 like when I print the sensor to serial. I cannot check it because the ATTiny85 had no serial out.
My code is a combination of snippets I found online, I am not happy with all the magic to format the data that needs sending. I would also like to send "Reading: 637" in stead of just the number but I find the concatenation Google results extremely complicated.
Should this code send the sensor data like 672?
Could there maybe be some Fuse setting blocking the AnalogRead?
#include <VirtualWire.h>

const int transmit_pin = PB0;
const int sensor_pin = PB4;
int sensor_data;
char sensor_msg[4];

void setup()
{
  vw_set_tx_pin(transmit_pin);
  vw_setup(2000);
}

int count = 1;

void loop()
{

  sensor_data = analogRead(sensor_pin);
  itoa(sensor_data,sensor_msg,4);
  vw_send((uint8_t *)sensor_msg, strlen(sensor_msg));
  vw_wait_tx(); // Wait until the whole message is gone
  _delay_ms(1000);
  count = count + 1;

}

Receiver Code as requested
This is a Pro Mini (clone) and it has an LCD attached so I can see what is going on.
#include <VirtualWire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

const int receive_pin = 11;
char* testje;
void setup()
{
    delay(1000);
    Serial.begin(9600); // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    vw_set_rx_pin(receive_pin);
    vw_setup(2000);  // Bits per sec

    vw_rx_start();       // Start the receiver PLL running

    lcd.init();
    lcd.backlight();
    lcd.home();
    lcd.clear();
    lcd.print("hello");
    delay(1000);
    lcd.clear();
}

void loop()
{
  char buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)) {
    int i;
    // Message with a good checksum received, print it.
    Serial.print("Got: ");

    for (i = 0; i < buflen; i++) {
       Serial.print((char)buf[i]);
    }
    Serial.println();
    Serial.println(buf);
    lcd.clear();
    lcd.print(buf);
  }
}

sensor_msg should be 5 bytes long not 4, but other than that it looks fine. What is your reception code? Maybe the bug lies there?

Actually, one thing i just noticed. The third argument of itoa should be 10 not 4. That argument is the base you want to represent the value in.

thanks, I've changed it. also tried HEX but 1 stays 1 obviously :D I will find an extra Pro Mini to test the sending of the data from a Pro Mini, will update my question afterwards

I would double check the pin numbers for the attiny. They look like port bit numbers but that might just work by chance.

Ok from a Pro Mini it all works. So the code is ok and the receiver is ok. About the pins; I use PB0 to send data, so PB4 must be PB4 right? It's not possible to name it A2 but it 'should be' that pin. I will make a blinking LED on PB3 to be sure :) maybe I can have it blink analogeRead/100 or something..

Tusen tack! It was the pin number after all... PB0 for physical pin 5 and 2 for physical pin 3. Awesome! Please convert something to an answer so I can give you credits :) Now I have to stop my LED routine because it is trying to blink the value 1023 :)

I would double check the pin numbers for the attiny. They look like port bit numbers but that might just work by chance.
const int transmit_pin = PB0;
const int sensor_pin = PB4;

A quick double check with the attiny/pins_arduino.h give:
// ATMEL ATTINY45 / ARDUINO
//
//                 +-\/-+
// Ain0 (D5) PB5  1|    |8  Vcc
// Ain3 (D3) PB3  2|    |7  PB2 (D2) Ain1
// Ain2 (D4) PB4  3|    |6  PB1 (D1) pwm1
//           GND  4|    |5  PB0 (D0) pwm0
//                 +----+

As you have found they should be defined as:
const int transmit_pin = 0; // Physical pin 5
const int sensor_pin = 4;   // and pin 3

This type of issue could be avoided by using strong data typing and object oriented design. Please see for instance Cosa ATtinyX5.hh and GPIO.hh.
Cheers!
Here is something that does basically the same as the sender. Cosa supports attiny and Arduino boards "out-of-the-box".


text:
ATMEGA32u4 Arduino Bootloader Issues
I've been struggling with this issue for a few days on and off now.  I made a custom PCB (schematic) for a smaller Arduino Pro Micro and it works - mostly.  The only issue I had was that the pins on the USB connector were backward, but when I soldered on a USB cable everything worked as expected.
I then made a new board (schematic) with the following changes:
 - Fix the USB connector
 - Changed two of the GPIOs that were brought out to pins (from D4 and D17 to D6 and D9)
 - Added an onboard LED connected to D8
 - Removed the jumper on HWB pin
I have been able to burn the bootloader using both an Arduino Uno and with an AVRISP mkII.  When I plug the micro into the computer the first time it is recognized as an "Arduino Micro (COM6)".  Then I try to upload the Arduino example Blink.ino sketch - and that works too.  In the process the IDE forces the reset and in device manager I can see the "Arduino Micro bootloader (COM7)" replace the micro on COM6.  The LED does begin to blink but in device manager it remains as "Arduino Micro bootloader (COM7)".  When I try to upload another sketch to this port it fails (as I would expect) because it cannot force the reset; presumably because the bootloader is already active.  So I unplug it and try again.  It shows up as "Arduino Micro (COM6); all looks good but when I try to upload it cannot force the reset, tries to upload to "Arduino Micro (COM6)" and fails (I assume because it is not entering into the bootloader).
When I double tap the reset pin or connect to the arduino using a baud rate of 1200 the micro does reset (as expected) and the light stops flashing so I suspect the bootloader is being executed - but on device manager it remains as "Arduino Micro (COM6)".
If anyone has any ideas I'm all ears.  Normally I do not have to fight with Atmel hardware like I have on this issue.

The bootloader on the chip only waits a few seconds for an upload request. If you start the upload within this time the things will happen as you expect them. If the time is over the bootloader stops listening on the serial port and frees it for the program.  You can reenter the "boot time interval" by resetting the chip. But as you have no button ( ;-) ) this would be difficult. A UNO for example has an extra USB to Serial converter chip that can perform this reset before the programming starts. Can you add an external reset button and try pressing it and start the programming immediately?

If you ask why the first upload was possible: As long as there is no program on the chip, the bootloader has no reason to give up control to a program. Then it waits forever for an upload.

That second comment makes sense (kinda what I figured).  When I reset (wire soldered to the resistor-next board will have a pin for RST) the chip the LED I connected for the blink turns off for 8 seconds.  (This is the boot time interval for the Arduino Micro bootloader I believe.  To the computer it is still seen as "Arduino Micro (COM6)" - not bootloader.  When Arduino IDE attempts to connect to the programmer (LED still off) it errors out.

8 Seconds sounds reasonable. It depends from where you got the bootloader, but the device name  "Arduino Micro" is the correct string for the caterina version that is chosen automatically by the IDE.  I found another thread that could be the solution but I don't understand why. Please see  https://arduino.stackexchange.com/questions/57651/arduino-pro-micro-bricked.

Perhaps this is also interesting: https://www.eevblog.com/forum/microcontrollers/reinstall-bootloader-for-an-arduino-pro-micro/ That's also a good read, if you use a linux box as workstation (like me).

It seems like the bootloader is not connecting via USB for some reason.  I can cause the chip to reset by open/closing a COM connection at 1200 baud.  It appears to be entering the bootloader section of flash because the LED stops flashing.  Same thing happens when I double tap the reset button.

The issue I am having a problem wrapping my head around is that I have two versions of this board; one works, one doesn't. Using Atmel Studio I can verify that the flash, fuse and lock bits are all identical. I updated the question with both schematics.


text:
Trying to connect to WiFi on ESP32 using credentials from SD card
I am trying to connect to WiFi on an ESP32 using credentials I stored on an SD card. I am able to read and parse the credential and printing them to the serial monitor shows that the SSID and password are correct, but it is not connecting to WiFi. When I hardcode the WiFi credentials it works. What could I be doing wrong?

write a sketch that gets the SSID and password from the SD card and compares them to hardcoded values ... that will tell you if they are the same ... also, print out the length of each of them

It would really help if you showed the code you are using.

thanks i was able to figure it out i had to find a way to convert the string to a const char* this way:  WiFi.begin(ssid.c_str(), pass.c_str());

I use the NVS partition to store NON VOLATILE information.
I use this library: NVS library
You can save like string and restore after reset/off.
Example:
#include <Arduino.h>
#include "ArduinoNvs.h"

void setup() {
    NVS.begin();
    Serial.begin(115200);
    // write to flash
    String set_SSID = "WIFI_name";
    NVS.setString("nvs_wifi_name", set_SSID ); //upload 1 time. after comment this line and upload again **
    // read from flash
    String get_SSID = NVS.getString("nvs_wifi_name");
    Serial.printf("Wifi name stored %s\n", get_SSID);
}

void loop() {}

This doesn't answer the question.


text:
TX, RX, ON, L LEDs were red at all time
Before seeing this error I did a project with my Uno board using a Bluetooth module.
After that, when I powered the board to upload another program, 4 LEDs (L, TX, RX, ON) went red without blinking.
So now, every time when I power up my Uno board, without any connection with any of the pins previously mentioned, the 4 LEDs are red coloured all the time.

are you able to upload something, like a "blink" sketch to board ?

There may be good reasons, that the LEDs are on. That's not directly an error. Are you still able to upload programs? What happens, if you upload the blink example?

When I tried uploade the blink example it's not uploading to the board,it says there a touble shooting problem.

Please give us the full error message (add it to your question by editing it)

If the LEDs are red then it's not a genuine Arduino. If it's not a genuine Arduino then all bets are off as to what happened.

If you can upload sketches, I don't think it is that big of a deal but if you can't, check the TX and RX pin tracks since if those tracks are shorted, they can keep the indicator lights on for ever due to the Serial code on the Arduino. To get further help, please tell me what happens if you try uploading code.