text:
Attiny85 not able to understand data from 433Mhz using VirtualWire.h
The basic plan is to have a Attiny85 pass information from a 433Mhz RF module to another chip/Arduino via I2C using VirtualWire and Wire libraries. I have been able to make this system work on their own using Arudino Nano's to debug, but the Attiny85 (A85) seems unable to grab the data from the RF 433 Mhz.
So have spent a few days doing some more research, and basically putting each component separate, to make sure what is being sent is correct.

433 Mhz transmitter is working by sending a 9 digit number, using VirtualWire.h.
Nano with a 433 Mhz receiver is receiving 9 digit
number, VirtualWire.h.
Attiny85 is sending either a no data, or the 9 digit number, to another Nano using Wire.h.
The Nano is getting only No Data, so the I2C is working between A85 and Nano.

Attiny85, on Pin 1 (pin 6 on chip) is not getting any data from the 433 Mhz, which works on (2). I connect the GND of the 433 RX to the chip.
Here is the Receiver code:
#include <VirtualWire.h>
#include <Wire.h>
void setup() {
  pinMode(A3, OUTPUT);
  Wire.begin(); // join i2c bus (address optional for master)
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(4000);   // Bits per sec
  vw_set_rx_pin(1);
  vw_rx_start();       // Start the receiver PLL running
}
void loop() {
  uint8_t buf[15];
  uint8_t buflen = 15;
  if (vw_get_message(buf, &buflen)) // Non-blocking
    {
      digitalWrite(A3, LOW);
      Wire.beginTransmission(8); // transmit to device #8
      for (int i = 0; i < buflen; i++) {
        Wire.write(buf[i]);
      }
      Wire.endTransmission();    // stop transmitting
    } else {
      digitalWrite(A3, HIGH);
      Wire.beginTransmission(8); // transmit to device #8
      Wire.write("no DATA");
      Wire.endTransmission();    // stop transmitting
     }
}

Here is the Transmitter code:
#include <VirtualWire.h>
int xPin = A7;
int yPin = A6;
int buttonPin = 2;

