text:
Arduino Nano BLE 33 Sense receives but not able to transmit data to XBEE Pro S2C
This is my first time asking a question so I will try my best to be precise and detailed.
I had recently started to work on a project that requires me to establish a wireless communication between two XBEE Pro S2C modules for the purpose of sending data of the sensors present on the Arduino Nano BLE 33 Sense.
What I did so far:
One of the XBEE (XBEE 1) is connected to my laptop using one of the USB-port, and the other (XBEE 2) to Arduino. The Arduino is also connected to the same laptop using another one of the USB ports. Using the XBEE and Arduino pinout diagrams, I connected Vcc, Dout, Din and GND of XBEE 2 to 3.3V, D3, D4 and GND pins of the Arduino respectively. Both the XBEES have been configured using XCTU software and are operating in AT mode. The XBEES are able to talk to each other on the XCTU console if I directly plug both of them into the laptop using the USB ports.
To check and establish a serial communication between the XBEE 2 and Arduino, I wrote the following sketch on Arduino IDE and uploaded it:
int received = 0;
#include<HardwareSerial.h>
UART mySerial(digitalPinToPinName(4), digitalPinToPinName(3), NC, NC);
void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  while(mySerial.available())
  {
    received =mySerial.read();
    if(received == 'a')
    {
      Serial.println("Character Received");
    }
  }
}

Now, when I type the character 'a' in the XCTU console of XBEE 1, the XBEE 2 is able to receive it wirelessly and Arduino prints - "Character Received", on the serial monitor as expected. The TX of the adapter for XBEE 1 and the RX of the adapter for XBEE 2 also blinks at the same moment, confirming that the character is being sent by the XBEE 1 and it is being received by XBEE 2 for the Arduino to print.
The Problem:
Now, I uploaded the following sketch to do the reverse job, so that XBEE 2 sends the data and it appears on the XCTU console of XBEE 1:
#include<HardwareSerial.h>
UART mySerial(digitalPinToPinName(4), digitalPinToPinName(3), NC, NC);

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

void loop() {
  mySerial.print("a");
  delay(1000);
}

This sketch does not print anything on the XCTU console of XBEE 1. I checked the connections and re-uploaded the sketch but it still showed nothing. I included the printing line inside a while-loop,
while(Serial.available()){
   mySerial.print("a");
}

so that I can manually type in a character into the serial monitor using Arduino IDE, but that also did not work. I also noticed that the respective TX and RX of the adapters also did not blink, meaning that XBEE 2 is not able to transmit the character only.
I cannot figure out what I am doing wrong and I spent hours to resolve this issue. I also tried changing the Din and Dout pins of XBEE 2 to RX and TX pins of the Arduino but that also did not work, although I think that's because the RX and TX are already being used by the Serial Connection between Arduino and laptop.
Any help to point me into the right direction would be greatly appreciated.
Thanks a lot!
Some points:
I came to know that SoftwareSerial library isn't available for the version of Arduino that I am using and for this reason I am using the UART instruction:
UART mySerial(digitalPinToPinName(4), digitalPinToPinName(3), NC, NC);
based on the discussion in this forum. I also use CP2012 XBEE explorer as adapters for XBEES.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.


text:
adc arduino using reference voltage to read stable/constant lithium battery voltage

I want to read my lithium battery voltage.

I WANT TO CREATE A FUNCTION TO READ MY 3.7~4.2V,1200mAH BATTERY VOLTAGE THROUGH A MICROCONTROLLER (ARDUINO OR ATTINY44).

THEN I WANT TO CALL THE CREATED BATTERY FUNCTION IN THE FORMULA TO READ PRECISE SENSOR VALUE
 int voltage = ((CALLING BATTERY FUNCTION) * (READ SENSOR VALUE)) / 1023;

I AM USING INTERNAL REFERENCE VOLTAGE 1.1V.
NOTE: I want the whole system to run on lithium battery ( I am just creating a prototype on Arduino, if it works, ill be editing the code for my attiny44 using 8mhz external crystal).
 void setup(){
   Serial.begin (115200);
 }

 void loop() {
   //REFS1 AND REFS0 to 1 1 -> internal 1.1V refference
   ADMUX |= B11000000;
   //We read A1 (MUX0)
   ADMUX |= B00000001;
   // Start AD conversion
   ADCSRA |= B11000000;
   // Detect end-of-conversion
   while (bit_is_set(ADCSRA,ADSC));
   float val = ADCL | (ADCH << 8);
   val = val * 5.7; //Multiply by the inverse of the divider
   Serial.println(val);
 }

This code is working but it is reading from analog Pin. Is there any possibility to do it without using AnalogPin because I dont have any spare pin on my attiny.

@jsotola Done, Thanks

The answer is probably no. You cannot do anything without using pins. You need a pin to interact through. You cannot interact through thin air. So you need to get a bigger Attiny

okay so you mean that it is impossible to get constant battery output using AREF pin we need analog pin to do that. is that what you mean

You wrote, that you don't have any spare pins. That would mean no AREF pin either. 2. Yes, you need a pin, that can be connected to the ADC, so any pin that is marked that way in the pinout of the Attiny44. If you have AREF free, than you maybe can change the pin connections. Though you didn't specify how the attiny is connected. In your question you show only an Arduino Uno, which seems to be irrelevant for your question.

If your attiny is powered by that same battery, you can just measure internal 1.1V reference against Vcc as ref and compute actual Vcc

@chrisl I meant no spare ADC pin i just have AREF pin free that's it

@KIIV Yes, the system is powered by the same battery. Is it possible to get constant/stable/unchanged voltage by using this method.

or is there a way to use reset pin as GPIO/ADC pin?

You can use reset pin on Attiny84 as digital IO, but not as an analog pin. And you won't be able to reprogram it without bootloader or without high voltage ISP programmer (in that case you'll have to take in account there will be 12V pulses on that pin during programming).

I want the whole system to run on lithium battery

If you power the Arduino from the battery, then you can indirectly read the battery voltage by reading the internal voltage reference. This requires no pins - just connect the battery across the Arduino ground and the 5V pin. Here is more explanation on why this works...
https://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/
Note: Do not connect more than 5 volts or less than 0 volts to the 5V Arduino pin. This pin is connected directly to the AVR without any overvoltage or reverse polarity protection. Your  3.7~4.2V battery should be fine.

Hi, thank you for your response. I need to read constant voltage not the current battery voltage and i believe that in the link the author wants to measure battery voltage. Is there a way to measure stable/constant/ unchanged battery voltage irrespective of the current battery level.

You want to (1) power your circuit using a lithium battery, and (2) you want to be able to measure the voltage of that lithium battery that is powering the circuit, correct? If so, then the above approach will do that. If not, then can you clarify what you are trying to do?

hi, please check https://arduino.stackexchange.com/questions/92329/reading-constant-battery-voltage-and-using-the-obtained-value-in-sensor-formula

source: Stack Exchange

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

sort: votes


text:
How to use reset pin as I/O pin with ATtiny44
I am using the Arduino IDE as an ISP programmer to program my ATtiny44 IC. Unfortunately, I ran out of pins, so I want to use the reset pin as I/O. I read several articles online that says it is possible and even the datasheet says so.

I have a high voltage programmer as well. I wrote the code in the Arduino IDE and then used its hex file to program it using the high voltage programmer (TNM PROGRAMMER).

After I program, the IC stops working.
////////////////////////////////////EDIT/////////////////////////////////////
const int led = 0;
const int reset_led = 11; //physical pin 4 on attiny

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

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

New fuse bit setup:

////////////////////////EDIT 2 /////////////////////////////////////////

Now, the led on reset has turned off completely while the another still blinks.
Powering my attiny44 with 5v.Code is same as before
////////////////////////////////EDIT 3////////////////////////////////////
#include <avr/io.h>
const int led = 0;
#define ledd PB3
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(led, OUTPUT);

DDRB |= (uint8_t)(1<<PB3);
pinMode (ledd, OUTPUT);

}

// the loop function runs over and over again forever
void loop() {

PORTB |= (uint8_t)(1<< PB3);

 digitalWrite (led, HIGH);
  digitalWrite (ledd, HIGH);

 delay(1000);                       // wait for a second

PORTB &= ~((uint8_t)(1 << PB3)); // set PB3 to "low"

 digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 delay(1000);                       // wait for a second
}

This code worked miraculously for me, Thanks to @thebusybee.
/////////////////////////////EDIT 3/////////////////////////////////////////
The PB3 pin is pin11 in arduino.

It sounds like you found the answer to what you're actually asking. "After i program ( the ic stops working)." The chip executes code irrespective of whether or not the reset function is enabled. So, your problem is elsewhere. I would look at whether or not I was staying out of the brownout detection and pay attention to what I was actually using as indication to determine that it "stops working" and maybe that will lead to a different question.

What do you mean by "stops working"?

If you are powering it by 3.6V (4.2V fully charged) battery, then with 4.3V BOD level it'll be held in reset state all the time (it might work a little if the battery is fully charged and you are lucky to have threshold deviation closer to 4V)

You could enable CKOUT fuse to have PB2 indicate that the clock is going. You appear to be forcing the watchdog timer to run and we're not seeing your code, which leads back to the question of how you're determining "stops working."

@timemage The reset pin is PB3. I have connected one led to the reset pin in order to indicate if it is working

@KIIV Yes, you are right, i did some research on it as well and changed my power to constant 5V but the led on the reset pin did not blink

@thebusybee It means that the led connected to reset pin goes off fully

@timemage As you can read my code above, there are two led on the board, the led on the reset stays on but looks like the voltage or current is extremely low due to which the led brightness is difficult to be seen (this led should be blinking as per the code). I connected the reset pin to potentiometer but the moment i change the value of pot the led connected to pin0 turns OFF or hangs.

Please take the [tour] to learn how this site works. It is not a forum. Please add clarification to your question by [edit]ing it. Down here in the comments it gets lost. -- If the LED on pin 0 stops blinking when you turn the pot's wiper towards GND, I'd say that the pin 11 is still /RESET. That would also explain the "glowing" of the LED at that pin too, because the pin is an input. Are you sure that your fuses are correct?

I am not 100% sure about the fusebits, Please check i have added new picture to the post above under edit @thebusybee The led at reset is also on (without blinking) but the brightness is extremely low

If you are not sure about the fusebits, and the result seems to indicate that RSTDSBL is not set correctly, how can we be sure and help you? ;-) Did you read the device's and the programmer's documentation at least three times to make sure you set the fuses correctly?

@thebusybee If you check above i have added screenshot of latest fuse bit setting. I have been using this HV programmer and attiny for long so I've idea the only new thing is that i have never before used RESET as GPIO. Just to confirm, RESET (PB3) is program pin 11.

As the data sheet () says: "Pullup is activated and output driver and digital input are deactivated when the pin is used as the RESET pin." What you see confirms that RSTDSBL is not programmed.

In my HV programmer there is option Disable Reset Pin (RSTDSBL) and we have two options to select (Yes or No). ofc if we have to disable it we must select "YES" and program it. Right?

Did you try the other option?

Let us continue this discussion in chat.

I believe you meant trying "NO" option. Yes, i did, it didnt workout

"The reset pin is PB3." I have no idea why you said that to me. Did your question get resolved or not?

The data sheet gives insights:
Chapter 1.1.4 states:

The reset pin can also be used as a (weak) I/O pin.

"Weak" means here, that the output function cannot deliver as much current as the other outputs, according to figures 21-24 to 21-27 beginning at page 198 roughly 2 to 3 mA. This is commonly not enough for LEDs, except you use a high-efficiency LED.
And on page 66 is this relevant table (I cut the irrelevant column for PB2):

Table 10-8. Overriding Signals for Alternate Functions in PB[3:2]

Signal Name
PB3/RESET/dW/PCINT11

PUOE
RSTDISBL(1) + DEBUGWIRE_ENABLE(2)

PUOV
1

DDOE
RSTDISBL(1) + DEBUGWIRE_ENABLE(2)

DDOV
DEBUGWIRE_ENABLE(2) • debugWire Transmit

PVOE
RSTDISBL(1) + DEBUGWIRE_ENABLE(2)

PVOV
0

PTOE
0

DIEOE
RSTDISBL(1) + DEBUGWIRE_ENABLE(2) + PCINT11 • PCIE1

DIEOV
DEBUGWIRE_ENABLE(2) + (RSTDISBL(1) • PCINT11 • PCIE1)

DI
dW/PCINT11 Input

AIO

Note:

RSTDISBL is 1 when the Fuse is “0” (Programmed).
DebugWIRE is enabled when DWEN Fuse is programmed and Lock bits are unprogrammed.

Since you have DebugWIRE enabled, this seems to be the cause. The alternate function RESET is still active.
Please be aware that according to note 1 below table 19-4 on page 160:

After programming the RSTDISBL fuse, high-voltage serial programming must be used to change fuses and allow further programming.

This means that your circuit at PB3 needs to withstand the high voltage, and that the voltage source needs to provide enough current, which the circuit additionally draws at the high voltage.

Now to your code.
You use the pin number "0" and hope to have PB3. Well, according to this shamelessly linked pinout this is not correct:

Pin "0" is PA0.
PB3 has no number assigned.
Your next step could be to look up the sources of the Arduino library and check, if PB3 has a number assigned at all. I'm afraid this is not the case. If you're lucky and it has, use it. You will want to tell us about your finding then.
You can directly access the data direction control register and the port register. Grab your data sheet and other documentation, read, and implement.
This is untested:
// in setup():
    DDRB |= (uint8_t)(1U << 3);

// in loop():
    PORTB |= (uint8_t)(1U << 3);    // set PB3 to "high"
    PORTB &= ~((uint8_t)(1U << 3)); // set PB3 to "low"

Yes, i read it and is disabled it but it still did not work for me. After i make debugWire disable the reset led goes full off.

Well, that's a good sign, because now the pin became an output and went "low" (erm, how did you connect the LED?) or at least switched off the pull-up. Does the other LED still blink? -- BTW, your title says 44A but the prose 44. What exactly is it? (Correct your question.)

Oh that's a relief to know! Okay, so i have connected +ive of led directly to reset pin and -ive directly goes to GND of IC. Yes, with the new setup the other led still blinks.

Please add what you tried now to your question, and post the current fuses. If you changed the sketch, please add it, too.

Done, edit 2. The code is same as before reset programmable pin11

Would you mind to clarify which device it is, 44A or 44?

The device is attiny44 not attiny44A. I mentioned in edit2 above