int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const char *controller;
void setup() {
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(yPin, INPUT);
  pinMode(xPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  vw_set_ptt_inverted(true); //
  vw_set_tx_pin(12);
  vw_setup(4000);// speed of data transfer Kbps
}

void loop(){
   xPosition = analogRead(xPin);
   yPosition = analogRead(yPin);
   buttonState = digitalRead(buttonPin);
if(xPosition > 0 || yPosition > 0) {
  String Data = (xPosition + yPosition);
  controller = Data;
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone

} else {
  digitalWrite(13, 0);
  digitalWrite(4, 1);
  controller = "#s0_0";
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone
}

Serial.println(controller);

}

So basically the A85 is not getting past if (vw_get_message(buf, &buflen)) { on pin 1. But does when using the Nano on pin D2, from the same transmitter, but not at the same-time of-course.
Am I using the wrong Pin on the A85? Chip pin 5 and 7 are used for the I2C so it only leaves analog pins so not sure they would work either. I also tried 8 Mhz and 1 Mhz when loading the A85.
I  have tried different Cores as suggested from Google, different versions of VirtualWire and clocked the Attiny 1Mhz, 8Mhz and 16Mhz. None of have worked.

Not sure what else I am missing?

@ChrisStratton Hi, the Nano is just for debugging, rather than using LED's as I wanted to make sure the numbers being transmitted are correct.  The end product will eventually be a Attiny84a.  The issue is Servo.h and VirtualWire.h do not mix (Both use Timer1), hence the work around, and to make the circuit smaller.

Have you tried using the Radiohead  library? I know you said you tried different versions of Virtual Wire. The RH_ASK class works on a 328p and a nano for sure and they claim a simple Rx program can run on a ATTiny85. They have documentation under RH_ASK regarding the changes you need make to the library.
Another possible fix is to edit the Virtual Wire library files, they might have variables like "Max_payload" (Radiohead does) whose size can be decreased.
I haven't actually read the Virtual wire library, but I am sure Radiohead should fix your problems.
If this doesn't work, do you have an oscilloscope? Maybe we can try debugging it like that.
Edit: Maybe try commenting out the vw_set_ptt_inverted line first. I don't think you are using the DR3100. Might not make a difference because you haven't actually set a pin for ptt.
Next thing you can try is just connecting the data pin of the Tx to the Rx. You should be able to check if the module is actually connected to the ATTiny with this.


text:
How to count the voltage pulses of a digital temperature sensor using Arduino Mega Atmega2560?
I have a digital temperature sensor which gives digital output in the form of current pulses. The number of pulses corresponds to a particular temperature.
I have converted the current pulses to voltage pulses using transistor as a level shifter. I want to count the number of pulses for a time interval of 50ms each time.
Please help me with the algo and the code.

Please give us more information such as which temperature sensor you are using, your circuit diagram, what you have tried and perhaps your code so far. See [ask].

I'm using lmt01 digital sensor . I'm a beginner in coding . So counting the no. Of current pulses is also fine .

There are function called pulseIn which probably need exactly what you want.
Just set a variable with the current 'time' (millis, start counting until the current time reaches 50 ms later.
So something like (not checked):
unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  pulses++;
}

PIN is a constant or variable that defines the pin number to check, LOW is to check low pulses, you also can use high, and optionally you can add a timeout. For example, you can use the timeout to check the last timeout is within the 50 ms region. Or to be more precise, check if the pulse was within the same 50 ms:
unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  if (timer + 50 < millis())
  {
    pulses++;
  }
}

source: Stack Exchange

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

sort: votes


text:
Arduino Pro Mini (5v) I2C pullups
I recently bought an ESP-WROOM-32 module and I want it to talk to my Pro Mini via I2C. Do I have to pull-up the lines to the 3.3v side (ESP32)? Since the Pro Mini runs at 5v, I think it's a bad idea to pull-up the lines from that side.

That would work. 3.3V is high enough for the 5V arduino to register as a HIGH. Just make sure you disable the internal pull up resistors on the Arduino. The default I2C library enables those for some reason (which it shouldn't imho).

@Gerben, the i2c signal needs to be 3.5V for an atmega328p at 5V. A digital input requires 3.0V, but the i2c needs 3.5V.

Indeed; Vih is 0.7*Vcc, so according to the datasheet you'd need at least 3.5V. But my guess is it will work just fine. If not, you could use two mosfets to create a I2C level shifter

note that you can feed your esp32 3.6v within spec.

@Gerben It works, I pulled-up the lines with 4k7 resistors on 3v3 side. Since the ESP32 has a higher core speed, I need to put a 5ms on every request for the Pro Mini to keep up.

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


text:
ESP8266(01) doesn't work when servo connected to GPIO-2
the wiki here says http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations
0 Low
1 High
x floating
MODE                   GPIO15   GPIO0   GPIO2
SDIO (BootSDCard)       1       x        x
UART (UploadCode)       0       0        x or 1
FLASH (NormalRunning)   0       1        x or 1

Can connecting my GPIO 2 to a servo Signal Wire cause it to go LOW? because some how my ESP8266 doen't boot when I have a servo hooked up to it.
I tried to change it to RX (which is GPIO3 on ESP8266) and everything seems to work fine. But I wanna know the reason why GPIO2 didn't work.
Thank you.
p/s:http://www.goodluckbuy.com/ld-1501mg-metal-gear-digital-servo-17kg-for-rc-robot.html this is the servo, if it matters. Also GPIO-2 works when I use another servo of different type instead (I don't know its name though)

only one conclusion: the servo pulls the input down

add external pull-up to io 2

It's what Juraj said.

add external pull-up to io 2 -Juraj

sovled it

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


text:
What might be the errors of my codes?
I tried to imitate lagsilva's clock projects using Arduino Uno and made the circuitry, then I've tried to upload the main source code of the author but noticed that it didn't work, so I've edited the sketch and modified some of the details. When uploading it to the board, it seemed fine but there was nothing on the board and the project. Here are the codes:
Lagsilva's:
/*  4-Stroke Digital Clock With Two MAX72XX LED Matrix & RTC
              V1.1 - 02.Feb.2018
               Author: LAGSILVA */

     #include <LedControl.h>                   // Library for LED Matrix - MAX72XX
#include <Wire.h>                         // Library for DS3231 - Pins of Arduino UNO: A4 (SDA), A5 (SCL)
#include <DS3231.h>                    // Library for Real Time Clock
// Global Variables
byte hh, mm;                              // Hour, Minute
byte uH, uM, dH, dM;                      // Units Hour, Units Minute, Teens Hour, Teens Minute
byte p = 0;                               // Plot Mode (Position of Digits: Up/Down)
int RPM = 0, lastRPM = 0, pinRPM = 0;     // RPM, Last value of RPM, Analog Pin for RPM
byte seq = 1;                             // Start Fire sequence

/*
  Pin numbers do Arduino para conexao com o MAX72XX (matriz de LED com controlador MAX72XX)
  pin 7 is connected to the DataIn (DIN)
  pin 6 is connected to LOAD (CS)
  pin 5 is connected to the CLK (CLK)
*/

LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, int CS, int numDevices)

// Array of Digits - (0 to 9) - Size 5x3

byte num[10][3] = {

  {0xF8, 0x88, 0xF8}, // 0
  {0x00, 0xF8, 0x40}, // 1
  {0xE8, 0xA8, 0xB8}, // 2
  {0xF8, 0xA8, 0x88}, // 3
  {0x78, 0x20, 0xE0}, // 4
  {0xB8, 0xA8, 0xE8}, // 5
  {0xB8, 0xA8, 0xF8}, // 6
  {0xC0, 0xB8, 0x80}, // 7
  {0xF8, 0xA8, 0xF8}, // 8
  {0xF8, 0xA0, 0xE0}, // 9

};

void setup() {

  setSyncProvider(RTC.get);    // Function to read RTC (Real Time Clock)
  //setSyncInterval(3600);                // Set the number of seconds between re-sync
  //setTime(14, 59, 00, 03, 02, 2018);    // Set the Time and Date
  //RTC.set(now());                       // Set the RTC time

  // Setup of Display "0"
  lc.shutdown(0, false);                // Wakeup Display "0"
  lc.setIntensity(0, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(0);                   // Clear Display "0"

  // Setup of Display "1"
  lc.shutdown(1, false);                // Wakeup Display "1"
  lc.setIntensity(1, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(1);                   // Clear Display "1"

}

void loop() {

  hh = (11);
  mm = (14);

  uH = hh % 10;
  dH = hh / 10;

  uM = mm % 10;
  dM = mm / 10;

  // Plot Hours

  for (byte k = 0; k < 3; k++) {

    lc.setRow(0, k + 5, num[dH][k] >> (p + 2));
    lc.setRow(0, k + 1, num[uH][k] >> (3 - p));

  }

  // Plot Minutes

  for (byte k = 0; k < 3; k++) {

    lc.setRow(1, k + 4, num[dM][k] >> (3 - p));
    lc.setRow(1, k , num[uM][k] >> (p + 2));

  }

  // Plot Fire Sequence: 1-3-4-2 (4 cyl: 1-3-4-2 or 1-2-4-3 or 1-4-3-2)

  if (seq == 1) {                               // Fire Cyl #1
    lc.setLed(0, 6, 0, true);
  }

  if (seq == 2) {                               // Fire Cyl #3
    lc.setLed(1, 5, 0, true);
  }

  if (seq == 3) {                               // Fire Cyl #4
    lc.setLed(1, 1, 0, true);
  }

  if (seq == 4) {                               // Fire Cyl #2
    lc.setLed(0, 2, 0, true);
  }

  seq = seq % 4 + 1;

  // RPM reading

  RPM = analogRead(pinRPM);                     // Potentiometer reading

  RPM = map(RPM, 0, 1023, 1, 9);

  if (RPM <= 8) {
    lc.setLed(1, 7, 8 - RPM, true);
    lc.setLed(0, 0, 8 - RPM, true);
    delay(300 / RPM);                           // Speed setup by potentiometer (100 - 800 RPM)

    if (lastRPM != RPM) {
      lc.setRow(0, 0, 0);
      lc.setRow(1, 7, 0);
      lastRPM = RPM;
    }

  }

  p = !p;                                       // Switch the position of digits (Up x Down)

}

My modification was this:
#include <Wire.h>
#include <DS3231.h>
#include <LedControl.h>
// Global Variables
byte hh, mm;                              // Hour, Minute
byte uH, uM, dH, dM;                      // Units Hour, Units Minute, Teens Hour, Teens Minute
byte p = 0;                               // Plot Mode (Position of Digits: Up/Down)
int RPM = 0, lastRPM = 0, pinRPM = 0;     // RPM, Last value of RPM, Analog Pin for RPM
byte seq = 1;                             // Start Fire sequence

LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, int CS, int numDevices)

// Array of Digits - (0 to 9) - Size 5x3

byte num[10][3] = {

  {0xF8, 0x88, 0xF8}, // 0
  {0x00, 0xF8, 0x40}, // 1
  {0xE8, 0xA8, 0xB8}, // 2
  {0xF8, 0xA8, 0x88}, // 3
  {0x78, 0x20, 0xE0}, // 4
  {0xB8, 0xA8, 0xE8}, // 5
  {0xB8, 0xA8, 0xF8}, // 6
  {0xC0, 0xB8, 0x80}, // 7
  {0xF8, 0xA8, 0xF8}, // 8
  {0xF8, 0xA0, 0xE0}, // 9

};

void setup() {

  //setSyncInterval(3600);                // Set the number of seconds between re-sync
  //setTime(19, 07, 59, 06, 03, 2018);    // Set the Time and Date
  //DS3231.set(now());                       // Set the RTC time

  // Setup of Display "0"
  lc.shutdown(0, false);                // Wakeup Display "0"
  lc.setIntensity(0, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(0);                   // Clear Display "0"

  // Setup of Display "1"
  lc.shutdown(1, false);                // Wakeup Display "1"
  lc.setIntensity(1, 4);                // Set the Brightness of Display (0 to 15)
  lc.clearDisplay(1);                   // Clear Display "1"

}

void loop() {

  hh = (21);
  mm = (32);

  uH = hh % 10;
  dH = hh / 10;

  uM = mm % 10;
  dM = mm / 10;

  // Plot Hours

  for (byte k = 0; k < 3; k++) {

    lc.setRow(0, k + 5, num[dH][k] >> (p + 2));
    lc.setRow(0, k + 1, num[uH][k] >> (3 - p));

  }

  // Plot Minutes

  for (byte k = 0; k < 3; k++) {

    lc.setRow(1, k + 4, num[dM][k] >> (3 - p));
    lc.setRow(1, k , num[uM][k] >> (p + 2));

  }

  // Plot Fire Sequence: 1-3-4-2 (4 cyl: 1-3-4-2 or 1-2-4-3 or 1-4-3-2)

  if (seq == 1) {                               // Fire Cyl #1
    lc.setLed(0, 6, 0, true);
  }

  if (seq == 2) {                               // Fire Cyl #3
    lc.setLed(1, 5, 0, true);
  }

  if (seq == 3) {                               // Fire Cyl #4
    lc.setLed(1, 1, 0, true);
  }

  if (seq == 4) {                               // Fire Cyl #2
    lc.setLed(0, 2, 0, true);
  }

  seq = seq % 4 + 1;

  // RPM reading

  RPM = analogRead(pinRPM);                     // Potentiometer reading

  RPM = map(RPM, 0, 1023, 1, 9);

  if (RPM <= 8) {
    lc.setLed(1, 7, 8 - RPM, true);
    lc.setLed(0, 0, 8 - RPM, true);
    delay(300 / RPM);                           // Speed setup by potentiometer (100 - 800 RPM)

    if (lastRPM != RPM) {
      lc.setRow(0, 0, 0);
      lc.setRow(1, 7, 0);
      lastRPM = RPM;
    }

  }

  p = !p;                                       // Switch the position of digits (Up x Down)

}

Anyone could help me please, thank you!

Did you try first a sketch to see if actually something can be displayed at all? To rule out, the circuit is OK?

I tried both of the sketches but none worked, so I was wondering if there might be some errors on the codes. Yes, sir, the circuit (as shown) was built in line with the diagram.

If you try a default / example sketch, high likely there is a problem in your circuit. First try a/the default sketch for an 8x8 matrix separately, than the other, than you can continue with this more 'advanced' sketch.

I have doing this project for a week or so and repeatedly checked if there are errors in the circuit I might got, and based on (I think) 7-10 times of checking the schematic diagram, there are no errors on the circuit. Okay sir, I'll try. Thank you!

run the example sketch for the martix

But did you EVER see the matrix lighting up? If not, do as I and Juraj said: try the example sketch first, and work up from there to the sketch you really want to use (in your post). Double check voltages if needed (using a multimeter, analyzer or oscilloscope), check pin numbers are correct (in your code/circuit). Only if you got that working, you know at least the circuit and starting code is ok.

LedControl lc = LedControl(7, 5, 6, 2);  // LedControl(int DIN, int CLK, - your picture is not in line with this entry. Pin 7 connected to CLK on the picture, and your code say CLK line connected to pin 5. And you claim you have checked your wiring?

what is the part number on the LED matrix module?

@smajli Sir, when I saw the changes in the codes and in the diagram, I've changed immediately the wirings on my arduino board.


text:
Trying to get a ILI9341 TFT to work with UTFT library
I'm currently trying to fill out the constructor but I'm not sure what's what...
The constructor of the UTFT library goes as follows:
UTFT(Model, SDA, SCL, CS, RST[, RS]);

Where the last bit is optional.
SDA meaning Serial Data, SCL serial clock, CS chip select, RST reset and RS register select.

This is the screen I'm trying to connect. As far as I understand:
SDI (MOSI) goes to SDA
SCK goes to SCL
CS  goes to CS
RST goes to Reset?
RS goes to D/C?
But it doesn't work. What am I missing...
Here's my full code:
#include <UTFT.h>

//Digital Pins:
//53 = MOSI
//52 = SCK,
//10 = CS
//6 = RS
//7 = D/C
UTFT myGLCD(ILI9341_S5P,53,52,10,6,7);

void setup() {
    myGLCD.InitLCD(PORTRAIT);
    myGLCD.clrScr();

}

void loop() {
    myGLCD.fillScr(0,0,255);

}

I did get the screen to work with the Adafruit_GFX library. I used 1k resistors between all of the data lines, including reset. When using the screen with the GFX library I connected reset to 3,3v.

SDA/SCL is I2C (Wire). MISO/MOSI/CLK/CS is SPI

from where do you have the UTFT library? I don't see one in Library Manager

@Juraj found it on rinky-dink electronics: http://www.rinkydinkelectronics.com/library.php?id=51

the library is not for SPI connected display

it doesn't work does not describe the observed results.

@Juraj , thank you for clearing that up. I will look out for a different library then. Can you tell me how you found out that it's not for SPI displays, apart from looking at SDA/SCL being for I2C? I'm still new to arduino.

the library you linked has documentation in the downloaded zip. and of course there is the source code not using SPI

and reset of a device should be connected to a gpio pin, to be able to reset the device from sketch


text:
What is a safe way to power arduino nano with 7.4V Lipo battery?
I'm trying to power Arduino Nano with 7.4V LiPo battery and use it to run 2 DC motor using L293D. I have figured out how power it with the connection just like in the figure below(the diagram uses Uno and the battery is 9V but try to imagine it as Nano and 7.4V).  I also found another way to power it by connecting the red wire from battery to Vin on the Arduino instead of connecting it to the positive power rail.
So, my question is which is a safer way to power it and what is the difference and risk of one the way I mention.

you ask if it is ok to connect the battery to Vin instead of the power rail of the breadboard from where it is connected to the Vin? there is no difference

What I mean is that, instead of having the red wire on the power rail, connect it directly to the Vin of the Arduino. Both of this works but my question is there any difference and which is safer to do?

on the fritzing schema the battery is connected to 5V. it would damage the Atmega. the battery should be connected to Vin. And it makes no difference if direct, over the power rail or with T junction.

Connect it via the Vin pin. That way the 6-8.4 volt of the battery will go through the voltage regulator on the Nano, giving you a stable 5v.
What you show in your diagram is the wrong way of connecting the battery. The absolute maximum you can supply to the Arduino's 5V pin is 6 Volt. Atmel recommends no more than 5.5V. So your battery exceeds this when it's full.

sorry, where in the question you see Vcc pin mentioned?

I thought the Arduino pin was labeled Vcc, but it was 5V. Updated my question.

right. on the fritzing it is connected to 5 V. that is wrong

That is what I was trying to say.


text:
Arduino UNO reset using SIM800L
I'm using the SIM800L module but i've problems. I'm triying to connect it to the Elegoo UNO i've, but it restarts at all times. Also the led of signal strengh blink every second, so i dont get signal.

I also upload a video to Youtube to explain the problem, this is the link.
Thanks in advance!

do not connect Reset RST

reset pin of a device should be connected to a gpio pin, to be able to reset the device from sketch

@Juraj Doesnt work, now the module seems to restart, the indicator led start blinking and after that get paused for a few secons and start again, idk what to do :(

you did not connect it or you connected it to some io pin? the library you use, should have a parameter with the reset pin number and taking care of setting that pin

@Juraj i didnt connected, you said that i need to connect it to a io pin and define it on the code?

When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.
You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.
The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.
If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.
If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.
The usual required state for reset is LOW so the output must be HIGH for the device to work.
Some tutorials and libraries require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.

Besides the RST pin situation that the others pointed out, you're not going to do much with the way you're powering the module. It might turn on, but you will never be able to register on the network.
You have to power the module with an external power source and common the ground.
Also, if the module you're using is the one on the image, you might need a logic level shifter to use the Tx-Rx connection.


text:
Splitting SCL and SDA pins
For a robotics project I am using an MCP23017 I/O Port Expander in order to have more pins available, and I am also using a PS2 controller for input. Both of these require pins 4 and 5 (because these are the data and clock pins). I was wondering if I can use a breadboard to simply connect these two pins to both devices in order to provide both of them with data and clock pins.
I am using an Arduino UNO and a playstation 2 controller with the following guide:
http://www.techmonkeybusiness.com/using-a-playstation-2-controller-with-your-arduino-project.html

Nowhere in that link does it mention using the I2C pins. The PS2 uses a bitbanged custom protocol. It can use any pins. You can only use I2C pins for I2C.

You are confusing pins here. In the library you mention there is a function call to set up the gamepad:
 ps2x.config_gamepad(5,4,3,2, false, false);
 //setup pins and settings: GamePad(clock, command, attention, data, Pressures, Rumble)

That is digital pins 5, 4, 3 and 2.
I2C uses analog input pins A4 and A5 on the other side of your Uno board.

An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.
But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function ps2x.config_gamepad().  In it's parameters you can set the pins that the library will use.


text:
What is better approach for non blocking pid algorithm?
I'm developing software side for 3 axes robot where are 360° continuous rotating servos used Documentation here
these servos have its own feedback system so it's possible to control it's position via pid system, when im using only one PID algorithm in clear sketch just for this pid everything working OK but when I want to use multiple PIDs there are problem with delays and every next function that is used in the sketch will result in bigger delays that make these servos flicking because it's executed in main function
int pinFeedback = pin_comes_here;

float tHigh = 0;
float tLow = 0;
int tCycle = 0;
float dc = 0;
float angle = 0;
float dcMin = 2.9;
float dcMax = 97.1;

void setup() {
  pinMode(pinFeedback, INPUT);
}

void loop() {
    while(1) //From Parallax spec sheet
    {                                       //There is core of the problem
      tHigh = pulseIn(pinFeedback, HIGH);
      tLow = pulseIn(pinFeedback, LOW);
      tCycle = tHigh + tLow;
      if ( tCycle > 1000 && tCycle < 1200)
        {
          break; //valid tCycle;
        }
    }

  dc = (100 * tHigh) / tCycle; //From Parallax spec sheet, determine the percentage of the HIGH in the pulse

  angle = ((dc - dcMin) * 360) / (dcMax - dcMin + 1); //From Parallax spec sheet

  if (angle < 0)
  {
    angle = 0;
  }
  else if(angle > 359)
  {
    angle = 359;
  }

    //This is just angle calculation part, we have angle as output value from this algorithm so its possible to calculate error how much to left or right value from out target angle value and adjust servo position via standard servo library

}

Reason why i need non blocking angle calculating is that because with everything this, i need to be able to control angles from firmata protocol and not just firmata but there can't be anything else done in sketch and i mentioned everything else causing bigger delays between reading signal, calculating angle, adjusting position, and every next function that could be placed in main loop.
So i came to the point that i need to use timer and interrupts like servo library uses by creating something like basic servo library wraper where i create PID class that inherit Servo class members for sake of accesing servo members from one object (attach, write) and two different approaches came to my mind

This PID class could instead of waiting in while loop for pulseIn sacrifices another one Timer that could divide feedback signal period which is long 1,1millisecond (see documentation, heading: feedback signal) by checking if it's up or down every several microseconds and counting total signal uptime for period and then calculate angle and error and adjust position with inherited write() member for every object from one timer
Using attachInterrupt that could behave similar like pulseIn but outside of main loop for every object(with same approach with PID class with inherted servo class)

The main issue you have is that pulseIn() is completely blocking - and your while loop doesn't help much either.
The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in gated mode. Actually you need two timers, but the Arduino already provides you micros() that will do for one of them.
Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.
That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses micros() to work out the time between successive falling edges (should be about 1100us).  A little bit of maths is needed to calculate the time from the count.
It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it.  On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.
Of course, it goes without saying that you need a gated timer for each servo you want to sense...


text:
Trying to make sense of the coding style in Arduino libraries. (Particularly the Radiohead library)
I've been using the Arduino IDE for some time now, and I want to shift to coding for the bare AVR microcontroller. So I wanted to begin by porting required arduino libraries to C/C++.
I started with the Radiohead library, but I've noticed a lot of variables/tokens that are directly used without a definition for them. For example:
    // path :RadioHead/RH_ASK.cpp
#if (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
 #ifdef RH_ASK_PTT_PIN
    RH_ASK_PTT_DDR  |=  (1<<RH_ASK_PTT_PIN);
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #else
    RH_ASK_TX_DDR   |=  (1<<RH_ASK_TX_PIN);
    RH_ASK_RX_DDR   &= ~(1<<RH_ASK_RX_PIN);
 #endif
#else
    // Set up digital IO pins for arduino
    pinMode(_txPin, OUTPUT);
    pinMode(_rxPin, INPUT);
    pinMode(_pttPin, OUTPUT);
#endif

None of the tokens in this snippet like "RH_ASK_PTT_PIN" or  "RH_ASK_TX_PIN" were mentioned anywhere in the code before or any other file that was included.
I understand what the code does, but how does the compiler know what these tokens mean? I tried to compile this code using Atmel Studio but it gives me an error (As it should):
"RH_ASK_PTT_PIN" not declared in this scope
So how does this library work with the Arduino IDE?
Link to the library : https://github.com/PaulStoffregen/RadioHead
Also can someone suggest tags for this post? Its my first post here.

They're not defined. If you notice that whole block is wrapped in a #ifdef which will be false unless you're on some specific platform, where the platform defines those macros.
Everything else uses the last little bit:
pinMode(_txPin, OUTPUT);
pinMode(_rxPin, INPUT);
pinMode(_pttPin, OUTPUT);

You only need to care about that bit - nothing else is of any concern unless you're using a "RH_PLATFORM_GENERIC_AVR8" (whatever that is).

Thanks for the prompt reply, I understand that to rewrite this I don't need to care about the #ifdef block but how does this file compile in the first place without actually defining the macros? I added this library as a .zip file using the library manager of the Arduino IDE, the entire folder does not mention them.

The top two thirds of the block only gets compiled if they have been defined. Since they haven't been defined it gets completely ignored. C compiling is done in multiple phases. The first is the "preprocessor" that looks at the #ifdef etc bits and expands them where it can. The C compiler doesn't see the top part at all because the preprocessor deletes it.


text:
Is there a bridge needed to connect Pro Mini 3.3v to HC-05 (level 3.3v)?
I can't understand how to connect my arduino pro mini https://www.amazon.in/gp/product/B071ZCHW5P/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
To my HC-05 Bluetooth module https://www.ebay.in/itm/HC05-Wireless-Bluetooth-RF-Transceiver-Module-Serial-TTL/182970488321?ssPageName=STRK%3AMEBIDX%3AIT&_trksid=p2057872.m2749.l2649
There is a guide to connect them given here : http://www.instructables.com/id/Bluetooth-Serial-Adapter-for-Pro-Mini/
I am trying to follow this guide but it is for 5V version and involves shorting the diode on the pro mini plus a divider circuit.
Here is the circuit:
Apparently, there is an obvious difference in the circuit according to my components.
Please help me connect them correctly.
Thanks :)

Double check that your pro mini is a 3.3V (the comment on Amazon states it is NOT 3.3V version). If it is, and you confirm that the HC is 3V3 too, you don't need the voltage divider (just use the wires). As for the diode, you just have to check that the power arrives to the HC; if it doesn't, try getting it from another VCC pin (or short circuit the diode as suggested in the instructable). Just note that the author says that you have to connect TX with TX and RX with RX; if your solution doesn't work try swapping them

If both devices are 3,3 volt, there is no need for the 10K/15K voltage divider. The Rx pin on the HC-05 is only receiving 1.98volt as a logical 1 and thet is way to low.


text:
What do I have to change to make this code functional?
I have a joystick, an I2C 16x2 character display, and an Arduino. I want to move the joystick and get an on-screen character (specifically, the letter h) to move in the direction that I pushed the joystick. Here is the Arduino code.
#include <LiquidCrystal_I2C.h>
int xVal;
LiquidCrystal_I2C lcd(0x27, 16, 2);
int yVal;

int blockPos[]= {8, 0};
int blockPosBack[]= {8, 0};

int ycal;
int xcal;
void setup() {

    lcd.begin();
    lcd.clear();
    lcd.backlight();
Serial.begin(9600);

pinMode(A0, INPUT);

pinMode(A2, INPUT);
lcd.setCursor(blockPos[0], blockPos[1]);
//lcd.print("h");

ycal = 500;
xcal = 514;
}

void loop() {

xVal = analogRead(A0);

yVal = analogRead(A2);

Serial.print(" Y is...");

Serial.print(yVal);

Serial.print(" X is...");

Serial.println(xVal);

blockPosBack[0] = blockPos[0];
blockPosBack[1] = blockPos[1];

if(xVal < (xcal - 150)){
  if(blockPos[0] > 0){
    blockPos[0] - 1;
    }
  }

  if(xVal > (xcal + 150)){
  if(blockPos[0] < 15){
    blockPos[0] + 1;
    }
  }

  if(yVal < (ycal - 150)){
  if(blockPos[1] > 0){
    blockPos[1] -1;
    }
  }

  if(yVal > (ycal + 150)){
  if(blockPos[1] < 1){
    blockPos[0] +1;
    }
  }
if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
  lcd.clear();}
  lcd.setCursor(blockPos[0], blockPos[1]);
  lcd.print("h");
}

The problem is, I get a message saying that "expected ')' before '!' token". How do I solve this, and how do I change the code to make it functional?
Edit: I learnt that '!' is not the same as 'not equal to', which is '!='. I tried this, but now the h just sits at the initial position but doesn't move when I move the joystick. What do I have to change in the code to make it work?

if(blockPos[1] < 1){blockPos[0] +1;} - shouldn't that be blockPos[1] +1 ?

Please describe with your own words what you want to achieve with the line if(((blockPosBack[0]) ! (blockPos[0])) && ((blockPosBack[1]) ! (blockPos[1])){

@MrGerber Without it, the Arduino keeps clearing the display, which results in the flickering of the character displayed on screen.

That is ugly code. If there is any possibility at all for misinterpretation you should write stuff out using multiple lines. And comment everything.

Let me rephrase- Describe with normal language what conditions you want to catch with this if-statement.

@MrGerber the 'lcd.clear()'

@DirkBruere I'm the kind of guy who gets code for one part of the project off the internet (in this instance the code for the joystick), and then frankensteins my own additions onto it. (Then asks on the internet why my code isn't working). I don't really prepare it for other people, because I can understand it fine myself. Writing neater code is one of my goals for coding.

I see that you run the lcd.clear()-function, but under what conditions do you want to run that?

@MrGerber What do you mean by conditions? If I don't clear the LCD when the position on the 'h' changes, instead of the one h moving around on its own, it will leave behind a trail of 'h'.

condition - kənˈdɪʃ(ə)n - [noun] 3. a situation that must exist before something else is possible or permitted. "for a member to borrow money, three conditions have to be met"

@MrGerber Oh, sorry. So I have the blockPosBack (stands for "block position backup") array which becomes the same as the blockPos array at the start of the loop. Then it runs through all the if statements which check if the joystick has been moved at all. After all that, the large if statement at the bottom check to see whether the blockPosBack array is the same as the blockPos array, if it's the same, it means that I have not moved the joystick. And, there is no reason to clear the screen, because the 'h' does not need to be moved.

Yes, then I follow you :) Then what you want is != to check if unequal, but you dont want &&, you want ||, so you clear if the column coordinate OR the row coordinate has changed

@MrGerber Ahhh thanks for that!, Yes it makes sense that way... But the 'h' still doesn't move at all though, it's still stuck in that initial position...

@Bruce Abbott Yes, it should, I changed that.

Like stated in my comment, to have proper condition for clearing the display, the condition you should want to meet are:
if ( (newX != previousX) OR (newY != previousY)) {
    clearLCD()
}
EDIT: Or else, what you're saying is that you're only clearing the display when you have changed both X and Y at the same time
And to adress your problem with the 'h' not moving, you need to change the lines
blockPos[0] - 1; etc
into
blockPos[0] = blockPos[0] -1;
or
blockPos[0]--;
or else, you're not really assigning the new value to the variable containing the position to use in the display.

This worked perfectly! I added a delay of 100 on the four if statements. Thank you so much! :)

!! is not a valid logical operator, you probably meant || for locical OR?
Did you verify that the condition to change the blockpos value is actually fulfilled? Means are you sure one of your if blocks is actually executed?

Sorry, that was supposed to be '!' for NOT. I made the edits. The code still doesn't work.

@skillz21 ! is a unary operator. I think you want != (not equal to).

@Jon Yeah I had a look into that, I changed it, but it still doesn't work.

Could you describe in your own words what you want this line of code to do?

@Humpawumpa I want the 'h' on the display to stop flickering.

Did you verify that the condition to change the blockpos value is actually fulfilled? Means are you sure one of your if blocks is actually executed?

How do I do that? I did 'Serial.print(blockPos[0]);' but no, the values of both blockPos values don't change... why?

First of all you should have edited the code way better, if you want help and want us to understand you must edit it properly.
if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
  lcd.clear();}
  lcd.setCursor(blockPos[0], blockPos[1]);
  lcd.print("h");
}

I took some time to understand that lcd.setCursor and lcd.print wansn't part of the if. When you are using 2 different sensors or components, you must try them separatly first, and when you got them both working fine that's when you use them together.
https://www.arduino.cc/en/Tutorial/JoyStick
This is an example pretty much more simple than yours, so i just think you must try lcd first, and when you understand how lcd works, and how joystick works, you can easly interact them.

If you wondered about how those five last lines worked, it was not harder than asking OP, or in fact - reading the comments section, it was explained there an hour before your answer was posted. Also, referring to another example code is not really answering the question.

just saying it was a bad edit, it wasnt critical in this code because it was short, but in real big codes this edit is critical. And im refering to another example because it was way simple, you didn't understand my aswer, i "advised" for future codes

Yeah I did, but you didn't understand my comment. Imo, advise for the future is not an answer to a question, but belongs in a comment, or as an addendum to a proper answer to the OPs question. Remember that these questions should be useful to anyone else reading the Q/A as well.


text:
Elegant solution for refreshing TFT display content?
I'm currently drawing black boxes over old content before displaying constantly refreshing content on my display, so for instance to display temperature:
if (sensorTemp != nowTemp){
    nowTemp = sensorTemp;
    tft.fillRect(0,52,88,21,ILI9341_BLACK);
    return nowTemp;
}