OK, so your title misled me. I have corrected it. Now I need to fetch the other data sheet and to check out the differences. :-( This will need some time, I have some other work to do.

ok.no prob, i checked they are almost the same just some memory size difference is there.

Right. I edited my answer concerning page numbers and such. However, since I don't have an ATtiny44 I cannot check in real. Currently it should work as your fuses are set, I'd say.

ok, i have 44A , i tried with that it still does not work. Please recheck my fusebits the spien, boden or maybe my pin declaration has some issues

See my edit, your code is wrong. I assumed you checked that already. Just a hint: don't program "by random", development is more science than art.

OMG, it is working with your code. Thank you so much, but why do we need to write high and low in that manner, it should work with simple coding as well because in the future i have to declare this pin as one of my antenna pins, how do i do that?  (#define CSN 0)
This command i have to write for PB3. i have to declare CSN PIN of antenna to pb3

Let us continue this discussion in chat.

I have just posted my code above.

If the pin has no number assigned by the Arduino library, you cannot use the common functions. That's what I wrote in my answer. "If you have no legs, you cannot walk." However, you're free to implement your own work-around. -- Please consider to mark the answer as "accepted".

I have accepted. Arduino library has assigned it as pin 11 (PB3 is pin 11) but if we code it, it does not work. I think it is because of the digitalWrite function i will try changing that function and update u tommorow

Not every Arduino model has pin number 11 assigned to PB3, I found multiple different assignments. Make sure you look at the correct model!

I rechecked PB3 is pin 11 for arduino UNO board. I have attached picture above

Sure, the Uno has this. But you use a ATtiny44, the Uno has the ATmega328P.

ATtiny44 also declared reset pin as pin11 but if you code it that way it is always rejected. (#define CSN 2 ) this is my antenna pin which i want to shift to the reset pin. i can use avr language to it but how do i declare it.

No, according to the pinout, "RESET" has no pin number assigned for the ATtiny44. Where did you find that? -- Since the programming issue is another beast, feel free to post a new question. You might want to add a link to that in your question.

Ok i will create new link

https://arduino.stackexchange.com/questions/92300/how-to-declare-pb3-reset-pin-or-attiny44-in-program-using-arduino-ide-platform

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


text:
I goofed: I used a digital output rather than an analog output
OK, I have a little hardware issue I need to fix in software for the time being.  I say, "For the time being," because I already have the PC Boards printed, and I need to make do for this run of boards.  (So sue me for not bread boarding first.)  I THOUGHT the little buzzers I purchased sounded off on a DC input, but I was wrong.  I used the nearest pin to the buzzer to activate it, which is D14.  The next run of boards I will use A6 instead, but  until then I will need to output a square wave of about 2731 Hz on D14 of an ATTiny88.  The straightforward approach would seem to be something like:
bool buzzer(bool x) {
  if (x) {
    return true;
  }
  return false;
}
bool PinVal = false;
void loop() {
  <some code here>
  buzzerVal = buzzer(true | false);
  <some code here>
  if (buzzerVal && micros()%376 > 365) {
    PinVal = !PinVal;
    digitalWrite`(14,PinVal);
    }
  while (micros()%376 > 365);
}

Is there a smarter, more efficient way?  If so, I might consider not even changing the board layout.  Pin 14 has an alternate function of register PB7.  It occurs to me it might be more efficient to write directly to PB7, rather than using the digitalWrite function, which presumably has more overhead.  Yes? No?  Any other ideas?

Try the tone() library or built-in function to generate the signal.

"The next run of boards I will use A6 instead", there is a fundamental misunderstnad of what A6 means, the pin is capable to be configure as an ADC input of ADC channel 6, but when you using it as an GPIO output, it just another GPIO pin like D14 pin.

Also, depending on the microcontroller,  A6 may not even be usable as an output pin of any sort. For example, the SMD packages of the ATmega328P break out analog pins A6 and A7 but these are pure input pins. The remaining analog pins A0 to A5 do not have this restriction and can also be used as digital pins.

This is contrary to my understanding.  My understanding was on the ATTiny88, pins A0 through A7 can all be used as PWM outputs using the analogWrite function.  Please confirm or deny.  Note pin A5 is also available on the board, so although it is less convenient, it could also be used in the next design.

Mind @6v6gt's hint, A6 and A7 are on some MCU pure inputs!! You did not specify your controller.

ATTiny88, as I mentioned above.

you don't need PWM (sound frequencies are not that high) and you don't need analog output (it would not vibrate the buzzer and there isn't a DAC on the ATTiny). you can use any pin. if the buzzer is 'active', then set the pin HIGH. if the buzzer is passive, use the tone() function or a timer with interrupt.

The IDE cannot find the tone() library.  I can't seem to find anything with the library manager that provides "pitches.h" or a tone() function.  Given the rest of the code (not shown here), I am not sure a timer interrupt is a good idea.  I definitely would rather have the tone vary a bit than risk collisions with the other interrupts in the code.

the tone() functions should be in the core, but maybe the core you use doesn't have it. in AVR core it is implemented with a timer interrupt. pitches.h is part of the tone example in IDE Examples menu

Why not buy the correct buzzers, that appears to me to be the easiest solution.


text:
IDE will not upload to ATTiny88
I was successfully compiling sketches and uploading to various MCUs, including the ATTiny88.  Suddenly the IDE quit compiling and complained of various missing compilers.  I found and corrected an issue with my anti-virus, which helped some.  Eventually I uninstalled and wiped the entire IDE.  I then reinstalled from scratch, and now everything compiles OK, butt he IDE will not upload the code to the ATTiny88.  This is done a bit differently than other MCUs.  Instead of creating a virtual com port, the driver creates a different virtual USB device, and then searches for the MCU on that USB device.  The driver should cause the "unknown" MCU to become known to the system, but this does not happen, despite having installed the drivers.  The IDE, in turn, does not create a specific error when uploading, but merely times out.  How can I get the virtual driver working again?  I am running IDE 1.8.13 on a Windows 7 PC.

Go into Properties on your "Unknown Device", go to Details tab, show the Hardware Ids property values.

There is an updated driver that fixes the issue. It will still show as unknown, however it will properly connect for programming when you reset or power up the ATTiny. NOTE: One component will say it failed during install, but it doesn't matter, ignore it, it will work.
Driver is here: https://github.com/MHEtLive/MHEtLiveArduino/releases/download/1.0.0/2.0a4.rar

No, that is the driver I am using.  I tried re-installing, but that does not help.  It is probably a registry issue.

It may be that it's still trying to use the old driver. In Device manager, uninstall the device and check the option to delete the driver. Then install new driver.


text:
Arduino seems to be reading incorrect analog I/O. Am I doing something wrong?
I am using an ATTiny88 to measure temperature using a 470 ohm thermistor attached to port A3 on the Arduino.  The thermistor is attached in series with an 1870 ohm resistor connected to Vcc.  At room temperature, the voltage across the thermistor is roughly 1.5V, and Vcc is 5.1V, so that calculates to be a digital conversion of about 0x012C.  When I query the Arduino, however, it is returning 0x0288.  Unless I am missing something, that corresponds to over 3 volts.  Of course, the value varies over time, but the point is the returned value is about a factor of 2 off.  That number is suspicious, but it may not be exactly a factor of 2.  As a sanity check, 0x012C is very close to what I should be getting according to a reference thermometer given the thermistor's resistance curve.  This is the Arduino code:
#include <Wire.h>

#define Cool    0   // Peltier Cooler ON = HIGH
#define POK 1   // Power Failure IN
#define Fan 9   // Fan Relay ON = HIGH
#define PiCtl   14  // Raspberry Pi Power
#define ADDR1   15  // I2C Address 1
#define ADDR2   16  // I2C Address 2
#define SCL 23  // I2C Clock
#define SDA 24  // I2C Data

#define PTC 16  // Thermocouple Analog IN
#define FanT    655 // Fan Threshold
#define CoolT   895 // Cooling Threshold
#define DelSt   120000  // Startup delay

int I2C;
bool True = 1;
bool False = 0;
float Temp;
bool FanSet;
bool PowerFail;
bool Responded;
unsigned long timeStamp;
unsigned long heartBeat;

union Response {
    struct {
        int Temperature;    // 2 bytes
        unsigned long Living;   // 4 bytes
        uint8_t Command;    // 1 byte
        uint8_t FanValue;   // 1 byte
        uint8_t CoolStat;   // 1 byte
        uint8_t PowerStat;  // 1 byte
        uint8_t padding;    // 1 byte
    };
    uint8_t bytes[11];
};
union Response Reply;

void setup()
{
    pinMode(Cool, OUTPUT);      // Set Cooling Pin
    digitalWrite(Cool, 0);      // Turn Cooling Off
    pinMode(POK, INPUT);        // Set Power Sense Pin
    pinMode(Fan, OUTPUT);       // Set Fan Pin
    analogWrite(Fan, 0);        // Turn Fan Off
    pinMode(PiCtl, OUTPUT);     // Set Pi Power Pin
    digitalWrite(PiCtl, LOW);   // Turn Raspberry Pi On
    pinMode(ADDR1, INPUT_PULLUP);   // Address Offset 0 or 1
    pinMode(ADDR2, INPUT_PULLUP);   // Address Offset 0 or 2
    I2C = (2 * digitalRead(ADDR2)) + digitalRead(ADDR1) + 8;    // Set I2C address 8 - 11
    Wire.begin(I2C);        // Initialize I2C Communications
    Wire.onRequest(requestEvent);   // Call requestEvent when data requested
    Wire.onReceive(receiveEvent);   // Call receiveEvent when data received
    Reply.PowerStat = 1;        // Reset Power Status
    Reply.FanValue = 1;     // Set Fan Status On
    Reply.CoolStat = 0;     // Set Cool Status Off
    delay (DelSt);
}

void HeartBeat()
{
    if (millis() - heartBeat > 30000)
    {
        digitalWrite(PiCtl, HIGH);  // Turn Raspberry Pi Off
        delay (10000);
        digitalWrite(PiCtl, LOW);   // Turn Raspberry Pi On
        delay (DelSt);
        heartBeat = millis();       // Set the living time
    }
}

void TempCheck()
{
    Reply.Temperature = analogRead(PTC);
    if (Reply.Temperature > CoolT)
    {
        Reply.FanValue = 1;     // Set Fan Status On
        Reply.CoolStat = 1;     // Set Cool Status On
        digitalWrite(Cool, 1);      // Turn Cooling On
        analogWrite(Fan, 255);      // Turn Fan On
    }
    else if (Reply.Temperature > FanT)
    {
        Reply.FanValue = 1;     // Set Fan Status On
        Reply.CoolStat = 0;     // Set Cool Status Off
        digitalWrite(Cool, 0);      // Turn Cooling Off
        analogWrite(Fan, 255);      // Turn Fan On
    }
    else
    {
        Reply.FanValue = 0;     // Set Fan Status Off
        Reply.CoolStat = 0;     // Set Cool Status Off
        digitalWrite(Cool, 0);      // Turn Cooling Off
        analogWrite(Fan, 0);        // Turn Fan Off
    }
}

void PowerCheck()
{
    bool Power = digitalRead(POK);
    if (Power)
    {
        if (PowerFail)
        {
            PowerFail = False;  // Reset Power Failure Variable
        }
        digitalWrite(PiCtl, LOW);   // Turn Raspberry Pi On
        Reply.Command = 0;      // Reset shutdown command
        Reply.PowerStat = 1;        // Reset Power Status
    }
    else
    {
        timeStamp = millis();       // Reset Timer
        int Iterations = 0;     // Reset Time Counter
        while (!Power)
        {
            if (millis() - timeStamp > 5000)
            {
                timeStamp = millis();       // Reset Timer
                Power = digitalRead(POK);   // Check Power Input
                Iterations += 1;        // Set Time Counter
                Reply.PowerStat = 0;        // Set Power Status
                if (Iterations > 24)
                {
                    digitalWrite(PiCtl, HIGH);  // Turn Raspberry Pi Off
                    analogWrite(Fan, 0);        // Turn Fan Off
                }
                else if (Iterations > 12)
                {
                    Reply.Command = 1;  // Set Shutdown Command
                }
            }

        }
        Reply.PowerStat = 1;        // Set Power Status
        Reply.Command = 0;
        digitalWrite(PiCtl, LOW);   // Turn Raspberry Pi On
    }
}

// Function that executes whenever data is requested by master
void requestEvent()
{
    Reply.Living = millis() - heartBeat;    // Set the responded time
    heartBeat = millis();           // Reset the heartbeat
    Wire.write(Reply.bytes, sizeof Reply);  // respond with message as expected by master
    Responded = True;           // Set the responded variable
}

// Function that executes whenever data is received from master
void receiveEvent(int howMany)
{
    while (Wire.available()) { // loop through all but the last
        char c = Wire.read(); // receive byte as a character
        }
    Responded = True;           // Set the responded variable
    Reply.Living = millis();        // Set the responded time
}

void loop()
{
    PowerCheck();
    TempCheck();
    HeartBeat();
    long int dSeconds = millis();       // Number of milliseconds since powerup
    while (millis() < dSeconds + 1000){}    // Delay 1 second before looping
}

When I issue the command i2ctransfer -y 1 r10@0x0a I get:
0x88 0x02 0x45 0x13 0x00 0x00 0x01 0x01 0x00

all of which is expected given the state of the board with the exception of the fact the first two bytes should be more like "0x2c 0x01".  The value of 0x0288 calculates to nearly 62C, and the board is more like 30C.

it is unclear how the resistors are connected... please add a diagram ... you can click on the button that looks like a circuit ... draw diagram, then click save and insert ... or draw a diagram on paper and insert a picture

The 1870 ohm resistor is connected to Vcc and the PTC to ground, with the Arduino connected to the common point.  How else would a voltage divider be designed?  I am also not exactly sure how it is relevant.  The actual voltage is 1.5V, while the reported voltage is 3V, regardless of the circuit design.

if you read your question, then you'll see that you said nothing about connecting to ground

Is your problem to do with an analog read of a voltage ? Is this the statment which yields the incorrect result analogRead(PTC) ? Is this: #define PTC 16 also pin A3 which you have referred to in your text ? Is it also shared with this: #define ADDR2  16 ?. If you are reading an analog pin, what is the relevance of this in your text i2ctransfer -y 1 r10@0x0a ? Try applying various voltages between 0 and 5v (using resistor divider networks) to A3 to see if you get the range between 0 and 1024. If not, look at the voltage reference configuration.

The pin numbering in your diagram looks odd in that it appears to be the underside of the IC and does not seem to correspond with an ATTiny88 which has either 28 or 32 pins depending on the package. State which Arduino core you are using so, for example, it is possible to match pin A3 to the definitions in your program.

This is the board:  https://www.amazon.com/QCCAN-ATTINY88-Development-ATmega328-Compatible/dp/B0B71FLZ4X/ref=sr_1_3?crid=1WPMLC2L6NQKB&dib=eyJ2IjoiMSJ9.NEwnS1IVFmzprb50H5C-tug_7yTOqnCJcN2fRd6O46ZF_CWO_tpuS0hHp5AWR-JioRVlo6yxRd1hjeOYd66OEXclEkvK7GWM87rNu05UnZeJyjPclnymcEI4Ao8TcID9pAJwkXjt6sG7Wwx4Yff1L5Iaw9hOi5LWoAdqs8fx8B_XfBPPqKuLMGSA_59bwGIjNXNdFCuL2bsO4ioCsFxu8LM6nXwmKQlUaiqKLO4jCPI.SgMxou8CSExZ5fwOckECv7thaKj5zJuVx-h3W3xXfjM&dib_tag=se&keywords=attiny88&qid=1731339694&sprefix=attiny%2Caps%2C143&sr=8-3

I thought it was clear.  I am reading a number of pins, one of them being an analog pin, as well as the elapsed time since the last request from the external host and storing the values in the structure "Reply".  I retrieve those values to the remote host by issuing the command i2ctransfer -y 1 r10@0x0a in a BASH script.   I don't have an easy way to vary the voltage on the pin at the moment, but the new PC board prototype is arriving in a few days, which will make it easier.


text:
Sudden Error: File does not exist
I am suddenly getting an error every time I try to compile code in the IDE, even though every one of the sketches previously compiled just fine:
Arduino: 1.8.13 (Windows 7), Board: "MH-ET LIVE Tiny88(16.0MHz)"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\lrhorer\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\lrhorer\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\lrhorer\Documents\Arduino\libraries -fqbn=mhetlive:avr:MHETtiny88 -ide-version=10813 -build-path C:\Users\lrhorer\AppData\Local\Temp\arduino_build_609285 -warnings=all -build-cache C:\Users\lrhorer\AppData\Local\Temp\arduino_cache_521731 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.micronucleus-2.0a4.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.avr-gcc.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -prefs=runtime.tools.avr-gcc-4.8.1-arduino5.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -verbose C:\Users\lrhorer\Documents\Arduino\sketch_feb27a\sketch_feb27a.ino

C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\lrhorer\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\lrhorer\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\lrhorer\Documents\Arduino\libraries -fqbn=mhetlive:avr:MHETtiny88 -ide-version=10813 -build-path C:\Users\lrhorer\AppData\Local\Temp\arduino_build_609285 -warnings=all -build-cache C:\Users\lrhorer\AppData\Local\Temp\arduino_cache_521731 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.micronucleus-2.0a4.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\tools\micronucleus\2.0a4 -prefs=runtime.tools.avr-gcc.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -prefs=runtime.tools.avr-gcc-4.8.1-arduino5.path=C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.8.1-arduino5 -verbose C:\Users\lrhorer\Documents\Arduino\sketch_feb27a\sketch_feb27a.ino

Using board 'MHETtiny88' from platform in folder: C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\hardware\avr\1.0.0

Using core 'tiny88' from platform in folder: C:\Users\lrhorer\AppData\Local\Arduino15\packages\mhetlive\hardware\avr\1.0.0

Detecting libraries used...

"C:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -w -x c++ -E -CC -mmcu=attiny88 -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_DIGISPARKPRO -DARDUINO_ARCH_AVR "-IC:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\mhetlive\\hardware\\avr\\1.0.0\\cores\\tiny88" "-IC:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\mhetlive\\hardware\\avr\\1.0.0\\variants\\tiny88" "C:\\Users\\lrhorer\\AppData\\Local\\Temp\\arduino_build_609285\\sketch\\sketch_feb27a.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

exec: "C:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\4.8.1-arduino5/bin/avr-g++": file does not exist

Error compiling for board MH-ET LIVE Tiny88(16.0MHz).

The file indeed does not exist in that location.  What now?
Update:
Under the ATTinyCore compiler the missing file name is the same, but the directory is different:
exec: "C:\\Users\\lrhorer\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-g++": file does not exist

The latest version of the DigiStump compiler does not even have the MH-ET Live Tiny88 board compiler included.
I can get the code to compile under Linux, but I am having trouble uploading the binary to the board.  How can I take the binary code and upload it to the ATTiny88 board under either Linux or Windows 7?
Update:
I found three files quarantined by my anti-virus.  I restored the files, and now avr-g++.exe seems to be back where it belongs, and the compiler no longer claims the file is missing.  Now, however, it s complaining about not finding the stdlib.h library called from the Arduino.h library.
Update:
After I removed three files apparently related to the IDE from quarantine by my virus scanner, I deleted everything, and re-installed the IDE.  Now it compiles without error, but I cannot upload to the board in either Windows or Linux.  Of course I tried more than once to reinstall the Windows USB drivers, and they install without error, but the virtual device does not show up like it is supposed to, and the upload processor times out.

"This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences." Please post the detailed error messages.

install/reinstall the Arduino AVR core in Boards Manager

I added verbose output during compilation and edited the query to include the output..  I tried to re-install the AVR code.  There is nothing identified as the  "core".  I tried installing Arduino 1.8.5 and then reinstalling 1.8.6, and I tried removing and reinstalling the  MH-ET Live boards.  Neither worked.  There is a file C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-g++.exe and a file C:\Users\lrhorer\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino7\bin\avr-g++.exe.  Should I try re-installing the Digistump drivers from the command line?

the MH-ET boards package depends on Arduino AVR boards package. so again, reinstall the Arduino AVR boards package in Boards Manager. reinstalling the IDE doesn't reinstall Boards Packages

Didn't help.  See the update in the main text.

didn't help? you solved your original problem

Not by re-loading the Arduino AVR board.  That had no effect.  Now it compiles, but will no longer upload, which it also did just fine before this problem occurred.

Deleting / uninstalling the entire IDE and completely reinstalling allowed the code to compile, so I am closing this question.  It will not upload, so I will open another question.


text:
Change Interrupts on the ATTiny 88
I am working on a project that requires a number of I/O pins for various purposes.  I chose the ATTiny88 because it has plenty of GPIO pins, and is relatively inexpensive.
Here is the updated code per timemage, with many thanks!
#include <Arduino.h>
#include <TM1637Display.h>
#include "PinChangeInterrupt.h"

int counter = 0;
bool Update = false;
int currentStatePhase_B;
int lastStatePhase_B;

// Shutdown Output
#define SW 11

// Rotary Encoder Inputs
#define Phase_A 13
#define Phase_B 12
#define DIO 3
#define CLK 4

TM1637Display display(CLK, DIO);

void setup() {

  // Set encoder pins as inputs
  pinMode(Phase_A,INPUT);
  pinMode(Phase_B,INPUT);
  pinMode(SW, OUTPUT);

    // Read the initial state of Phase_B
    lastStatePhase_B = digitalRead(Phase_B);

    // Call updateEncoder() when any high/low changed seen
    // on interrupt 0 (pin 2), or interrupt 1 (pin 3)
    attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, CHANGE);
    attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, CHANGE);

  display.setBrightness(0x0f);
  display.clear();
}

void loop() {
  delay(100);
    if (Update){
        // Show decimal numbers with/without leading zeros
    display.showNumberDec(counter, false);
    // Expect: ___0
        Update = false;
    }
}

void updateEncoder(){
  delay (4);
    // Read the current state of Phase_B
    currentStatePhase_B = digitalRead(Phase_B);

    // If last and current state of Phase_B are different, then pulse occurred
    // React to only 1 state change to avoid double count
    if (currentStatePhase_B != lastStatePhase_B  && currentStatePhase_B == 1){

        // If the Phase_A state is different than the Phase_B state then
        // the encoder is rotating CCW so decrement
        if (digitalRead(Phase_A) != currentStatePhase_B) {
            counter --;
        } else {
            // Encoder is rotating CW so increment
            counter ++;
        }

    if (counter > 1023){
      counter = 1023;
    }
    if (counter < 0){
      counter = 0;
    }
    delay(15);
    }

    // Remember last CLK state
    lastStatePhase_B = currentStatePhase_B;
    Update = true;
}

It is now capturing most, but not by any means all, interrupts, but the direction is highly unreliable.  More often than not, it counts up regardless of which way the encoder is turned,and often counts down when the encoder is turned clockwise.
Here is what seems to be a good reference:
ATtiny88 8-bit Microcontroller

forget about your code for now ... make sure that the interrupt actually works ... write a simple program that has one ISR (interrupt service routine) ... the ISR triggers when a pushbutton is pressed, and alternates the status of an LED at every press

you're overthinking the encoder program ... trigger on one channel only ... the state of the other channel indicates the direction of rotation

Here is what seems to be the best reference ... no, the manufacturer's website is the source of the best reference  not some 3rd party site ... look at page 53 in https://ww1.microchip.com/downloads/en/DeviceDoc/doc8008.pdf

more info https://onlinedocs.microchip.com/pr/GUID-19759098-FF73-4B52-AA3D-E651C849337D-en-US-2/index.html?GUID-EC4CAB0F-FADE-433B-8381-0866ED41CF64

Re “updated code per Edgar Bonet”: you mean “per timemage”. 2. Since updateEncoder() only cares about changes in Phase_B, there is no point in calling it when Phase_A changes. 3. Never delay() in interrupt context! 4. If you make counter unsigned, you won't need to clamp its value, and it will always be correct modulo UINT_MAX.

2′. Since updateEncoder() only cares about the rising edges of Phase_B (i.e. when it changes from 0 to 1), there is no point in calling it on the falling edges. Attach the interrupt on RISING events and remove the test on currentStatePhase_B and lastStatePhase_B (and remove those variables also).

I certainly understand delays in ISR routines are not  great idea, and this one was not my idea.  One of the references suggested putting in a brief delay to debounce the encoder.  If I only call updateEncoder() on the rising edge of B, then the code will miss a CCW turn, right, because B is already high and remains high?  I am going to start a new thread, because the original question is effectively answered

I am going to use UINT8_T.  An 8 bit data space is good enough for this purpose.  I will just double the value of counter when I output the voltage.

Wait, that will not work.  Using something like UINT8_T or indeed anything that rolls over will not work.  The counter must not only be restrained to positive integers between 0 and 1024, it must ignore any input that would cause the counter to roll over at 0 or 1024.  Instead, it should just stop counting in that direction.

If you needed an example of what I'd said (and a fair bit of dishonestly on the part of a mod) notice the messages are gone.

Interrupt types

One source says there are only two interrupt pins, ...

There are  two "external interrupt" pins; that is the term you'll find in the chip's datasheet. This is the term that refers to the kind of pins that attachInterupt uses. These are the ones in the pinout labeled INT0,INT1,INTn. The "external" term may be confusing for a couple of reasons. Lots of external things cause interrupts, but this name is applied to when you're not talking about events tied to particular peripherals, like USART (serial peripheral) receiving a character. The special function of "external interrupt" is dedicated to dispatching interrupts based on signals on these INT0/INT1/INT# pins. There's one interrupt vector for each of these signals (two in your case). As you've probably seen in the documentation they can be configured to trigger on rising or falling edges, both edges, and low levels.
So, they're right about that to the extent that they're talking about the "external interrupt" pins.
The "external" name is also confusing because of what else you've found:

Another source says there are quite a few Change Interrupt pins

This is also true. These are the "PCINT#" signal names listed in the chip pinout.  These "pin change interrupts" are newer; not new, but newer. There exist(ed) AVR that had/have "external interrupts" but no "pin change interrupts". I'd like  to think that if they were created at the same time they wouldn't have simply called the former ones "external", because these are no less external although they're less dedicated. There's only a single ISR/interrupt for each group of 8 PCINT pins. And unlike the others they only naturally detect that a pin has changed and nothing about the nature of that change (rising vs falling). But a lot of AVR support them and those that do have a significant number of them. In the case of your ATTiny88, all of the GPIO (Arduino "digital") pins are capable of dispatching a pin change interrupt.  However, the Arduino AVR core doesn't provide a function for using them.
Modifying NicoHood's PinChangeInterrupt library
One of the people that used to be in my circle was NicoHood, who created this PinChangeInterrupt library. I have a foggy memory of helping with bits of it.
What he did was model it after the normal attachInterrupt function. So, you can use it almost as though you have the RISING/FALLING/CHANGE "external interrupt" capability on all of your PCINT# pins; in your case all of your pins. Underneath it is tracking the state of each port pin to determine what has changed and in what direction. In other words, using an interrupt that fires given a change on any of 8 pins together with variables to synthesize per-pin callbacks for not just change but also specifically rising and falling if you want. This is not perfect it is possible to lose short lived events and it takes longer to dispatch your handler function. But it's probably fine for what you're doing.
It does not support your chip out of the box. However you can modify to support the ATTiny88; partially if you're not picky. You should find it in the library manager as "PinChangeInterrupt" by NicoHood, currently at version 1.2.9. If you install that it should show up under your sketchbook/libraries directory. You will need to edit the file at path:
<sketchbook-directory>/libraries/PinChangeInterrupt/src/PinChangeInterruptBoards.h
That's your local copy of this file.
Your ATTiny88's handling of PCINT is going to be nearly the same as the ATMega328P that's in the UNO. Or rather nearly a superset of it. The chips are closely related in a way.
However, you have extra PCINT capable pins on the ATTiny88 that aren't available on the ATMega328P. So you can crudely hack in a line into this section to read:
#if defined(__AVR_ATmega328__) || defined(__AVR_ATmega328A__) || defined(__AVR_ATmega328PA__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328PB__) \
   || defined(__AVR_ATmega168__) || defined(__AVR_ATmega168A__) || defined(__AVR_ATmega168PA__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega168PB__) \
   || defined(__AVR_ATmega88__) || defined(__AVR_ATmega88A__) || defined(__AVR_ATmega88PA__) || defined(__AVR_ATmega88P__) || defined(__AVR_ATmega88PB__) \
   || defined(__AVR_ATtiny88__) \
   || defined(__AVR_ATmega48__) || defined(__AVR_ATmega48A__) || defined(__AVR_ATmega48PA__) || defined(__AVR_ATmega48P__) || defined(__AVR_ATmega48PB__)

The addition of that second to last line above should make the library treat the ATTiny88 you have as though it were an ATMega328P. This compiles under ATTinyCore. I am not set up to test it on a real ATTiny88. But, I expect it will work if you try some examples.
Having done that, the library should be work on any of the pins that carry a PCINT0 through PCINT23 label.  If you want it to work with PCINT24-PCINT27, that can be done, but requires more work. But given what you've said you probably don't need one of those four and they're not available on the DIP package which I'm guessing you have anyway.
Updating your code
You would to #include "PinChangeInterrupt.h" at the top of your code, and then your current code:
    attachInterrupt(digitalPinToInterrupt(Phase_A), updateEncoder, CHANGE);
    attachInterrupt(digitalPinToInterrupt(Phase_B), updateEncoder, CHANGE);

then becomes:
    attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, CHANGE);
    attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, CHANGE);

With luck, that should do it provided Phase_A and Phase_B under your core (e.g. ATTinyCore) map to GPIO/Arduino "digital" pins that carry a PCINT# signal where the number less than 24.
As I said, I have no way of testing it on real hardware right now. But I expect it will work. If not, it is the sort of direction you need to go in.
Doing PCINT yourself
You can also take a more direct approach with reading the datasheet and sorting out how to do what the library does for you, only manually. One of the examples NicoHood provided with the library is not really an example of using the library but rather an explanation as to what the library does in the form of code. Notice it doesn't actually include the library; it would operate stand alone. So if you want to understand the guts yourself by following the ATtiny88 datasheet, that's a place to start.
One reason you might want to do it yourself anyway is if your encoders are being operated quickly, to the point where you can't afford some of the extra effective dispatch time imposed by what the PinChangeInterrupt library is doing in sorting out which pin changed and how. If you handle PCINT yourself, you can make a point of putting your two encoder pins in completely different groups of 8 such that there is only one source of pin change interrupt for each ISR and so there is no need to check which pin caused the interrupt and to route that to another function.

+1, very nice answer. Just a small correction: “they can be configured to trigger on rising or falling edges or at high and low levels”. They can be configured to trigger on change (like PCINT), rise, fall or low, but not on high level.

You're right. Brain on autopilot I guess. Will update it either on next natural edit or with in a couple of days if I have no other cause.

Well, I guess I'm going to integrate your change now, because they haven't given an indication on a change and this is likely going to by my last post.

I am sorry, I don't quite follow the conversation between the two of you.

Meanwhile, the code is close to working.  At least the interrupts are now occurring.  They frequently get missed, however, and they are counting erratically.  Instead of counting up when the encoder turns clockwise and down when it is turned counter-clockwise, more often than not iot counts up regardless of which way the encoder is turned, and occasionally it counts down regardless oif which way the encoder is turned.  I am unsure what is causing this behavior.

It's not important to your use case. As you found I tiered the explanation so you (or anyone else) could take the answer at whatever level they needed. Edgar Bonet pointed out a thinko I'd made in acknowledging/describing your findings about different counts of pins being described as capable of interrupts. For those that care and are going to follow that part, it only makes sense that it is also correct. And so it was corrected


text:
ATTiny88 missing pulses - maybe
I have been given to understand the ATTiny88 is very similar to the Arduino Uno / ATMega328 MCU.  There does not seem to be a tag for the ATTiny88, so that is why I chose the tags I did.  I do not have a high enough reputation to create a tag, yet.  Thanks to the generous help of timemage, Edgar Bonet, and others, my MCU board is now responding, albeit very erratically, to pulses on pins 12 and 13, designated Phase_B and Phase_A, respectively, in the code below.  I have not yet entirely ruled out a hardware issue (I will do so), but a software issue is still likely.  I don't quite know what.  The MCU is registering pulses, but it very often misses large numbers of turns in either direction.  What's more, it frequently reports the wrong direction, strongly favoring a CW rotation, but sometimes reporting a CCW rotation when the knob is turned CW.  It is definitely not an overflow issue, as the anomalous effects are seen in abundance when in the mid range of the variables.
#include <Arduino.h>
#include <TM1637Display.h>
#include "PinChangeInterrupt.h"

volatile uint8_t counter = 0;
volatile bool Update = false;
volatile int currentStatePhase_B;
volatile int lastStatePhase_B;
volatile int pulses = 0;

// Shutdown Output
#define SW 11

// Rotary Encoder Inputs
#define Phase_A 13
#define Phase_B 12
// TM1637 I/O ports
#define DIO 3
#define CLK 4
TM1637Display display(CLK, DIO);

void setup() {

  // Set encoder pins as inputs
  pinMode(Phase_A,INPUT);
  pinMode(Phase_B,INPUT);
  pinMode(SW, OUTPUT);

    // Read the initial state of Phase_B
    lastStatePhase_B = digitalRead(Phase_B);

    // Call updateEncoder() when any high/low changed seen
    // on interrupt 0 (pin 2), or interrupt 1 (pin 3)
    attachPCINT(digitalPinToPCINT(Phase_A), updateEncoder, RISING);
    attachPCINT(digitalPinToPCINT(Phase_B), updateEncoder, RISING);

  display.setBrightness(0x0f);
  display.clear();
  display.showNumberDec(0, false);
}

void loop() {
    if (Update){
        // Show decimal numbers with/without leading zeros
    display.showNumberDec(pulses, false);
    delay(1000);
    display.showNumberDec(counter, false);
        Update = false;
    }
}

void updateEncoder(){
    // Read the current state of Phase_B
    currentStatePhase_B = digitalRead(Phase_B);

    // If last and current state of Phase_B are different, then pulse occurred
    // React to only 1 state change to avoid double count
    if (currentStatePhase_B != lastStatePhase_B  && currentStatePhase_B == 1){
        // If the Phase_A state is different than the Phase_B state then
        // the encoder is rotating CCW so decrement
        if (digitalRead(Phase_A) != currentStatePhase_B) {
            counter --;
        } else {
            // Encoder is rotating CW so increment
            counter ++;
        }
    }
    if (counter > 1023){
      counter = 1023;
    }
    if (counter < 0){
      counter = 0;
    }
    pulses ++;
    // Remember last Phase_B state
    lastStatePhase_B = currentStatePhase_B;
    Update = true;
}

try this ... use interrupt on only phase_A ... when interrupt fires, increment or decrement counter depending on the state of phase_B ... also set Update flag

For answers to most of these questions, see https://arduino.stackexchange.com/questions/92354/change-interrupts-on-the-attiny-88

@jsotola It's an EC11 on a board I created myself.  I don't know what sort of encoder you might be imagining, but this is as basic as it gets.  What do you suggest for debouncing?  Note (I have tried a number of things, including polling rather than employing interrupts.

I've seen an encoder that clicks repeatedly on one contact when turned in one direction, and clicks repeatedly on the second contact when turned in the other direction ... I think that EC11E0B is like that

OK, this is definitely not that.  Actually, it would be great if it were.

https://www.arduino.cc/reference/en/libraries/rotaryencoder/

It does not like that library, at all.  It spits out more than a dozen errors of all sorts with all the examples.

Rotary encoders with Gray encoding or quadrature encoding are by their encoding immune against bouncing. Would you mind to [edit] your question and provide a link to the encoder's data sheet?

No, they definitely are not.   See https://www.pinteric.com/rotary.html  It is true bouncing can be readily detected and perforce ignored, but no mechanical switch is immune.  I just bought these off Amazon:  https://www.amazon.com/gp/product/B07DM2YMT4/ref=ppx_yo_dt_b_asin_title_o08_s02?ie=UTF8&psc=1

I did not say "they do not bounce". I claim the the encoding is immune in the sense that you will always have correct rotation angles. I should have added this. Your referenced paper backs my claim.

Do you have the required pull-up/pull-down resistors on pins 12 and 13?

Yes, of course, but I need to put a scope on the encoder to confirm it id bouncing, and of course then add a couple of capacitors

OK, I have an answer.  The MCU is still missing a lot of pulses, but I am fairly certain this is a hardware issue, or at least mostly so.  I found some code by Ralph S. Bacon and Marko Pinteric.  The YouTube video can be found here
As should always be the case, the ISR is brief.  Here it is a single line that merely sets a Boolean variable true.  In the loop section, the code repeatedly checks to see if the interrupt has occurred.  The checkRotaryEncoder function then verifies the pin values to make sure the encoder is in a valid state (not bouncing).  If so, then the counter value is updated with the result.
#include <Arduino.h>
#include <TM1637Display.h>
#include "PinChangeInterrupt.h"

uint8_t lrmem = 3;
int lrsum = 0;
int num = 0;
unsigned int counter = 0;

// Shutdown Output
#define SW 11
// Rotary Encoder Inputs
#define Phase_A 12
#define Phase_B 13
// TM1637 Display I/O
#define DIO 3
#define CLK 4
TM1637Display display(CLK, DIO);

// A turn counter for the rotary encoder (negative = anti-clockwise)
int rotationCounter = 200;
// Flag from interrupt routine (moved=true)
volatile bool rotaryEncoder = false;

// Rotary encoder has moved (interrupt tells us) but what happened?
// See https://www.pinteric.com/rotary.html
int8_t checkRotaryEncoder()
{
    // Reset the flag that brought us here (from ISR)
    rotaryEncoder = false;

    static uint8_t lrmem = 3;
    static int lrsum = 0;
    static int8_t TRANS[] = {0, -1, 1, 14, 1, 0, 14, -1, -1, 14, 0, 1, 14, 1, -1, 0};

    // Read BOTH pin states to deterimine validity of rotation (ie not just switch bounce)
    int8_t l = digitalRead(Phase_A);
    int8_t r = digitalRead(Phase_B);

    // Move previous value 2 bits to the left and add in our new values
    lrmem = ((lrmem & 0x03) << 2) + 2 * l + r;
    // Convert the bit pattern to a movement indicator (14 = impossible, ie switch bounce)
    lrsum += TRANS[lrmem];
    /* encoder not in the neutral (detent) state */
    if (lrsum % 4 != 0)
    {
        return 0;
    }
    /* encoder in the neutral state - clockwise rotation*/
    if (lrsum == 4)
    {
        lrsum = 0;
        return 1;
    }
    /* encoder in the neutral state - anti-clockwise rotation*/
    if (lrsum == -4)
    {
        lrsum = 0;
        return -1;
    }
    // An impossible rotation has been detected - ignore the movement
    lrsum = 0;
    return 0;
}

void setup() {
  // Set encoder pins as inputs
  pinMode(Phase_A,INPUT);
  pinMode(Phase_B,INPUT);
  // Set Power Switch as output
  pinMode(SW, OUTPUT);
  // Initialize display
  display.setBrightness(0x0f);
  display.clear();
  display.showNumberDec(0, false);
  // Set up interrupt pins and vector
  attachPCINT(digitalPinToPCINT(Phase_A), rotary, CHANGE);
  attachPCINT(digitalPinToPCINT(Phase_B), rotary, CHANGE);
}

void loop()
{
  // Has rotary encoder moved?
  if (rotaryEncoder) {
    // Get the movement (if valid)
    int8_t rotationValue = checkRotaryEncoder();
    // If valid movement, do something
    if (rotationValue != 0) {
      counter += rotationValue;
      if (counter > 1023){
        counter = 1023;
      }
      else if (counter < 0){
        counter = 0;
      }
      display.showNumberDec(counter, false);
    }
  }
}

// Interrupt routine just sets a flag when rotation is detected
void rotary()
{
    rotaryEncoder = true;
}

Any comments are welcom.  In addition, Ralph Bacon used the IRAM_ATTR directive to create the rotary() ISR.  My understanding of this directive is it is not necessary in most cases.  On the other hand, presumably the code will execute faster if it is pushed into flash RAM.  I could not make this work.  The compiler complains, "expected initializer before 'rotary'"  Is this by chance because the ATTiny88 does not have flash RAM?  If not, then what?


text:
How to use arduino to run .exe file in a windows computer
Is there a way to run .exe file on a windows computer that connected to arduino? (I want to create some sort of stream deck, but it will be used for running Google Chrome and other .exe file on a windows computer)
Can someone explain how to run it using arduino uno by taking input from the user?

how do you normally run  microsoft edge?

double clicking the shortcut, or using cmd

don't forget that the subject of your question is about an external device that is connected to a computer ... so double clicking the shortcut, or using cmd does not answer the question I asked ... anyway, program the arduino to be one of the external devices that you use to control your computer

Ah I see, but I only find some tutorials on how to use the arduino as an automated keyboard, is there a way I use it to open microsoft edge without using my arduino as an automated keyboard?

Maybe use a script (say Powershell) running on the PC. It constantly checks a Serial port for any commands the arduino may send it. The script interprets such commands and initiatives an appropriate action. In your case this would be opening Microsoft Edge.

Thanks for the answer, I will try!

setup keyboard shortcuts in Windows to run the programs. then if you still need it, you can use an Arduino Leonardo or Arduino Micro to send this keyboard shortcuts.

Ah I just figured out that there is Arduino Leonardo, I will try using that one

@Juraj: I believe your comment would make a perfectly good answer.

As mentioned in comments, one way to do this would be to bind a windows shortcut key to do the action you desire and then have the arduino send that as a keystroke.  This would only be possible on devices (like the leonardo) that have native usb device support rather than a serial to usb converter chip.
An alternate (and more secure and reliable) approach would be to create a windows service that looks for the arduino and monitors it and runs actions when the arduino generates specific events.
The easiest way to get events would be to read incoming serial data from the arduino and parse it; this would work on all arduinos.  A more complex approach (only available on arduinos with native usb device support) would be to create a special USB device profile that generated the events, and a corresponding windows service or driver to recognize and use that custom device.
I've done things like this with my own projects, although in linux, not in windows.


text:
Modbus RS485 Decode the message received
I'm try to read some value from a soil NPK sensor using RS485 Modbus e Arduino uno.
I menage to sent the request msg and I got the response but now i don't know how to read the response in order to get the information I need.
the following code sent the request to get moisture value to the sensor:
#include <SoftwareSerial.h>

#define RE 8
#define DE 7

const byte msg[] = {0x01,0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
byte values[11];

SoftwareSerial mod(2, 3);

void setup() {

  Serial.begin(4800);

  mod.begin(4800);

  pinMode(RE, OUTPUT);
  pinMode(DE, OUTPUT);

  delay(500);
}

void loop() {
  test();

}

byte test(){
  digitalWrite(DE,HIGH);
  digitalWrite(RE,HIGH);
  delay(10);
  Serial.flush();

  if(mod.write(msg,sizeof(msg))==8){
    digitalWrite(DE,LOW);
    digitalWrite(RE,LOW);

    for(byte i=0;i<7;i++){
     values[i] = mod.read();
    Serial.print(values[i],HEX);

    }

    Serial.println();
    Serial.flush();
    delay(4000);

  }

}

My response is following bits:
114BA4134
1D5112A671
341D2119B
A61341D51
12A671341
E811BBAB13
41DB114BA4
1341DB11
4BA41341DB
114BA4134
1E311CA691
341C911EB
A11341E31
1CA691341
EC11FA6A13
41E4117BA8

looking at the datasheet below there should be a data area in the message response from the sensor.
how to convert this bit info to my humidty value.

my be this example from the datasheet can help

114BA4134 ... you have to print spaces between the bytes ... looks like leading zeros are not printed ... don't bother trying to decode the mess you have right now ... also, add code to print the leading zero ... if (values[i] < 16) Serial.print(0);


text:
Replace mechanical switch with electrical switch or relay
I have a remote controller for a portable heater, and working on a small project to be able to control the fan on/off from an arduino with Bluetooh HM-10 module. I thought a solenoid might work by mounting on top of the remote but it doesnt have enough force, I want to remove/desolder the mechanical button and figure out a way to control it without the switch but kind dont really know what circuit
I should use, kind of just learning how to use arduino.
Images of remote and button traces below.
Any idea how I could wire this up to arduino via some switch/relay circuit? Any circuit design / schematic would be helpful

Is that a battery powered remote control? Often a opto-coupler is possible, but for this I would use a mechanical contact. Some small 5v reed relays require only 20mA. The arduino uno can drive that directly (without transistor).

Would I solder the relay or remove the button and solder on to the pads?

Don't forget to edit your original question if you have additional thoughts to make the question better. 2. Caution, try a much safer project.  A heater project may go wrong and start a fire.  Try a low voltage light.  3. With out knowing the voltage and current handled by the part your are replacing it is difficult to make recommendations.  That said, if the switch is N.O. then likely you could simply solder the N.O. contacts of the relay across the switch.

I would not remove the button, but solder two wires. To prevent that the wires break, attach them to the board. For example drill a hole and use a cable tie. I often also use hot glue to stick the wires to the board so they don't move where they are soldered.

I would unsolder the switch then solder in a FET in the configuration shown below. The FET will act as a switch and may be controlled with any digital output from your Arduino board. When selecting a FET makes sure you find something that will fit the foot print you have to work with on your board, and the gate-source threshold voltage is rated to handled 5V.

Great thanks! Would a BJT NPN transistor work aswell?

@condo1234 yes...a BJT NPN would accomplish the same task but the FET is less of a load on your Arduino board and more efficient than the BJT. When you have 5vdc on the base of your BJT you will have a constant base-emitter current (BJT load). With the same 5vdc on the FET gate you only need to initially drive the FET capacitance (FET load).

Thanks, would an IRF540n work ok?Also with the 10k resistor can I just link that directly to an arduino ground pin?

@condo1234 Yes, that could work as long as you don't exceed Vds and Vgs (data sheet specs). That it a pretty beefy FET for what otherwise looks like a low power application. Conceptually you have the idea; now you just need to go through some trial-and-error (design iteration) to get the circuit to do what you want it to do for you.  The grounds should be tied together on your Arduino board and the circuit board if they are sharing a circuit (in this case the switch). This is to ensure both circuits are referencing the same ground potential.

@condo1234  If you want to get into circuit design I would advise you to download a Orcad Lite (Free Version of Orcad). This will allow you to layout your circuits and run simulations to help determine how the circuit will behave. Heres the link: https://www.orcad.com/resources/download-orcad-lite


text:
Maintaining time in Arduino
I am working on development of alarm clock using Arduino.
No doubt RTC will be the best but it increases the Price of the project. Also I opened a digital clock (which I purchased online) and I see that there is only one IC (obviously it is covered with something black wax). But there was that one patch only.
So it seems it used only a controller or RTC. But with only RTC its not possible to control LCD. So it must be only a microcontroller
Now I have three options for maintaining time

I use RTC like DS3231
I use millis() function
I use timer and timer interrupts of micro controller for free running timer.

Can I get accurate time using micro controller.

It depends, can you show us a photo of your arduino board? A 16MHz resonator is not accurate, but a 16MHz crystal is pretty good. You don't need interrupts, the millis can be just as accurate as the 16MHz crystal/resonator (when the sketch uses millis in the right way). The time library can be used with millis, and the time library can be used with the ds3231 as well, so it is easy to upgrade: https://github.com/PaulStoffregen/Time The time library works with the TimeAlarms library. If you want only a clock with hours, minutes and seconds, then you can use millis and write code for it yourself

I see from eBay that you can get the DS1307 for around 10 cents. Is that really too much to pay? You also need a crystal and a backup battery (eg. CR2032). Without a battery the device cannot possibly remember the time if it is powered off.
If your device is battery powered then you could conceivably just use millis(), however you would need to have a way of setting the time. The resonator used on a Uno is not as accurate as a crystal, however that might be good enough depending on your project.
If you are trying to save money I wouldn't use a Uno or Micro, but the bare chip, with a few extra components (eg. decoupling capacitors, a couple of resistors, and a crystal).

Yes, I am now making a project with all the available board, just after proving everything I'll go for separate IC's and components.


text:
facing issue while compiling code
This following error message I am getting while compiling:
Arduino: 1.6.8 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

In file included from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/opt.h:51:0,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwip/init.h:40,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/IPAddress.h:27,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:31,

                 from C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:20:

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:1301:2: error: #error TCP_MSS must be defined

 #error TCP_MSS must be defined

  ^

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:2381:2: error: #error LWIP_IPV6 must be defined

 #error LWIP_IPV6 must be defined

  ^

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/lwip2/include/lwipopts.h:3534:2: error: #error LWIP_FEATURES must be defined

 #error LWIP_FEATURES must be defined

  ^

In file included from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFiSTA.h:29:0,

                 from C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:34,

                 from C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:20:

C:\Users\Shree\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0/tools/sdk/include/user_interface.h:34:2: error: #error LWIP_OPEN_SRC must be defined

 #error LWIP_OPEN_SRC must be defined

  ^

C:\Users\Shree\Documents\Arduino\libraries\firebase-arduino-master\examples\FirebaseDemo_ESP8266\FirebaseDemo_ESP8266.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory

 #include <FirebaseArduino.h>

                             ^

compilation terminated.

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
***************************

please help me out to solve this issue.

are all options set in tools menu? it is better to use esp8266 Arduino package 2.4.2 until 2.5.1 is released

Can you please provide the code?

at a guess you're including some headers in the wrong order, or haven't included a required header at all ... without code, I'm guessing

ok I will try with esp866 2.4.2. I am trying to compile example of FirebaseDemo_ESP8266. Yet no any code updated.

Hey guys I have run my example with esp8266 2.4.2 version now I'm getting following error while compiling- C:\Users\Shree\Desktop\FirebaseDemo_ESP8266ex\FirebaseDemo_ESP8266ex.ino:21:29: fatal error: FirebaseArduino.h: No such file or directory
#include <FirebaseArduino.h>
                         ^

compilation terminated.
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).


text:
Arduino Uno Analog pot values are not smooth
I have tired Arduino smoothing example but mine analog value are not staying constant even when I don't rotate the potentiometer. I am mapping the values from 0 -> 1024 to 0-> 100. I have tried exponential filter also but the result is same.
Values change 2 to 3 point mostly. Any idea how can I make the readings much more smooth.

Welcome to Arduino:SE. You might find this post on our Meta site helpful: How to ask a good question for Arduino Stack Exchange.

please include a diagram of the circuit ... include the pot value

Dividing a normal (270 degree linear) potentiometer into 100 sectors is pushing to the limit. You can add hysteresis so it does not wander between adjacent values. Better is to use a rotary encoder.

Without seeing your filtering code we cannot say why they didn't smooth the values enough. Please share your code. It also depends on the noise your circuit is receiving (and its frequencies)

@6v6gt can you guide me or share the link how Can I add the hysteresis?

@chrisl I will add the code to today

@Arslan Hysteresis. https://forum.arduino.cc/t/hysteresis/506190  It includes an example with a potentiometer but, from experience, 100 sectors is the outer limit of what can be achieved.

Help yourself by helping us help you. Post a Schematic, not a frizzy picture showing how it is wired including power, and grounds. Include links to technical information to each of the hardware items. Reason for the links is many, it helps us to understand the part you have, there are many items with the same name but are not electrically the same. Second it saves a lot of time looking and guessing is that the correct one. We want to help but we need yours to accomplish that. Thanks st2000!

I will share rest of the details soon

There will always be noise in the output an Analog to Digital Converter (ADC).

An ADC converts a continuous-time and continuous-amplitude analog
signal to a discrete-time and discrete-amplitude digital signal. The
conversion involves quantization of the input, so it necessarily
introduces a small amount of error or noise.

All one can do is mitigate the noise.  Consider cleaning up your power supply.  Make sure your voltage reference is well filtered.  Inspect these power rails with an oscilloscope if one is available.  Also consider keeping all wiring as short as possible and avoid using Bread Boards as they tend to introduce noise in sensitive circuits.
When using exponential averaging consider the equation / code can be modified easily to accommodate very noisy signals at the sacrifice of responsiveness.  If the application can tolerate the delay, the decay of historical samples can be lowered such that what most consider noise can be filtered out.  One can do this by picking very small values for alpha in the following equation found on wikipedia.org:


text:
Having issues understanding what "#define GET_STATUS" does
I am trying to use a Waveshare 4.2inch e-paper display with an Adafruit Feather Adalogger M0, but am having issues with two separate instances of #define GET_STATUS being defined differently in different locations. More specifically, in the Demo Library (download) for the Waveshare display, one of the files (epd4in2.h) defines GET_STATUS as 0x71. However, in a file (USBCore.h) I downloaded from the board manager in the ArduinoIDE to be able to support the Feather Adalogger, GET_STATUS is defined as 0.
I've tried messing with the values to see if making them match (both as 0x71 and both as 0) would solve the issue, but it didn't change anything. I can't find any information about what GET_STATUS in general, so I'm unsure what I can even try to fix this issue. Furthermore, I can't find any instances of GET_STATUS being used, so I'm unsure what its significance even is. So, basically, my questions are: 1) what is the significance of GET_STATUS, and 2) how can I reconcile it being used differently in two different places?
Below is the code I'm trying to run (it's the demo code from Waveshare), and the libraries other than "<SPI.h>" are in the demo library download from Waveshare.
#include <SPI.h>
#include "epd4in2.h"
#include "imagedata.h"
#include "epdpaint.h"

#define COLORED     0
#define UNCOLORED   1

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Epd epd;

  if (epd.Init() != 0) {
    Serial.print("e-Paper init failed");
    return;
  }

  /* This clears the SRAM of the e-paper display */
  epd.ClearFrame();

  /**
    * Due to RAM not enough in Arduino UNO, a frame buffer is not allowed.
    * In this case, a smaller image buffer is allocated and you have to
    * update a partial display several times.
    * 1 byte = 8 pixels, therefore you have to set 8*N pixels at a time.
    */
  unsigned char image[1500];
  Paint paint(image, 400, 28);    //width should be the multiple of 8

  paint.Clear(UNCOLORED);
  paint.DrawStringAt(0, 0, "e-Paper Demo", &Font24, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 100, 40, paint.GetWidth(), paint.GetHeight());

  paint.Clear(COLORED);
  paint.DrawStringAt(100, 2, "Hello world", &Font24, UNCOLORED);
  epd.SetPartialWindow(paint.GetImage(), 0, 64, paint.GetWidth(), paint.GetHeight());

  paint.SetWidth(64);
  paint.SetHeight(64);

  paint.Clear(UNCOLORED);
  paint.DrawRectangle(0, 0, 40, 50, COLORED);
  paint.DrawLine(0, 0, 40, 50, COLORED);
  paint.DrawLine(40, 0, 0, 50, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 72, 120, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawCircle(32, 32, 30, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 200, 120, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawFilledRectangle(0, 0, 40, 50, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 72, 200, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawFilledCircle(32, 32, 30, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 200, 200, paint.GetWidth(), paint.GetHeight());

  /* This displays the data from the SRAM in e-Paper module */
  epd.DisplayFrame();

  /* This displays an image */
  epd.DisplayFrame(IMAGE_BUTTERFLY);

  /* Deep sleep */
  epd.Sleep();
}

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

}

When I run the code, I get the following messages
In file included from /home/beingpool/Arduino/epd4in2-demo/epd4in2-demo.ino:28:
/home/<user>/Arduino/libraries/epd4in2/epd4in2.h:64: warning: "GET_STATUS" redefined
   64 | #define GET_STATUS                                  0x71
      |
In file included from /home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/Arduino.h:157,
                 from /home/beingpool/.var/app/cc.arduino.IDE2/cache/arduino/sketches/96EFEDEA56FF573B678089A960FFC685/sketch/epd4in2-demo.ino.cpp:1:
/home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/USB/USBCore.h:23: note: this is the location of the previous definition
   23 | #define GET_STATUS     0
      |

I updated the question to include the error message I get when I compile the code. I honestly don't know too much about what the issue is that I'm trying to solve, I'm first and foremost looking to understand what the issue even is. It seems to me that these two files that define GET_STATUS need it to be two different values, and I don't know how to make them work together with a single definition.

read the second line of the message

There is no generic meaning in GET_STATUS. Apparently both libraries use the very same identifier for their own different purpose.
If you do not use GET_STATUS in your sketch, you can remove the definition before the inclusion of "epd4in2.h", like this:
#include <SPI.h>
#undef GET_STATUS
#include "epd4in2.h"

// ...

Thank you, this answers my question


text:
Good practice to assign shift-register pins at the same time?
I'm new to bit register manipulation and am trying to set input and output values of some pins. The code sample I have on hand does it this way::
DDRD |= (1 << 2);
DDRD |= (1 << 4);
DDRD &= ~(1 << 5);
PORTD |= (1 << 2);
PORTD &= ~(1 << 4);
PORTD &= ~(1 << 5);

I have two questions:

This is part of a code where I'm attempting to determine the time for a capacitor's discharge between pins 2 and 4. The arduino helpfiles mention that there may be a benefit to triggering both pins at once. Therefore: Is it is it possible to do DDRD |= B00010100; and PORTD |= B00000100; or combine the first three DDRD  lines so it happens simultaneously, or does it have to be separately called?

Why is it PORTD &= ~(1 << 4) and not PORTD |= ~(1 << 4);Can this conflict with the previous state of PORTD.

(1 << 4) is 00010000,  they are interchangeable ... ~(1 << 4) is the inverse 11101111 ... think about what the OR function does and what the AND function does

so it happens instantaneously ... maybe you wanted to say simultaneously

OK, thanks. Writing this out in a simplified form helps. Since & only returns 1 if a = 1, and b = 1, therefore 0 & 0 = 0, and 1 & 0 = 0 which is exactly what we want no matter what happens. On the other hand 1 & 1 = 1, so anything on remains on, and 0 & 1 = 0 so what was off remains off.

Yes, sorry simultaneously. I was quoting from the Arduino help page but didn't add its context.  If I'm timing a capacitor discharge between pins 2 and 4, is there a benefit to triggering both pins at once instead of doing it line by line? eg B00010100 vs each pin individually?

Its context for the question. The original is because I don't know how it affects timings. It appears my question wasn't properly phrased from your feedback. I've amended it accordingly. Thanks.

DDRD |= (1 << 2);
DDRD |= (1 << 4);

The equivalent to that is:
DDRD |= (1 << 2) | (1 << 4);

However I prefer bit because it does the shift for you:
DDRD |= bit(2) | bit(4);

Why is it PORTD &= ~(1 << 4) and not PORTD |= ~(1 << 4);

PORTD &= ~(1 << 4) is turning a bit off. First you invert the sense of the bit with the ones complement operator (~) and then by anding it, it means that all bits are retained except that one. So this is basically turning bit 4 off. If you used |= it would turn all of the other bits on.
Equivalent code:
PORTD &= ~bit(4);

Based on your example you meant bit 5 not bit 4.

PORTD |= (1 << 2);
PORTD &= ~(1 << 4);
PORTD &= ~(1 << 5);

That is turning on bit 2, and turning off bits 4 and 5, and leaving the rest unchanged.

Thanks. In that case would DDRD &= B00000000; DDRD |= B00010100; have a similar result ...

If you do DDRD &= B00000000; then you are setting all bits to zero. So the simple equivalent to the above would be:
DDRD = B00010100;

This is a straight assignment, so you don't need to clear any bits.
Or, you could write:
DDRD = bit(2) | bit(4);

Do you know if bit() faster or is it cleaner compared to 1 << x; or is it better for me to hook up a scope to test this myself?

It is exactly the same. bit is just a #define  in the Arduino.h file, as follows:
#define bit(b) (1UL << (b))

So all it does is save you writing the brackets and the shift left operator. It expands out to the same as what you were writing and thus will execute at the same speed, and take the same amount of memory.

Thanks. In that case would DDRD &= B00000000; DDRD |= B00010100; have a similar result to your DDRD |= bit(2) | bit(4); DDRD &= bit(3) | bit(6); In my mind this first sets everything to input, then sets bits 2 and 4 to output. The malus would be that it changes all other settings due to the first DDRD &= B00000000 section?

See expanded answer.

Thanks. Do you know if bit() faster or is it cleaner compared to 1 << x; or is it better for me to hook up a scope to test this myself?

@Letshin See additional paragraph in answer.


text:
MacBook + BLE Microcontroller Incompatibility?
I've programmed an Adafruit Feather nRF52840 board to send MIDI signals to my computer via BLE. I can confirm that the board pairs successfully with an Android phone and a Windows PC, but my laptop (MacBook Pro 2021) will not recognize the board; it does not appear in the Bluetooth menu as an option for pairing. I've tried the following troubleshooting options:

Turned bluetooth off & on on laptop
Turned device off & on
Added the name of the board in the code (advertisement.complete_name = "BOARD_NAME")
Downloaded Bluefruit Buddy, Bluefruit Connect & Bluetility to find any BLE signals coming from the board (verdict: no trace!)
Tried a BLE smart dongle
Unpaired/forgot device from Android phone, attempt to re-pair with laptop
Attempted to connect the device via Apple’s Audio MIDI setup (https://support.apple.com/guide/audio-midi-setup/set-up-midi-devices-ams875bae1e0/mac)
Tried steps 1-7 with two additional MacBooks (2016 & 2022)

I know that the BLE pairing functionality of the board is working, since it consistently pairs with an Android phone and a PC laptop; I just cannot figure out why it won't pair with my MacBook. I want to resolve this issue and ensure that the board can be used across platforms.
Are there any other troubleshooting actions I should try?

try pairing with a Windows PC and a Linux PC

this is not a question about the Arduino until you determine why a Mac does not accept the connection

@jsotola, I tried pairing with a Windows PC yesterday and the board showed up in the Bluetooth menu and paired successfully. This is a good sign, however I still need the bird to work across all platforms.
I posted the question in this forum to see if possibly there was any hardware setting on the board that may impact its ability to pair with a Mac (i.e. double-tapping the reset button or holding down for a certain amount of time).  Generally, I just wanted to know if anyone else had run into this issue or could suggest helpful ways to troubleshoot beyond what I’ve already done.

What macOS version do you have?

Ventura for two computers, Catalina for the 2016 MacBook

Have you tried Bluefruit Connect from Adafruit? It is available in the Apple store. Don't quote me on this, but I read a long time ago, that Mac requires encryption for a BLE device to be recognized, whereas, most of the out-of-the-box Adafruit example doesn't use it.
I had a similar issue. And I used Bluefruit Connect to connect my device to my Mac.

Item not available in my country? Got a download link to the app not involving the "app store"? What versions of OSX are supported?

Unfortunately, I can't seem to find the information about what OSXs are supported on the app page, but I have "macOS 10.14".

Too bad it's not available in other countries besides the US.

That's unfortunate. Also, I found what OS are supported: "Requires macOS 12.0 or later and a Mac with Apple M1 chip or later."

Yes, I have tried Bluefruit Connect, Bluefruit Buddy & Bluetility.  None of these apps are able to detect the board.


text:
Porting the FastNoise c++ library to Due
I'm trying to use the FastNoise library with a Due, however, I get something like the following errors, when I try to complie.
error: 'abs' was not declared in this scope
error: 'mt19937' is not a member of 'std'
error: 'uniform_int_distribution' is not a member of 'std'
so I added the following:
#include <cstdlib>
#include <cmath>
#include <random>

which solved most of the problems, however it still says printf hasn't been declared. So I tried to edit cstdio to comment out the #undef printf, but it just brought back the full list of error messages, so that's not the solution. I googled some solutions but none of these seem to work. Do you have any suggestions I should try?
I'm not trying to use printf, just want to use the library.
Thanks for any help.

Also asked here: https://forum.arduino.cc/index.php?topic=579997.0 and we still don't know which library you are trying to port to the arduino.

apologies for spamming, this one: https://github.com/Auburns/FastNoise

I don't know how the std and algorithm extensions are used in the gcc compiler for arduino. They are not used a lot. I think it should be possible to convert it to normal c++ code. The printf might be connected with the std and the cstdlib extension. The arduino preprocessor includes most common include files, only extra libraries needs to be included. Your title of this question is about FastNoise, but the problem is how to port code to the arduino. Perhaps you can change the title of the question to get attention from experts.

The FastNoise library compiles as it is for the Arduino MKR and Arduino Zero, but there is a "not cool" issue for the Due: https://github.com/arduino/ArduinoCore-samd/issues/308
A issue with assert can easily be solved, but the #include <algorithm> and #include <random> are somehow linked to a printf function.
I thought it was very hard, but then @Juraj wrote in his answer about the simple solution to comment out the #undef printf line.
In the file cstdio is a list of about fourty #undef lines. Only the printf requires to be commented out.
// #undef printf

The file is located in the hidden "Arduino15" folder in the build environment for the Due: Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio
Then it will also compile for the Arduino Due (even without removing the assert). There are many warnings.
I was able to run it on a SAMD21 processor and it produces random numbers. However, I am not sure that those numbers are correct. I don't know if the many compiler warnings can be ignored.
#include <FastNoise.h>

FastNoise myNoise; // Create a FastNoise object

float heightMap[32][32]; // 2D heightmap to create terrain

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("FastNoise");
  delay(1000);

  myNoise.SetNoiseType(FastNoise::SimplexFractal); // Set the desired noise type

  for(int x=0; x<32; x++) {
    for(int y=0; y<32; y++) {
      heightMap[x][y] = myNoise.GetNoise(x,y);
      SerialUSB.println(heightMap[x][y]);
    }
  }
}

void loop() {
}

Do you know the XY Problem? You did not explain the reason for trying to make that library run on a Arduino Due. Perhaps there is an other way for what you want to achieve.
The Arduino Due was a major update for the Arduino boards, but nowadays some say to avoid the Arduino Due because it has issues (hardware and software).

I have updated my answer with help of the answer from @Juray.

Thank you guys, I tried to remove that line before, but it just say the same error messages when no library was included (it misses the abs function and so on).
Moreover, I was unable to compile it for Zero or MKR. Is it possible that something is missing for me? I have the regular Arduino IDE and downloaded the latest boards. (the error message is around 1000 lines, maybe these are the warnings you mention? however for me it does not compile)

I'm experimenting with LEDs with the FastLED library and serial communication, but the communication wasn't perfect since these LEDs (WS2812B) require precise timing, and the interrupts are disabled while the Uno is sending the LED data. So on the FastLED help page advises to switch to Teensy or Due. Since Due seemed the easier step from the Uno, I chose that. And with the added computational capacity I thought I can use the FastNoise library for noise generation instead of the FastLED one (which is fine, but has its faults). So I'm not persisting on using Due at all.

Do you think the FastNoise could be run on Teensy? Or that would be even harder to make work? Teensy seems way more powerful on floating point math (which this library uses) than Zero. Unfortunately I'm not even sure how much processing power I need exactly, I was just about to check how fast the Due is with the library (since I had to switch anyway because of the serial communication issue with the Uno)..

@Gergo, you might try to get the FastNoise library files again, maybe something has been changed. It compiles for the zero and mkr and by commenting out that line also for the due. I have no experience with the teensy. Stackexchange is about questions and answers. You could update your question that you want to use it for ws2812b leds and that the teensy or due is advised, and so on.

FastNoise did not change in the last year or so according to github, so I was skeptical about downloading it again, but did it nevertheless, and now it complies. I'm not sure what went wrong, since I should have the same FastNoise, as it did not change seemingly. Anyways, thank you very much for your time and help in this matter. Additionally thank you for the guidance how to use this forum.

The workaround is in the issue found by Jot.
In file
C:\Users\aaaaaa\AppData\Local\Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio
comment the line
#undef printf
and it will compile

Thanks, I missed that. I have updated my answer.

@Jot, the line must be removed


text:
Trouble understanding connection diagram

The image shows a way of connecting an optocoupler.
My problem comes from how the emitter (Q1 in the image) is connected. The emmiter goes to a resistance going to ground and to v_out. When i try to add this to my circuit the pin that is suppost to be receiving data, the v_out pin goes silent. If i remove the resistance going from the emitter to ground and just have vout to the emitter everything works fine.

Is the optocoupler connected to an arduino board? What is your circuit?

My first reaction is "YIKES- That's 18Volts going into the arduino input pin?". If the Ardiono in question is the kind that has an on-board 5V regulator, use that in place of the 18V at Q1's collector, put the resistor back in, and try again. Obvious, but don't forget to configure your input pin and an INPUT. You also might want to try a different input pin because as much as I hate to say it, you're first experiment could have destroyed the input circuit for the first pin.

please explain what this means .... pin goes silent

pin that is suppost to be receiving data .... which pin are you talking about?

Normally you would connect the ground (0V) side of resistor R2 to the ground of the Arduino and the other side of R2 (which is also connected to the emitter of Q1) to an input pin of the Arduino. When the LED is energized by pressing the button it sends light to the fototransistor. Because of this the phototransistor starts conducting current (I1) which causes a voltage drop I1xR2 over R2. When this voltage is high enough the input pin will show a "1" (or HIGH) when read out.  "High enough" means >= 0.7 x Vcc, where Vcc is the voltage of the powerline to the Arduino.
The website from which the picture in your question originates (here) has an extensive article about the working and implementation of optocouplers. It also shows examples of alternative circuits.

maybe i'm misunderstanding here, but something like this? https://imgur.com/6xZE5gx Here the red wire goes to the collector. the emitter goes to ground via resistor and sends signal to the Arduino via the gray cable

I would leave away the resistor in the collector line. Are the resistors from the picture the real ones you use (how did you get a non standard resistor of 250 Ohm?). Personally I have more faith in the circuit of fig. 14 in the datasheet: https://www.vishay.com/docs/81181/4n35.pdf