If I don't do this the display will just overlay content until it becomes a white blob.
However, this solution leaves me with a black flickering on the display and I can't control exactly what is refreshed where. So for instance when I want to display the current time or date it has to refresh the date all the time, even though nothing changed.
void loop() {
  tft.setTextSize(2);
  tft.setCursor(0,0);
  tft.print(rtc.getDateStr());
  tft.fillRect(144,0,199,15,ILI9341_BLACK); //Black box drawn over 'old' time data
  tft.setCursor(144,0);
  tft.print(rtc.getTimeStr());  //Draw new time
  tft.setCursor(0,52);
  tft.print(tempCall());  //call function to check on temperature and draw new data if necessary
}

Is there a more elegant solution to this problem?

What library are you using? You either want to render your string in an off-screen buffer (which takes lots of memory and library functions that support that kind of thing) or somehow make the characters print the background as well as the foreground colour - and that depends on what library you are using.  The Uno is poorly equipped for working with TFT screens due to lack of memory. It certainly wouldn't be my first choice (it wouldn't even make it on my list at all...)

@Majenko I'm using a Mega with the Adafruit GFX library for ILI9341 tft screens. I am not aware of any other libraries that work with SPI screens, but I haven't done any extensive googling on that yet.

Ah, good. That library is the one I originally based DisplayCore (chipKIT display library suite). It can be done.  I'll explain how...

@Majenko ah! I remember you! You're the guy who told me about SPI like a month ago :)

The Adafruit GFX library has two functions for setting the text colour:
setTextColor(uint16_t c)
setTextColor(uint16_t c, uint16_t bg)

The first sets both the foreground and background to the same colour, and the second to two different colours.  You may ask why you would want the foreground and background to be the same - well, the library handles that situation as a special case: it makes the background transparent.
By setting the foreground and background to different colours you force the library to draw that background colour in over whatever is already on the screen.
tft.setTextColor(ILI93481_WHITE, ILI9341_BLACK);

With that any background pixels in the text string will be coloured black and the text itself white.  As long as the string you are printing is the same length as the text that is already there it will be replaced completely.

Thanks again for your help, this made my whole code a lot easier and displaying data much more elegant.

Should be noted that this only works with the built-in GLCD font. Custom fonts can't be re-drawn in this manner.

If you look in the "Adafruit_GFX.cpp" you will see the following.
void Adafruit_GFX::setTextColor(uint16_t c) {
 // For 'transparent' background, we'll set the bg
 // to the same as fg instead of using a flag
 textcolor = textbgcolor = c;
}

void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
 textcolor   = c;
 textbgcolor = b;
}

If you only want to Draw the Character with a transparent background meaning you only write the character setTextColor in the prescribed pixels changing none of the surrounding pixels in the character block defined by x, y, setTextSize.
TFT.setTextColor(GREEN); //With Transparent Text Background not updating surrounding pixels.

If you want to Draw the Character with your background color, replace app pixels in the character block defined by x, y, setTextSize with your chosen text color and your background to be the same as your chosen background. This will overwrite all pixels with old character that are no longer used with the background color all at the same time preventing mess of pixels, and character flashing.
TFT.setTextColor(GREEN, BLACK); //With Text Background Color updating surrounding pixels.

This code works well and accounts for values of different length.
void textValue() {
  float newValue = @your input@;
  int numChars = String(newValue).length(); // Get the number of characters
  int valueWidth = numChars * 6 * 2.5;

  if (valueWidth != previousValue) {
    tft.fillRect(0, 55, previousValue, 30, ST77XX_BLACK);
    previousValue = valueWidth;
  }
  tft.setCursor(3,60);
  tft.setTextColor(ST77XX_WHITE, ST77XX_BLACK);
  tft.setTextSize(2.5);
  tft.print(newValue);
}

Hmm the solution is how the code is written...no fancy stuff...the KIWI way
//in setup function add tft.fillScreen(ST7735_GREEN);

void loop(){

  int lightIntensity = myBH1750.getLux();
  tft.setTextSize(3);
  tft.setCursor(10,10);
  tft.setTextColor(ST7735_RED);
  tft.print(lightIntensity);
  delay(3000);
  tft.setTextColor(ST7735_GREEN);
  tft.setCursor(10,10);
  tft.print(lightIntensity);
  tft.setCursor(10,50);
  tft.setTextColor(ST7735_BLUE);
  tft.print("LUX");
}


text:
Lag in fetching serial data from Arduino
I am working on a project based on Arduino and python3.6,two HC-SR04 sense the distance of palms and process the data using Arduino and send it through serial port to python3.6 ,python3.6 with the help of pyserial ,pyautogui based on data from arduino controls a game named supertuxcart,a racing game,basically the thought behind this is  controlling game with palms instead of keyboard or mouse .But the problem am facing is Arduino takes the distance measurement data from two HC-SR04(one for each hand) ultrasonic sensors, processes according and sends processed data through serial port to python3.6 ,there while running the my python script i open the game to check if its working ,it works, but there is lag in data received from arduino thus turn the game messy.
here is arduino code am using with NewPing library
#include <NewPing.h>
int trig1=9;
int echo1=6;
int trig2=7;
int echo2=5;
int R;
int L;
NewPing right(9,6,100);
NewPing left(7,5,100);
void setup() {

  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(6,INPUT);
  pinMode(5,INPUT);

}

void loop() {
  Serial.begin(9600);
  //Serial.println("hi,am arduino");
  R=right.ping_cm();
  L=left.ping_cm();
  //Serial.println(R);
  //Serial.println(L);
  delay(0000);
 if (R==0 && L==0){
    Serial.println('0');
  }
  else if(R<L&&L-R>5){
    Serial.println('1');
  }
  else if(R>L&&R-L>5){
    Serial.println('2');

delay(3000);

  }

}

Here is python3.6 code am using
import serial
import pyautogui
import time

Arduino = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(0)
print(Arduino.readline())
pyautogui.keyDown('up')
while 1:
    Data = Arduino.readline()
    print(Arduino.readline())

    if Data == b'0\r\n':
        pyautogui.keyUp('up')
        pyautogui.keyUp('right')
        pyautogui.keyUp('left')
        break
    elif Data == b'1\r\n':
        pyautogui.keyUp('left')
        pyautogui.keyDown('right')
    elif Data == b'2\r\n':
        pyautogui.keyUp('right')
        pyautogui.keyDown('left')

You could try using a higher baudrate, instead of just 9600.

Possible explanation for the lag. Since serial data is being buffered; if you send data faster, than the serial connection can handle, you'd get lag. As the latest data has to wait in line to be send. Using a tiny delay, or better Serial.flush(), or Majenko's #3 suggestion would eliminate the lag caused by buffering.

NewPing right(9,6,100);
NewPing left(7,5,100); Is the 100 the timeout for no return? Can you make that shorter?

its maximum distance ,100cm

Don't edit the question and invalidate an existing answer.

A couple of things jump out at me:

You only need to run Serial.begin(9600) once in setup() - never in loop() like that.
Your delay(3000) will be causing a 3 second delay when R>L&&R-L>5.
You don't need to constantly send the data over and over again. You just need to send it once and once only when the state changes.

At the moment you're sending something like:
0000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000000000000000002222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222200000000000000000000000000000000000000000000000000000000000000

when all you really need to do is send 01020. Remember what the state is and only send anything when that state changes from one iteration to the next. And never ever use delay().

The code is using Serial.println, so it's more like 0\r\n0\r\n1\r\n1\r\n. So three bytes, for every byte of actual data.

Yeah, but still it's overkill.  And I didn't want to make my post 6 miles long to illustrate a point...


text:
Point-to-point Communication of Arduinos with RFM LoRa Shield
In this tutorial, it sends a string from a node to the other node. But if I want to send an integer instead of a string, how should I change the code?
Serial.println("Sending to rf95_server");
// Send a message to rf95_server

String radiopacket = "Hello World #";
radiopacket += String(packetnum++);
radiopacket += " from ";
radiopacket += node_id;

Serial.print("Sending "); Serial.println(radiopacket); delay(10);
rf95.send((uint8_t*)radiopacket.c_str(), radiopacket.length()+1);

Serial.println("Waiting for packet to complete..."); delay(10);
rf95.waitPacketSent();

You can either convert it to text (sprintf) or send it as bytes. However you like. How do you want to send it?

i want to send the data generated from the ultrasonic sensor, how can i send the data as byte? sorry i'm new in programming

I can tell...  Data is just data - whether it's a string or a number. It's just data.  An int is just two bytes. You can send it by casting it as bytes (as you already do with the existing code) with a size of 2 bytes. Just remember to cast it using the address of the integer, not the value of the integer.

The simplest way is to just cast the integer into an array of 2 bytes and send that.  Assuming int temperature:
rf95.send((uint8_t *)&temperature, 2);

To make it more portable you can use the size of an integer instead of 2:
rf95.send((uint8_t *)&temperature, sizeof(int));

Reading back, you just cast the buffer you have received as an integer, or combine the data manually (which may be safer since the buffer may be misaligned on a more powerful system than an 8 bit Arduino):
int temperature = buf[0] | (buf[1] << 8);

(Assuming it was sent from a little-endian 8-bit system).
If you want to send the number as plain text, so it can be easily read by a human, you want to print it to a string:
char temp[6];
sprintf(temp, "%d", temperature);
rf95.send((uint8_t *)temp, strlen(temp));

thanks for the help, but i received weird symbol on the server side
. do i need to change anything on the server side so that i can get a proper integer?

Yes. I told you what to change.

Note that the binary methods are only "portable" when the machines on both ends use the same variable size and byte order, as may indeed be the case here.  Otherwise the packing and unpacking will need to be done explicitly, something specified in many network protocols for example.  This would work between two ATmega Arduinos, or two Due Arduinos, but not between a mixed collection without explicit handling.

Just cast the integer to a String before sending and convert the String back to an int when you received. May not be memory friendly considering you are using Strings, but its very easy.
int a = 10;
String s = String(a);

You can then send the String as you would a normal string. Then on the receiving end you cast back to an int.
Assuming you received a String s.
int b = s.toInt();

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


text:
ESP8266/NodeMCU unable to communicate with MFRC522 RFID reader
I am trying to use the 'DumpInfo.ino' example file to dump an rfid tag, the only changes i have made to the example is changing the pin settings.
#define RST_PIN         3          // Configurable, see typical pin layout above
#define SS_PIN          4         // Configurable, see typical pin layout above

i have wired it based on this guide (tried using the pins shown on here as well) when i run the code i get this error from mfrc522.PCD_DumpVersionToSerial();
WARNING: Communication failure, is the MFRC522 properly connected?

Ive also tried printing the version and i get 0xFF which along with 0x00 seems to mean it isnt connected.
The only light that is on during the test is D1 on the RFID reader which you can see in the first wiring pic.
Pictures of wiring here
Edit: I've changed the pins to D3 and D4 but i still get the same error

change the pins to Dx constants, to match your connections
#define RST_PIN         D3
#define SS_PIN          D4

because pin D3 is not io 3 and pin D4 is not io 4. see pins_arduino.h

Thanks, i didnt realise that, unfortunately it still doesnt work.

ok i got it working with this pinlayout:
D1 (GPIO 5)-- RC522 - RST
D2 (GPIO 4)-- RC522 - SDA/SS
D3 (GPIO 0)
D5 (GPIO 14)-- RC522 - SCK
D6 (GPIO 12)-- RC522 - MISO
D7 (GPIO 13)-- RC522 - MOSI
D8 (GPIO 15)
also i used this tutorials code and i posted a serial.println after each piece of code to see where it is/or fails:
http://www.instructables.com/id/MFRC522-RFID-Reader-Interfaced-With-NodeMCU/


text:
IO with port manipulation while not interfering with i2c
I'm using an Attiny84 with the Tiny Core.
I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.
How can I write only to the lower 4 bits to avoid interfering with the i2c?

Have you tried doing it, and it has not worked?

I don't think you need to worry. A simple piece of code:
void setup()
{
 PORTA |= bit (0);
}

void loop() { }

Generates:
00000044 <setup>:
  44:   d8 9a           sbi 0x1b, 0 ; 27
  46:   08 95           ret

In other words, the compiler generates code to set that bit, ignoring all the other bits.

Presumably PORTA |= bit (0000); would set the 4 least significant bits?

Not at all. Zero is zero, no matter how many leading zeroes you put there. You could do this:  PORTA |= 0b00001111;

The bit macro sets a bit by shifting the number 1 left the number of bits in the argument, so bit (0) is 1 << 0 which is the same as 1.

OK, so I understand now that I can set the bits to 1 without touching the i2c pins. Is it the same, but I suppose with the OR operator to set back to 0?

No, you use the AND operator. PORTA &= ~0b00001111; The ~ operator takes the ones-complement, and you AND that into the port. Alternatively: PORTA &= 0b11110000;


text:
Getting 3.3v on 5v pin in Arduino Uno
When interfacing my Arduino Uno with a relay I was facing reliability issues, and while investigating it with a multimeter, I found something strange.
I noticed that in the 5V power pin (with which I was powering my circuit) is producing only 3.3V when using the power adapter. However, when connected via the USB-A port, the 5V pin was producing the expected 5V voltage.
I tried powering it in many ways - computer-to-USB-A, computer-to-barrel-jack, phone-charger-to-USB-A, phone-charger-to-barrel-jack and an external 5V DC power supply. In all cases, the above observation held true - powering the board through the barrel jack made the 5V power pins produce only 3.3V.
Question: Why is this happening? Does that mean my board is faulty? Is there any way to fix this?

What voltage are you putting into the barrel jack? Is it 5V?

Yes, I'm using a 5V barrel jack power input - in one trial from a phone charger, and in another trial from a computer's USB output. I measured it with a multimeter and checked that it is indeed 5V.

and an external 5V DC power supply

OK, assuming you are putting 5V into the barrel jack this is exactly what you expect to happen.
From the Arduino Uno specifications you are supposed to supply a recommended 7V to 12V. Your supply of 5V is too low.
The barrel jack first goes through a M7 protection diode which would have about a 0.7V forward voltage drop, and then through a NCP1117ST50T3G voltage regulator which has a dropout voltage of (typically) 0.95V at 100 mA.
Thus you have:
5V input - 0.7V - 0.95V = 3.35V

That is what you are finding.

Solutions

If you have a proper, regulated, 5V DC supply you can put that directly onto the 5V pin of the Arduino. Better get the wires around the right way because you are bypassing the protection diode!
Get a DC supply in the range 7V to 12V and put that into the barrel jack.
Another simple idea is to just get a wall-wart that is used for charging phones via USB and run a USB cable into the Arduino USB port.

Empirical test
I put 5V into the barrel jack of my Uno and read 3.33V on the 5V pin, which is pretty-much what you got. I measured a 0.77V drop over the M7 diode.

Thanks for explaining this. Indeed my barrel jack input is 5V, and I forgot that the input needs to be 7V to 12V. I'll change the barrel jack input to a 7V input. But I'd like to learn more... could you please talk more about how I can built a "properly regulated 5V DC power supply" from 4 AA batteries? Some starting links would help - I'll dig into it more.

Tempted as I am to amend my answer to respond to this, I think this is a whole new (and quite interesting) question. If you would be kind enough to make a new question out of it then I'm sure you'll get some interesting responses. Possibly one of them would be that this is purely an electronics question, and not an Arduino one, but we can only hope that people don't do that. :)

For example, make a question along the lines of: how I can built a properly regulated 5V DC power supply for my Arduino Uno from batteries? Answers might then discuss one battery, two batteries, four batteries, a 12V car battery, a LiPo batttery, etc.

While Nick's answer is 100% (technically) correct.
Functionally, it's a much easier story (given you feed 5V into the barrel jack).
Check the Arduino's product page.
Microcontroller ATmega328P
Operating Voltage   5V
Input Voltage (recommended) 7-12V

So yes, while the Arduino runs on 5V (and does so over USB). The recommended input voltage is 7-12V. You're simply not supplying a high enough voltage.
The difference, as per Nick's answer, is the protection circuit and regulator snooping off a few volts (which is bypassed when using USB).


text:
Send Bluetooth Data to Android App (HC 05)
I'm struggling to send data strictly from my arduino UNO to an android app using bluetooth module HC 05. I am able to send/receive using 1) the serial monitor in arduino IDE and 2) Bluetooth Chat android app (a sample project in Android Studio). But when I use software serial using pins 3,2 instead of TX/RX on my UNO, the Bluetooth Chat app cannot connect to my HC 05. I think I'm missing something important.
My end goal is not to send messages like a chat. It will be a very simple flag-based system where, for example, an event occurs on my arduino which causes it to transmit character 'h' through bluetooth, which is then received by my android app. In android receive: if 'h' is read by bluetooth, doSomething(). I don't need to send anything from my android app to the arduino right now, but that would be nice to know.
I just thought I could test my bluetooth functionality with this Bluetooth Chat sample app. Now, that seems like a poor place to start.
Any suggestions are appreciated.

what do you mean by strictly? it has no meaning in the sentence that you used. ... you could have used the word joyfully and it would be just as meaningless. ... i am not trying to be snarky, i am just questioning the meaning of the word

one thing you need to do when developing hardware and developing code, you need to clearly identify the problem. ... your problem is cannot connect to my HC 05 when I use software serial using pins 3,2 ... your question should be about that, everything else that you mentioned is just a distraction from the real problem

@jsotola The serial monitor on my PC receives android messages fine. As far as I know about this, and I don't know much since I just began this android/arduino communication endeavor, the issue seems to be strictly transmission from arduino to android. Obviously the issue could be android reception. Sorry I'm spotty on the description of my issue. I'm experienced with serial communication but new to bluetooth. I suppose I could use some advice on where to start.

Another thing. People seem to be using a software serial abstraction to accomplish what I'm trying to do. But I don't understand why one would use a software serial and not tx/rx 0 and 1.


text:
Adadfruit Trinket software not running on ATtiny85
I have an application that uses a pair of nRF24L01+ as a simple RF link between a camera PC sync output and a set of LED flashes. The important factors are power and low latency - hence the 2.4GHz.
I developed both ends using UNOs and then moved to Trinket 3 V. The system works very well with Trinkets.
My next step was to strip this down further to ATtiny85 at least at the receiver end.
I overcame the programming challenges and a day's worth of board installation in Arduino IDE and can not now program the ATtiny85 as well as the Trinket.
I will share the code lower down, but let me explain the difference in result.
With the Trinket the trigger output from the receiver is a simple pulse the width of the transmitted pulse (as is the goal.
               __________________________________
 _____________|                                  |__________________________
The pulse is anywhere from 5 ms to 50 ms.
On the ATtiny85 the link is clearly operational from transmitter to receiver but the output is ugly. Something like this:
                 _____      _____            _____
________________|     |____|     |__________|     |___________
The pulses appear (not always the same number) for the duration of the transmitted pulse and the interval is variable. The pulses themselves are of 8 MHz duration.
The code:
#include "RF24.h"

// Note: these includes looked necessary when I started but during debugging I
// removed them with not change in functionality - strange!
//#include <Mirf85.h>
//#include <MirfHardwareSpiDriver85.h>
//#include <MirfSpiDriver85.h>
//#include <nRF24L0185.h>
//#include <SPI85.h>

/*    **ATtiny25/45/85 Pin map with CE_PIN 3 and CSN_PIN 4**
      nRF24L01 CE oins is tied high and pin3 is used as the trigger output.

                                   +-\/-+
                     NC      PB5  1|o   |8  Vcc --- nRF24L01  VCC, pin2 --- LED --- 5V
      nRF24L01  CE, pin3 --- PB3  2|    |7  PB2 --- nRF24L01  SCK, pin5
      nRF24L01 CSN, pin4 --- PB4  3|    |6  PB1 --- nRF24L01 MOSI, pin6
      nRF24L01 GND, pin1 --- GND  4|    |5  PB0 --- nRF24L01 MISO, pin7
                                   +----+
*/
*    **Trinket 3V Pin map with CE_PIN 3 and CSN_PIN 4 **
* @code
*                                 + -\ / - +
*                   NC      PB5  1 | o   | 8  Vcc -- - nRF24L01  VCC, pin2 -- - LED -- - 5V
*    nRF24L01  CE, pin3 -- - PB3  2 |    | 7  PB2 -- - nRF24L01  SCK, pin5
*    nRF24L01 CSN, pin4 -- - PB4  3 |    | 6  PB1 -- - nRF24L01 MOSI, pin6
*    nRF24L01 GND, pin1 -- - GND  4 |    | 5  PB0 -- - nRF24L01 MISO, pin7
*                                 +---- +

// (Create an instance of a radio, specifying the CE and CS pins. )
RF24 myRadio (3, 4); // "myRadio" is the identifier you will use in following methods
/*-----( Declare Variables )-----*/
byte addresses[][6] = {"1Node"}; // Create address for 1 pipe.
int dataReceived;  // Data that will be received from the transmitter
int flashPin = 3;
int flashValue = 0;
long flashStartMicros = micros();

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

  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MIN);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power

  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();

  digitalWrite(flashPin, 0);
}//--(end setup )---

void loop()
{
  if ( myRadio.available()) // Check for incoming data from transmitter
  {
    flashStartMicros = micros();
    while (myRadio.available())  // While there is data ready
    {
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload (You must have defined that already!)
    }
    if (dataReceived == 8) {
      flashValue = 1;
      digitalWrite(flashPin, flashValue);
    }
  }
  if ( micros() - flashStartMicros > 1500) {
    flashValue = 0;
    digitalWrite(flashPin, flashValue);
  } //END Radio available
}//--(end main loop )---

Simply - I send a character, received it and set trigger high. Then time out and set it low. There is only one statement setting pin 3 (flashPin) low.
I have spent 2 days trying to find the difference.

The flash pin is the same as the CE pin?

CE pin is tied high to Vcc and Flash in is set to output. This works on the Trinket.

change the last digitalWrite(flashPin, flashValue); to digitalWrite(flashPin, 1); .... that will tell you if the output is going low because of that line

I changed the line as you suggested and the LED comes on (the pin goes high) and stays on. I put a delay at the end of the setup() to see when it gets set high and it waited low for the delay then went high. It does not react to the pulse of course. Fair suggestion though.

since you posted a waveform, I assume that you have a scope of some kind. .... check all the other pins of the nRF24L01+ .... see if there is a difference between the Trinket and the ATtiny85 ..... could it be the power supply voltage? ... or maybe something to do with the CE pin

I have and I should do that. Thanks for the suggestions. I'll get to that in the morning.

My debugging effort was in an endless DO loop because I was trying to see why the ATtiny was not acting on the received data like the Trinket. Thanks to some simple questions from #jsotola I looked at what the Trinket signals looked like to compare.
Turns out, my transmitted was broken and that both receivers were dealing with the same garbage. Now I do not have a difference between the 2 receivers and I can go back and make the TX do what I need it to do.
“When you eliminate the impossible, whatever remains, however improbable, must be the truth.”


text:
powering arduino with a voltage divider to increase lifespan
I have a chinese arduino nano that I'm planning to use to open a door using a numeric keypad.
My power source is 12V and I want it running 24/7. I have read that the first thing to fail on an arduino is the voltage regulator due to the heat of lowering the voltage to something the arduino can use.
I have think of buying two big resistors of around 1W each to build a voltage divider and only feed 7V to the Vin pin of the arduino, so it will increase its lifespan.
Is this a good idea?

It's basically another load to the battery. Some low power DC-DC voltage regulator (12V -> 5V) will be much better.

that is a very good idea ... doing experiments with the Arduino is the best way to learn

READ THIS: https://hackingmajenkoblog.wordpress.com/2016/08/30/why-you-cant-use-resistors-as-a-voltage-regulator/

How much current do you expect to use? If you know that you can calculate how much power is converted to heat. If your circuit is only using a few tens of milliamperes, the voltage regulator will only need to dissipate a few tenths of a watt of heat.

Thanks for the comments guys, things are clearer now. I will buy a regulator and use it.
Gerben: it will only use around 50mA, but I wanted to build it very durable so thats why I though on the big resistors.

@Majenko Nice off-site explanation! You could make it an answer! (Copy/paste, upload images).

Or I could hunt down one of the many duplicates and close it ;)

Terminating voltage by dropping it over large power resistors is a bad idea, efficiency wise. There are better options.
Switch-mode Buck (=step down) converters are usually far more efficient than linear regulators. A linear regulator dumps the excess voltage in a resistor which converts the energy mainly into heat. A switch-mode converter works by switching on/off an inductance at the right time, which is far more efficient.
For step-up/step-down DC-DC converter theory look here, here and here. For a comparison for switch-mode against linear regulators look here.
A step-down converter module like the ones with a LM2596 should be good enough for you. See here on ebay.


text:
Zero-ing Compass | Following Magnet Strip Robot
So my problem is purely programming, I understand the problem but can't figure out what to do, Is there a library? should I create my own code for Zero-ing my compass so I don't have value from earth field in my equasion?
I have a small robot that I want it to follow a refrigerator magnet strip that is incrustated in floor
The compass on its own works well but I want to be able to drive my robots by a positive or negative value that I would receive from a library/function I coded off values from library of compass
The actual problem is that earth magnetic field will offset my value
Lets say north is on the left and magenet is also on the left. I should receive for example -1000 Gauss
but then if I put the magnet to the right but keep the same oriantationg of the magnet I will receive -500 when I really wanted 500 for example.
Now id like to take a measurement of earth magnetic field first and from there subtract current value off the actual values i get.
But my understanding of vector is very limited.
Doing this for a compass that its oriantation don't change would be pretty simple but, in my case compass will be mounted on robot itself therefore orientation will change all the time
Im not looking for some code but more a general idea on how to do this, either by using a library or some maths idea on how to acheive that.

As you've noted, the fact that your platform rotates means that you can't directly do this.  First consider if the earth's field really makes enough difference when you are close to the strip.  If it does, you might need to add orientation tracking via wheel encoders and/or a gyroscope (tricky but getting surprisingly good in drones). Or perhaps you should look at using two sensors displaced left and right, or one near the ground and one raised in the air to detect the earth reference field with less influence from the strip.

Thanks @Chirs i could put one in the midle and the substract from this.  But i really feel like its posible to get a reading with nothing except earth mag field and use it as a calibration to substract and get only the actual magets around the sensor on each axis on all axis.  I just dont know where to start for this

It might be easier to use hall effect sensors instead of a compass. Use them like optical sensors for a normal line following robot.

@Majenko Yep I would do that, but i want to utilize the north and south pole of the magenet, so i can count where the robot is at in its trajectory.

@NicolasRacine analog hall sensors detect the polarity of the field not just the strength

i don't know if this would work, but you could try to orient the compass along one of the other axes. ... or use a separate compass along each axis

@jsotola What do you mean?  Can you elaborate ?

i used the compass app on my phone to detect the magnetic seal on my fridge .... i got a different response when i turned the phone sideways ... i was talking about the xyz axes in 3d space in my comment


text:
Burning the Bootloader on Adafruit Feather 32u4
So, the default bootloader in Arduino is oddly set to erase EEPROM with every reboot, rendering the EEPROM, well, useless.
I found where the fuses are set in the boards.txt file, but getting this configuration change into the chip requires burning an updated booloader.
In the Arduino IDE, there is an option to "Burn Bootloader", but that would be way too easy, and of course, doesn't seem to work.
I can't find any clue on the Internet about how to actually get the bootloader updated in these devices.
So, is it possible to reprogram the bootloader on the Adafruit Feather 32u4 devices?
If so, what's the trick to do it?

Are you sure it erases on every boot and not on every re-flash?

Yes, it seems to be every boot, however I am looking to survive re-flash, so I needed to set the EESAVE bit correctly to make this work.

Update:  it looks like i had a bug in my code that was making me think EEPROM data wasn't being saved, so I ended up not needing to burn the bootloader after all.  Woot.

"Burn Bootloader" only works if you have a programmer connected to the device. The onboard bootloader in your Feather cannot change the fuses, even though the process may indicate it has done so.
You would have to connect an ICSP (In-Circuit Serial Programmer) to the correct pins (MOSI, MISO, SCK, RESET, VCC, GND). You can use another Arduino as a programmer by uploading a specific sketch to the Arduino to make it an Arduino as ISP.
The normal bootloader on an Arduino emulates this kind of device to allow programming by serial/USB port, but it has limitations. The ICSP process is the native way to get a program onto the AVR chip, and is the only way to set fuses.
EDIT:
This AVR USB Bootloader Datasheet states on page 3:

• Boot Reset Fuse The Boot Reset Fuse (BOOTRST) can be programmed so
  that the Reset Vector points to the Boot Flash section start address
  after reset. Once the user code is loaded, a bootloader command
  (“start application”) can start executing the application code. Note
  that the fuses cannot be changed by the MCU itself. This means that
  once the Boot Reset Fuse is programmed, the Reset Vector will always
  point to the Bootloader Reset and the fuse can only be changed through
  the serial or parallel programming interface. The BOOTRST fuse is not
  active in the default factory configuration.

That document also references AVR282: “USB Firmware Upgrade for AT90USB” (Note, I could not find this on the Atmel website.) This document details the FLIP program, at Atmel tool for uploading firmware over the USB DFU interface and setting configuration settings, etc.
This doc has a FAQ section which states:

Can I modify the fuse bits using Flip? • No, Flip cannot modify the fuse bits. To modify the fuse bit you can use either the JTAG ICE
  MKII, the AVRISP MKII, or parallel programming

So, while this may not be a definitive answer, it appears at this time that "burning fuses" cannot be done over USB on the 32u4. If that's not the case, I'm sure the site would welcome the new info.

Note that the question is about a 32u4, not a traditional Arduino, so I believe there are some hardware-assisted DFU options in addition to ISP.

Not long after I asked this question, I had a "duh" moment and and realized I had a JTAGICE3 in my drawer.  Once I got the pinout right, and overcame a problem with macOS grabbing the device, I was able to cobble a way to get the bootloader to work.  I'll post a complete answer here later today so everyone gets the benefit.

In my case the 32u4 (Lora32u4II) failed after uploading big firmware. Not responsive.
Fortunately I have the buspirate 4 with firmware 7.0. And during this time I discovered that the BusPirate is not able to power the board to reflash the firmware. But if I connect the board over USB and then the cabling as described:
BUS PIRATE - LORA32U4II
MISO              MISO
MOSI               MOSI
CLK                SCK
GND                GND
CS                 RST

And I use arduino ide to upload a new bootloader it starts to work again. So. I wonder why the firmware update locked the board while there's enough space. And why powering over 5v doesn't get it to work on buspirate + arduino ide.
I leave info for others that have same problem.
I discovered that using this method, even if slower, I can skip bootloader, leaving more room for my firmware...


text:
Weird multiplication result
Here's come Arduino code.
#define M(x, y) x * y;
void setup() {
  Serial.begin(9600);
  Serial.println(M(3 + 2, 4 + 2));
}
void loop() {
}

Why is the result 13?

Because M(3 + 2, 4 + 2) gets replaced to 3 + 2 * 4 + 2 and then the normal priority of operations does the multiply before the addition.
This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.
If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.
#define M(x, y) ((x) * (y))

Always also surround the whole macro in parenthesis; otherwise you can have the same problem in the other direction: If you do #define A(x, y) (x) + (y), then A(1, 2) * 3 will expand to (1) + (2) * 3 = 7, instead of ((1) + (2)) * 3 = 9, like one would expect.

And trailing semicolon here will also make problems.


text:
LMT84 temperature sensor measurement error
I want to measure atmospheric temperature with an Arduino. The sensor I am using is an LMT84.
After uploading the following code to the Arduino board I am getting very high temperatures in the serial window.
I am unable to understand what the error in my code is. I've connected a 0.1 μF cap between Vcc and ground, and the data pin is connected to A1 on the Arduino.
Please check the following code:
const int sensor = A1; // assigning analog pin A1 to variable 'sensor'
float tempc;  // variable to store temperature in degree Celsius
float vout;   // temporary variable to hold sensor reading
float vout1;  // temporary variable to hold sensor reading

void setup()
{
  Serial.begin(9600);
  pinMode(sensor, INPUT); // configuring pin A1 as input
}

void loop()
{
  vout = analogRead(sensor);
  vout1 = (vout * 500) / 1023;
  tempc = vout1; // storing value in degrees Celsius
  Serial.print("LMT84 temp=");
  Serial.print(tempc);
  Serial.println();

  delay(1000);
}

The serial window shows these values:
LMT84 temp=168.13
LMT84 temp=168.13
LMT84 temp=168.64
LMT84 temp=168.89
LMT84 temp=168.13

The Arduino uses an analog voltage as reference. It is default set to the Vcc of the microcontroller, which is about 5 V for an Arduino Uno. The function analogReference can be used to set something else as reference.
When that reference is not precisely 5.0 V, it is impossible to measure a voltage in a accurate way. It is almost never precisely 5.0 V. When using the USB connector to power the Arduino board, it might be somewhere between 4.5 and 5.0 V.
The Arduino Uno has an internal voltage reference of 1.1 V. That is better than using the default 5 V. The actual voltage can be 1.0 to 1.2 V, you have to put the actual value in your sketch.
The LMT84 has an output of 1034 mV at 0°C and 476 mV at 100°C. That means your calculation is not correct. In the datasheet are two ways to calculate the temperature, an accurate formula and a simple calculation.
You can avoid all these problems with a temperature sensor that has a digital interface to the Arduino board. For example the DS18B20. That is a cheap and accurate temperature sensor.


text:
State machine doesn't function
My goal is to make a logic controller for a cassette tape mechanism, right now I'm simply trying to get the mechanism to engage and disengage the pinchroller arm which is motorized, spin the reels/capstan to advance the tape for playback; and stop the process by stopping the capstan motor, and retracting the pinchroller arm.
Currently this code doesn't respond to any of the button inputs, and I'm unsure as to why that is. I have another program that allows manual control of the motors, and that works fine, this however does not.
Can someone point out/correct what is the mistake? Because I can't seem to find what is wrong. Thank you in advance!
Here is my current full code:
const int motor1Pin = 5; //If motor1 is HIGH and motor2 is LOW,  the motor will spin one way, if motor1 is LOW and motor2 HIGH then the motor will spin in the opposite direction.
const int motor2Pin = 4;
const int motor3Pin = 2;
const int motor4Pin = 1;
const int enablePin = 6; //turns pinch roller arm motor on or off
const int enablePin2 = 3; //turns capstan motor on or off
const int limitswitch1Pin = 7; // end of top travel limit switch
const int limitswitch2Pin = 9; // end of bottom travel limit switch
const int cyclePin = 8; //switch that cycles the pinch roller arm depending on limit switches
const int reversePin = 10;
const int forwardPin = 11;
const int stopPin = 12;

int state;
int buttonState;
int limit1State;
int lastlimit1State;
int limit2State;
int lastlimit2State;
int reverseState;
int forwardState;
int stopState;

enum State_enum {STOP,PLAY};

bool enableState = false;
bool enable2State = false;

void setup() {

  pinMode(motor1Pin, OUTPUT);
  pinMode(motor2Pin, OUTPUT);
  pinMode(motor3Pin, OUTPUT);
  pinMode(motor4Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);
  pinMode(enablePin2, OUTPUT);
  pinMode(reversePin, INPUT_PULLUP);
  pinMode(forwardPin, INPUT_PULLUP);
  pinMode(stopPin, INPUT_PULLUP);
  pinMode(limitswitch1Pin, INPUT_PULLUP);
  pinMode(limitswitch2Pin, INPUT_PULLUP);
  pinMode(cyclePin, INPUT_PULLUP);
  pinMode(A0, INPUT);

  buttonState = digitalRead(cyclePin);
  limit1State = digitalRead(limitswitch1Pin);
  limit2State = digitalRead(limitswitch2Pin);
  reverseState = digitalRead(reversePin);
  forwardState = digitalRead(forwardPin);
  stopState = digitalRead(stopPin);

}

void loop() {

  if (buttonState == LOW) int state = PLAY;
  if (stopState == LOW) int state = STOP;

  switch (state) {
  case PLAY: //Plays the cassette
    if (stopState == LOW) {
      state = STOP;
    }
    if (limit1State == LOW) { //running the pinchroller arm clockwise from the top to bottom

      digitalWrite(motor1Pin, HIGH); // set leg 1 of the pinchroller motor H-bridge high
      digitalWrite(motor2Pin, LOW); // set leg 2 of the pinchrooler motor H-bridge low
      analogWrite(enablePin, 176); //set pinchroller motor speed

    } else if (limit2State == LOW) { //pinchroller arm is fully down (at bottom)
      digitalWrite(enablePin, LOW); //disable pinch roller motor
      digitalWrite(motor3Pin, LOW); // set leg 3 of the capstan motor H-bridge low
      digitalWrite(motor4Pin, HIGH); // set leg 4 of the capstan motor H-bridge high
      analogWrite(enablePin2, 200); // set capstan motor speed
      digitalWrite(enable2State, true);
    }
    break;

  case STOP: //Stops the cassette
    if (enable2State == true && limit2State == LOW) {
      digitalWrite(enablePin2, LOW);
      digitalWrite(enable2State, false);

    } else if (enable2State == false && limit2State == LOW) {
      //running the pinchroller arm counter-clockwise from the bottom to top

      digitalWrite(motor1Pin, LOW); // set leg 1 of the motor H-bridge high
      digitalWrite(motor2Pin, HIGH); // set leg 2 of the motor H-bridge low
      analogWrite(enablePin, 176); //set pincroller motor speed

      if (limit1State == LOW) {
        digitalWrite(enablePin, LOW);
      }
    }
    break;

  }
}

I don't know enough about how tapes work to comment on the sense of what you're doing, but some problems with the code:
You are reading the input and setting buttonstate once only in setup(). You need to read it repeatedly, by putting it in loop().
You also have three variables called state: one global which is never set, and two with very restricted scope which are set but never used - they go out of scope immediately. Remove the ints where you set state in your loop().
This part is useless because you've already done it just above, but probably not hurting anything:
if (stopState == LOW) {
    state = STOP;
}

That's as far as I got. If that doesn't fix it, consider adding trace: you'd have found these two problems pretty quickly if you'd printed out the variables to check your assumptions.

You are reading the input and setting buttonstate once only in setup() - the same applies to all the states.

The OP is testing if  enable2State is true, but nothing in the code changes enable2State.


text:
Unknown USB Device (Device Descriptor Request Failed) - Win 10
I am posting a possible solution here for any online searches happening upon this exact issue.
So I have a third party board (Mega 2560) and I was plagued with my board intermittently working, on some rare occasions it worked but in most cases it just threw me the "USB device not recognized" after plugging it into my pc.
Upon closer inspection I have noticed the following
The one coupling capacitor (Blocks DC but allows AC and signal to pass) was poorly soldered, barely making contact!
So if your pc intermittently connects to your arduino, maybe check what the physical signal path looks like, you might find something like this.

We are getting the same error completely out of the blue. We have an Arduino Uno board. We have tried just about everything from changing out the USB cable, uninstalling ALL programs associated with our machine and reinstalling them. Changed settings, updated our computer, used a different laptop to see if our computer was the issue (no problems there). Thought it was a driver issue to redownloaded and attempted updating... no go... Help!
We as a last resort have ordered a new Arduino Uno... Have we not thought of something to check? Thanks ahead of time!

SMD soldering is not easy but here is the fix. Continuity achieved!

Continuity achieved but... Did this solve the problem? Did you get again some errors or not?

It did solve the problem. Zero errors afterwards, connected every time I plugged it in. It does seem that the capacitor was to blame


text:
NFC PN532 SPI - Error: Timeout when waiting for ACK
I've been struggling to get the PN532 module working over SPI with an Arduino Uno.
I have the wires connected as follows:
SCK   -> 13
MISO  -> 12
MOSI  -> 11
SS    -> 10
VCC   -> 5V
GND   -> GND

And the board mode set for SPI as follows:

When I run the code below I get this output:
-------Peer to Peer HCE--------
write:  02
Time out when waiting for ACK
Didn't find PN53x board

Code:
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"

PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);

void setup() {
    Serial.begin(115200);
    Serial.println("-------Peer to Peer HCE--------");

    nfc.begin();

    uint32_t versiondata = nfc.getFirmwareVersion();
    if (! versiondata) {
      Serial.print("Didn't find PN53x board");
      while (1); // halt
    }

    // Got ok data, print it out!
    Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
    Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
    Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

    // configure board to read RFID tags
    nfc.SAMConfig();
}

void loop()
{
    // Truncated
}

I've been trying to edit the source files and find the problem but I cannot seem to find whats causing it. Some help is much appreciated :)

According to https://dangerousthings.com/wp-content/uploads/PN532_Manual_V3-1.pdf you are doing everything correctly, Uno pins and supply voltage is okay.. Can you invert the two switch positions for interface selection for fun? Can you try their example code from the PDF? Can you try the I2C interface?

@MaximilianGerhardt I cannot use anything else than SPI, because I probably broke the SDA and SCL soldering points when trying to resolder them... (Perhaps this explains the weird behavior and is the chip dead, but I am refusing to believe that for now). Concerning the code, this is the exact code from their GitHub.


text:
Reading RAM from SH1106 OLED Controller through I2C
Summary: I'm having trouble with writing a program to get RAM data from an SH1106 OLED controller via i2c. In the first part of the question I've written the assumptions I've made to get informations I couldn't find in the datasheet, in the second part I've posted a program which should read that data but doesn't (obviously, since I'm writing here...).

I'm working on a program to control an SH1106 OLED display. I read the datasheet to find out how to send commands to it and it works, I can write to my display.
Now in the datasheet there is one thing I don't understand: how can I read the RAM?
Consider the picture below, taken from the command table at pages 30 and 31 of the SH1106 datasheet; the last line is the one about reading RAM.
This chip can be connected to a microcontroller through different interfaces: 6800 and 8800 8-bit parallel, 3 and 4 wire SPI and i2c. Since I'm using SPI I don't have any A0, RD or WR pin, and I didn't found anywhere in the datasheet a "translation" of the boolean value given to those signals in the command table to some i2c signal. I assume that WR corresponds with the lsb of the i2c address, since it is 0 for writing and 1 for reading. And my assumption seems to be true since I can read the status (line 25).
Then I assumed that A0 should match DC (Data/Command, see second screenshot), a bit of the Control byte. The control byte is a byte that has to be sent before each byte or group of bytes to tell the chip how to interpret it (command or data). But I tried to send it before an i2c reading with different values and I always get the status byte (never the RAM data).
How could I read the memory of an SH1106 chip through i2c? The datasheet doesn't states that it is impossible (neither that it is possible...), maybe I simply can't?
Command table

(I removed lines 1-16, which contain commands like those at lines 17-23)

Control byte

EDIT
Here is the shortest working program I could write which shows the problem (i.e. which contains my implementation errors). I tested it on an Arduino UNO.
#define ADDR  0x78

void i2c_start() {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while (!(TWCR & (1 << TWINT)));
}

void i2c_stop() {
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
}

void i2c_send(uint8_t data) {
  TWDR = data;
  TWCR = (1 << TWINT) | (1 << TWEN);
  while (!(TWCR & (1 << TWINT)));

}

uint8_t i2c_read(bool isLastByte) {

  if (isLastByte) TWCR = (1 << TWINT) | (1 << TWEN);
  else TWCR = (1 << TWEA) | (1 << TWINT) | (1 << TWEN);
  while (!(TWCR & (1 << TWINT)));
  return TWDR;
}

void display_init() {
  i2c_start();
  i2c_send(ADDR);
  i2c_send(0x00); //................ control byte
  i2c_send(0xAE); //................ displayOff
  i2c_send(0x8D); //................   *
  i2c_send(0xD5); i2c_send(0x80); // clockFrequency
  i2c_send(0x32); //................ pumpVoltage0123
  i2c_send(0xA1); //................ segmentRemap
  i2c_send(0xC8); //................ flipVertically
  i2c_send(0xDA); i2c_send(0x12); // comConfiguration
  i2c_send(0xA8); i2c_send(0x3F); // multiplex
  i2c_send(0xD3); i2c_send(0x3F); // displayOffest
  i2c_send(0x10); i2c_send(0x00); // columnAddr
  i2c_send(0x40); //................ startLine
  i2c_send(0xB0); //................ pageAddr
  i2c_send(0xAF); //................ displayOn
  i2c_stop();
}

void setup() {

  // Initialization
  Serial.begin(115200);
  display_init();

  // Request RAM data
  i2c_start();
  i2c_send(ADDR);
  i2c_send(0x80); //   control byte
  i2c_send(0xB0); // page address
  i2c_send(0x80); //   control byte
  i2c_send(0x10); // column address high
  i2c_send(0x80); //   control byte
  i2c_send(0x00); // column address low
  i2c_send(0x40); //   control byte
  i2c_send(0xE3); // nop
  i2c_stop();

  // get RAM data
  uint8_t a[10];
  i2c_start();
  i2c_send(ADDR + 1);
  for (int i = 0; i < 9; i++) a[i] = i2c_read(false);
  a[9] = i2c_read(false);
  i2c_stop();

  // print results
  for (int i = 0; i < 10; i++) {
    Serial.print("0x");
    Serial.println(a[i], HEX);
  }

}

void loop() {}

I've tried as many possibilities as I could imagine in the // Request RAM data section. To avoid confusion I leave only the posted one to your kind analysis, but of course if someone would like to see them just write it in a comment and I'll post all the (unsuccessful) test I have made.
The output on the serial monitor is always a list of 0x3s.
I've not reduced the initialisation routine I use in my code because maybe the issue comes from there. BTW, I have no idea about what the i2c_send(0x8D); //................   * line does, I've added it because all the others SH1106 libraries I found had it, but I didn't found it in my datasheet. Maybe there are multiple versions of the chip or of the datasheet?

My version of the data sheet has a flowchart (Figure 10) for doing a "read-modify-write".  In there is a clue - there has to be a dummy read before the actual read is done.  Here is my function for plotting a pixel, which requires a read-modify-write to add a pixel to the existing data.  It's not clear dummy read is needed before every byte read, or just on the first of a sequence of bytes, but that's easy enough to test.
#define CTRL_LAST_CMD 0x00
#define CTRL_NEXT_CMD 0x80
#define CTRL_LAST_RAM 0x40
#define CTRL_NEXT_RAM 0xC0

void MySH1106_PlotPixel(char x, char y, char on) {
  unsigned char curDisp;
  MySH1106_SetPage(y/8);
  MySH1106_SetCol(x);

  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_CMD);
  Wire.write(0xE0); //R-M-W enable
  Wire.endTransmission(1);

  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_RAM);
  Wire.endTransmission(1);

  Wire.requestFrom(SLAVE_ADDR, 2, 1);
  while(Wire.available()<2);
  curDisp = Wire.read(); //dummy read
  curDisp = Wire.read(); //real read.

  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_RAM);
  if (on) {
    Wire.write((0x1<<(y%8)) | curDisp);
  } else {
    Wire.write(~(0x1<<(y%8)) & curDisp);
  }
  Wire.beginTransmission(SLAVE_ADDR);
  Wire.write(CTRL_LAST_CMD);
  Wire.write(0xEE);//end R-M-W
  Wire.endTransmission(1);

}

This is woefully inefficient for plotting one pixel, but it's a start.
Edit: I've subsequently confirmed that only 1 byte of dummy read is needed, even if the reads are stopped/restarted.  As long as you're only doing RAM reads, no further dummy reads are needed.

It's slightly tricky understanding the protocol with I2C.  The bit to watch is:

If the R/ W bit is set to one in the slave-address, the chip will output data immediately after the slave-address according to the D/C bit, which was sent during the last write access. If no acknowledge is generated by the master after a byte, the driver stops transferring data to the master.

So you have to set the D/C bit in the transaction before you want to access the RAM.
It's unclear from the datasheet if you have to send a data byte after the control byte for it to be accepted, but if you do you can use the NOP command.
So you do a write of NOP with D/C (which, yes, corresponds to A0 in the other interfaces) set to 1 in the control byte (i.e., write the bytes 0x40 0xE3) and then you can do a read which should return the RAM contents at the current page/column address, which will auto-increment for each subsequent byte.
It's quite an unclear datasheet when it comes to explaining how I2C reading works...

Thank you for your answer. I've tested it (in particular I hadn't considered using a NOP after the 0x40 control byte), but I'm still unable to read the data. I've edited my question adding the shortest code I could write which still contains and shows the problem.


text:
RS422 interfacing with the Arduino
Good day,
I have a sensor which supports serial data output using RS422 which has 4 wires (RX+, RX-, TX+, TX-)
my question is how can I connect this sensor to the Arduino.
I read that i can use 2 max485 chips to do this but uncertain of the exact procedure.
Thanks in advance.

This is not really an arduino question, for of an Electrical Engineering question,    this should help   https://electronics.stackexchange.com/questions/280073/how-to-interface-rs-422-to-uart-on-my-mcu

There are pre-made and very inexpensive Arduino RS-485 modules available on Ebay or Amazon.  Much simpler than building your own circuit.
They look like this:

The MAX490 chip consists of DI (pin 3) and RO (pin 2) pins that connect to the Arduino TX and RX respectively. the rs-422 side of the chip consists of pin 5 (Y / T+), Pin 6 (Z / T-), pin 7 (B / R-) and pin 8 (A / R+)
http://arduinotronics.blogspot.com/2018/09/long-distance-serial-with-rs-422.html