text:
Communication between 2 arduino boards
I am not really 100% too sure how to do this but I am trying to make my arduino UNO communicate with my arduino MEGA. The reason why I needed to do this was because I was using the RFID module along with a TFT display and the problem I faced is that on the arduino mega they both needed pin 53. Luckily I have an arduino UNO so I just went for that instead for the display. I am trying to use the analogWrite() function to send analog signals from my MEGA over to the UNO so that the TFT display on the UNO can display the results. The UNO would also read the analog inputs coming from the MEGA. This did not work very well. The analog inputs are being sent from the MEGA but the UNO is not reciving them. I am using a PWN pin on the MEGA to send the analog output to the UNO.
This diagram shows what I mean:

These are the 2 compotents I am using:
https://i.sstatic.net/CqXdB.png
TFT display

RFID

This shows how the libary sets out the pins. I am only a beginner so I personally don't want to mess around with the libary.

Use Serial or I2C or SPI. Never try this sort of thing with analogue, it's just not realistic.

How do you use those? I am quite new to all of this.

Start by googling for some tutorials. There's no shortage.

What was the deal with pin 53?  What were they using it for?  Sounds like SPI in which case they can just share it.  Perhaps figuring that out first would be smarter and you won’t end up with such a convoluted design.  If it’s not about SPI then most likely you can switch one of them to

Also note that a PWM signal is alternating 5V and ground.  It isn’t a true analog signal.  When you try to read it with the other Arduino you won’t get an analog reading.  You’ll get 0 sometimes and 5V sometimes.

@Delta_G pin 53 is used for an RFID module

@Delta_G Do you know at all how you can send analog signals on an arduino because there is a analogWrite() function

Pin 53 is just the default Slave Select pin for SPI. You can pick literally any pin instead of 53. There's nothing special about it (unless you're doing SPI slave mode).

@Majenko I think the RFID module uses SPI. The issue is that I have a display which uses SPI and an RFID module that uses SPI and they both cannot use it at the same time.

Yes they can. That's the whole point of SPI. The only pin that needs to be unique is the SS pin, All the others can be shared. And you can change pin 53 for any other pin

I have what modules I am using above:

If you have "shields" that mount on top of the Arduino then cut pin 53 off the top level one and solder a wire from there to another pin somewhere else. If you don't have "shields" then just plug the slave select pin from one of the modules into a different pin.

@Majenko I don't have the tools to do that!

Then get the tools. Those are basic tools for working with electronics. Arduino isn't LEGO®, it's electronics. Real electronics.

Take the wire that connects to pin 53 of the RFID module and plug it into another hole on the Arduino. Look at the number next to that hole. Read the manual for the RFID library you are using and look for the words "chip select" or "constructor" or "slave select" and it will tell you where to stick the number you just read.

@Majenko, I don't have sheilds, I think the RFID documentation specifically mentions that pin 53 needs to be used and additionally this is the same for the TFT display

@Majenko The picture above shows what I mean

The RFID neither knows nor cares what pin it's using. Only the library cares, and most of those have a specific way of telling it what pin you want to use. RTFM for the library, not the RFID.

@Majenko I am only a beginner so I personally don't want to mess around with the library.

I'm not telling you to "mess around" with the library. I am telling you to read the manual. Or at the very least tell us what library you are using so we can point you to the paragraph that tells you how to use a different SS pin!

@Majenko Here is the libary: https://github.com/miguelbalboa/rfid

You see in the table of pins on that page you link to? See the little [2] next to pin 53? Click it. It takes you to a bit that says "Configurable, typically defined as SS_PIN in sketch/program."

All the examples have #define SS_PIN ... in them where you can change the pin that you want to use instead of 53. The constructor has MFRC522 mfrc522(SS_PIN, RST_PIN) where you can put any pin numbers you like (or just redefine the macros to be something else).

You can use the I2C interface.
TX:
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

RX:
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

Schematic:

Image by Dronebot Workshop; check out their tutorial for more info: https://dronebotworkshop.com/i2c-arduino-arduino/

This is perfect! Thank you so much! :)

You are welcome!

What is the address 8 part?

That is just any address both the boards communicate on. It can be any number but it has to be the same on both sides.

Isn't the RX pin pin 0 and the TX pin is pin 1 thought or vice versa?

Can you show a schematic that shows this? It might help me to get a better understanding.

Yes so this is the wire library can doesn't use the Serial put. I will put the schematic in the answer.

Can it work with different boards? I am using an arduino MEGA and an arduino UNO

Yes, for the mega, right next to the Serial pins, there is an SDA and SCL pins. Use those. Also, remember to connect both of their grounds together, or else it will NOT work.

Have you potentially got a schematic using a mega and uno? (I am quite new to the arduino)

I put the schematic in the answer.

What if you want only 1 way communication

This is one way. One is TX and the other is RX.

Pin 53 is just the default "slave select" pin. There is nothing special about it. You can use any other pin as slave select, as long as the libraries for your devices allow it (check the documentation and tutorials for those libraries).
You cannot transmit information with analogWrite() since it isn't really analogue (it's PWM), and analogue doesn't have enough definition for reliably representing more than a handful of discrete values anyway.

I realize I'm later here, but: As an AVR SPI master, you cannot allow your SS pin to go low as input.  So if you chose something other than 53 (or SS on an AVR generally) to be your slave select line, you'd still want to set 53 to be OUTPUT, or INPUT_PULLUP, or INPUT and pulled up externally.  Otherwise you may be taken out of master mode by noise on the pin.  Not that it goes against your main point, but here is still one thing to be aware of that is special about 53/SS with regard to SPI master.


text:
Using 1 ms delay() in a for loop to check inputs.. Bad?
So first off, I know millis() exists. Just asking out of curiosity. Say you have a button you wanna check for during a delay.. Maybe a 10 second delay. So you make a for loop that checks for input and delays 1 ms... 10,000 times. What's bad about this?
 int pin = 13;
    bool button = false;

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

    void loop()
    {

     while(button == false) {
     for(int i = 0; i<10000; i++) {
     if(digitalRead(pin,HIGH){
     button = true;
}
     delay(1);

    }
  }
}

Guess why loop() is called loop.
Your code becomes simpler, if you don't nest other waiting loops inside.
Simpler is Better.

You can do this, for quite simple sketches. It starts to become ugly if you add more features and conditions.
Therefore, the "correctTM" (read: professional) way is to implement a state machine. See in the IDE the non-delay blink example.
const unsigned long DELAY_MS = 1000;

int pin = 13;

enum State {
    WAITING, WORKING,
};

State state;

unsigned long startTime;

void setup()
{
    pinMode(pin, INPUT);
    state = WAITING;
    startTime = millis();
}

void loop()
{
    switch (state) {
    case WAITING:
        // You can put both conditions in one "if" with an "||" operator.
        // But it will look less clear.
        if (millis() - startTime > DELAY_MS) {
            state = WORKING;
        } else if (digitalRead(pin)) {
            state = WORKING;
        }
        break;
    case WORKING:
        // anything to do after the delay or the button
        break;
    default:
        // any error handling you see fit
        break;
    }
}

The function loop() is designed to be called endlessly in repetition. Use this to your advantage.

What's bad about this?

It looks a bit clunky but I suppose there is nothing particularly bad about it (apart from your typo of digitalWrite rather than digitalRead).
I would do it more like:
unsigned long now = millis ();
button = LOW;

while ((millis () - now < 10000) && (button == LOW))
  button = digitalRead (pin);

but then, if would work too in loop()

I know millis() exists

Ok, millis is always the best way...

Say you have a button you wanna check for during a delay..
So you make a for loop that checks for input and delays 1 ms... 10,000 times.

Your code is not really doing what you want. Your while loop never ends until button is pressed so 10s delay has no sense. I suppose your code should exit after 10 seconds or if button is pressed.

Just asking out of curiosity

You're code, without millis(), should be
bool button = false;
...
...
void loop() {
  uint16_t ms2wait = 10000;
  while (button == false && --ms2wait > 0) {
    if(digitalRead(pin,HIGH)
      button = true;
    delay(1);
  }
}

In my case I don't want the while loop to end until a button is pressed. I'm also trying to bring forth discussion on why millis() is better than delaying 1ms 10,000 times.

You should ask "Would my code do something else while it's waiting for an event?". If the answer is YES your code should use a millis() approach if it's NO you can use delay(). I said millis is the best way because YES is on 99,99% the right answer. In your example, 10 seconds is a huge amount of time and it's quite obvious your MCU should do something else in the meanwhile. In general checking if 10000ms are elapsed or freezing your MCU for 1ms 10000 times is quite the same.

I say quite because using1msx10000 you don't consider the time spent to run the code inside the for loop and this could increase the real delay after 10000 cycles.

source: Stack Exchange

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

sort: votes


text:
Keyboard/mouse libraries with UNO
I have an Arduino Uno Rev. 3 and I'm trying to make it so that the Arduino can send a key press / mouse action to the computer. However, these libraries are restricted to a few other versions of the board. Is there another alternative method to doing this without actually pressing any buttons/interacting with the arduino other than USB? Thanks!
Link

These at fist glance don't seem to be duplicates. However, the original question is basically the same thing, just suggesting a method for doing this. If you feel this isn't a duplicate, or you want another way (ex: PS2 mouse/keyboard support), feel free to edit your question and flag it for moderator attention so one of us can take a look at it. Thanks!

It is actually possible, but not easy.
The main MCU on the Uno, the ATmega328, is not capable of using the USB connection at a low enough level to make this possible. The other MCU on the Uno R3, the ATmega16U2, is. You can reprogram it to act as almost any arbitrary USB device.
Since the '16U2 has no connection to digital pins 2 and up or to any of the analog pins, you would have to program it to communicate with the '328 (or an external chip) via UART, and then have another program running on the '328 that would communicate with the other pins.
Note that you will need an external programmer for this, since once the '16U2 is reprogrammed you will lose the ability to program the '328 until you restore the original programming. Using another board running ArduinoISP will work for this.

A software approximation to low-speed USB using GPIO pins of the '328 itself and passives to sort of achieve the required USB voltages might be another option.

@ChrisStratton: The '328 does not have any access to the USB lines whatsoever, so you'd have to wire in another USB connector.

Yes, of course - but that also preserves the original one for development use, both loading programs and having serial debug output (which can be extremely useful when dealing with USB code).

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


text:
What's the maximum number of keys in Yun Bridge?
The Yun has a Bridge for communicating between the Arduino and Linux processors via a key/value hash. The docs say this is actually stored on the Linux side, but it doesn't say what the limit is.
How many key/value pairs can the Bridge store? What are the practical limitations?

I think that the limit is the memory in the atmega32u4 and the speed limit for the python script on the linux side. About 20 values should be no problem, but when you have 20 different values, all the updating and controlling those 20 values via the bridge can be a problem. When you need 1000 values, perhaps you can try to control everything on the linux side and start a linux-script from the arduino side now and then. The best solution is stop using the yun right now, before you spend too much time struggling with it. Have a look at the mkr wifi boards, or the esp32 or the raspberry pi.

The data is just stored in an array within the Python daemon. The ATMega32U4 just sends commands to set / get the values, so there is no limit imposed by the ATMega side of things.
The only limit is the size of the array in Python, and that is restricted by:

The amount of available memory in Linux, and
Whether or not you have swap space set up on the Yun

Since both those are very much variable (it depends what processes you have running, what your configuration is, etc) the answer can only really be:

Quite a few.

Putting memory aside for a moment, an answer to this question on SO states:

According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*) . On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

So you have the smaller of:

The maximum you can fit in Linux's memory, and
536,870,912

Majenko, google translate has troubles with the expression "quite a few". It can understand "quite a lot" or "a few" and also "quite a few beer", but it gets confused with just "quite a few". It is "many", right? Have you used the arduino yun? Every idea that pops into my mind turns out to be very hard to implement on the arduino yun.

GT often struggles with idioms. Quite A Few = A Lot, but not a huge amount. More than a few, less than a massive amount. I have a Yun, but all it is doing at the moment is being a router to connect my sky box to the WiFi. The Yun was a nice idea when first thought up, but MCU technology has moved on since then, and it's pretty redundant now.

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


text:
Wiring 5V ultrasonic sensor to Arduino Due
Is it possible to use the 2760342 ultrasonic range sensor with an Arduino Due? The docs say it takes a 5V input, but doesn't specify the output, but I'm assuming it also outputs a 5V signal. Does this make it incompatible with the Due?
I've tested it with an Uno, it it works flawlessly. I've been researching using a Due and some other ARM based single-board computers, but they all seem to use 3.3V, while almost all Arduino shields and sensors use 5V. I'm hesitant to "upgrade" to these boards if I have to purchase an entire new set of shields and sensors. And I have no interest in hacking in some clunky custom voltage level shifter. Why isn't everything standardized on 5V?

Is this too clunky?
https://www.adafruit.com/products/735
Breadboard Friendly 8-bit Logic Level Shifter, $1.50.

Yes. I have no interest in buying an $80 SBC and then spending weeks debugging my own hacky level shifter circuit. That's like buying a new car for $30k and then having to make your own tires...

If your question is "Why isn't everything standardized on 5v?", see this good SO answer:
https://electronics.stackexchange.com/questions/135841/voltage-standards-like-3-3v-5v-etc
Bottom line is that the voltage drops as the electronics' technology advances (12v to 5v to 3.3v).
Concretely to your problem, I honestly do not think that a level shifter is somewhat "clunky" solution to your problem, as suggested by mikeY (and as rejected by you). This is the way things are done in the electronics world - when a hardware mismatch arises, there is a hardware adapter to rescue.

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


text:
Determine difference between 3.3V and 5V shields
How do you determine if an Arduino shield uses 3.3V or 5V on their pins?
Previously, I thought all Arduino shields used 5V, since that's what most  Arduinos use. However, I've been researching Arduino-compatible single-board computers like the PCDuino and Galileo, but these all seem to use 3.3V. More confusingly, they're vague about what types of Arduino shields they support. The PCDuino claims to only support 3.3V shields, but has an adapter shield to convert 5V. The Galileo has a jumper to support either 3.3V or 5V shields.
The main problem is how do you determine what voltage level Arduino shields use? I have a Seeedstudio motor shield and a Sain Smart sensor shield, and while they both take 5V power input, the docs don't mention anything about logic voltage level. How do I determine this?

Can you provide links to the doc's you're referring to? Maybe someone can look at those and see if the relevant info is there.

A 5v shield on a 3.3v arduino could fry the arduino. A 3.3v shield on a 5v Arduino could fry the chip(s) on the shield. Could, but not necessarily.

You read the schematics and datasheets. The former will tell you what power supplies are connected and how, and the latter will tell you what voltages are acceptable to the devices.


text:
How to wire QRB1114 IR sensor to an Arduino Uno
What's the best way to wire a QRB1114 IR sensor to an Arduino Uno? I'm attempting to use it as a white-line-on-black-background line detector. Google shows many different ways wire it to an Arduino, but I'm using this one because of its simplicity.
However, when I tested the circuit using the AnalogInput example code, I'm not getting the expected behavior. It registers a reading of 0 for both white and black backgrounds (I'm using white and black electrical tape as test surfaces), and occasionally registers between 5-10 if there's nothing in front of it at all.
What is the most likely problem? Is this circuit an improper way of wiring the sensor? Is my sensor defective? Is the code not reading it properly?
This is my test code:
#define BUTTON_PIN 2
#define LED_PIN 13

const int IR_SENSOR_PIN = A0;
int sensorValue = 0;

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

void loop() {
    sensorValue = analogRead(IR_SENSOR_PIN);
    Serial.println(sensorValue);
    delay(1000);
}

It was a dumb programming/wiring problem on my end. As I discovered from this description, the signal pin needs a pullup resistor. Since my circuit doesn't have that, I need to enable the pullup resistor on A0, which I wasn't doing.
After modifying my code to do that, the sensor works as expected.

Good find. Depending on the range (white vs black surface) you get from analogRead you might want to use a different value (external) resistor.


text:
Interfacing with an SSI sensor?
I'm trying to interface with version RM08S of this rotary encoder using an Arduino Mega. The sensor supports a "Synchro serial interface (SSI), single ended" interface. I'm unfamiliar with this protocol.
Despite the name, it doesn't appear to match the description of the formal SSI or RS-422 specification, since that requires two wires for differential clock and data lines, whereas this sensor only has a single wire for each. This makes it sound more like IIC, but without the bus-like functionality.
Googling finds very few results on interfacing the Arduino to SSI devices, much less any standard libraries. This forum thread asks a similar question, but doesn't seem to resolve the issue.
Since there's just a clock and data line, would reading from this be as simple as toggling clock, and then reading the 10-bits of data from the data line, sequentially with each clock tick, accounting for whatever bits are used to pad the packet?

On my RM08 is an RS422 Interface connected. Can i just connect Data+ to Miso and CLK+ to SCK?
@Majenko

It's just SPI.
SPI.begin();
SPI.setDataMode(SPI_MODE2);

// ...

uint8_t h = SPI.transfer(0x00);
uint8_t l = SPI.transfer(0x00);
delayMicroseconds(20); // Indicate EOT
uint16_t v = (h << 8) | l;
v >>= 4; // for 12 bit resolution, 5 for 11 bit, 6 for 10 bit etc.

For 8 bit resolution or less you only need one SPI.transfer, and subtract 8 from the right-shift amount.
Wiring is simple: clock to SCK (52 or ICSP 3) and data to MISO (50 or ICSP 1).
The timing diagrams in the datasheet (page 5) describe it all in detail.

If it's functionally SPI, why are they calling it SSI? Aren't those very different things?

It's almost SPI. Close enough to work. There is no CS pin, and timing is more critical, so they can't really call it SPI. It's a serial interface, and it's synchronous.

The datasheet notes that the clock should start high, and after a falling-edge, the sensor value is latched, and on the next rising edge, you get the MSB. For SPI, doesn't clock start low, so you won't get the MSB until the 2nd cycle (2nd bit)?

@josecanuc It depends on the "mode" of SPI. You may need to issue an SPI.setDataMode(...) to set SPI into the right phase / polarity.

@josecanuc Thanks for pointing it out, by the way. I have added the right mode call to the example above. It looks like SPI_MODE2 should do it (Polarity = 1, Phase = 0)


text:
Which Arduinos have a true serial port?
After driving myself insane with an unreliable Leonardo, I narrowed down the problem to its serial port. Namely, it's not a true serial port, but some sort of simulated monstrosity that can't be reliably reset. This makes uploading sketches immensely difficult. I found that neither Arduino-Makefile nor the Arduino IDE can reliably upload sketches to a Leonardo, and succeed only 10% of the time.
It took me awhile to accept just how terrible the Leonardo was, because before this, I had only used the Uno and Mega, which are extremely reliable. They've always "just worked" for me, so I couldn't understand why Arduino would release a board as unusable as the Leonardo. I've since realized the Uno is so reliable, in part because it has a more complete serial port, and don't use the dreaded 32u4 chip and its fake serial port that doesn't support the DTR or RST pins.
That said, which Arduino's have a real serial port? Is it only the Uno and Mega? After months of banging my head against a Leonardo, I want to avoid anything else that uses the Atmega32u4 chip. Unfortunately, looking at all the various boards, it looks like many, especially most of the newer ones, use the 32u4.
Am I missing something here? Everything I Google an error uploading with avrdude or the IDE, the results always mention problems with boards like the Leonardo and their unstable serial ports. Why does Arduino keep using the 32u4 chip if it's that unreliable?

No Arduinos since the Arduino Serial have a real serial port. They all leave it to the USB-UART bridge (if any) to handle anything beyond RX and TX.

Strange, I (and many others) have never had such problems with the Leonardo not the other 32U4 based boards.

Most of your question is just a rant. And your definition of a "real" serial port seem to be no native USB support. There are Arduinos with native USB support that are not 32u4 based but ARM based.

Your problems are likely caused by loading bad sketches.  A more productive question would focus on the means of recovering from this, ie, identifying a reliable way reset the board and stay in the bootloader to erase the bad sketch.

@ChrisStratton, I doubt it's the problem with the sketch. I was able to upload the same sketch to an Uno and didn't experience any issues. I heavily researched ways reset the Leonardo, and the near universal answer was that were was no reliable method, short of using an ISP to reflash the bootloader, which is what I did, and why I dislike the Leonardo. I expected this question to get heavily downvoted, because I know you're very defensive of these terrible boards, but I'll leave it up because I stand by my experience. Please everyone, avoid the Leonardo like the plague. It's a bad product.

@Cerin, I hear you. In linux, with an old Leonardo bootloader or third party bootloader, and a wrong sketch, and something called 'modemmanager' in linux, it is a real problem. In Windows and with a recent bootloader, it is working 100% okay. Do you have a programmer, and did you burn the bootloader with the Arduino IDE ? In linux, remove the 'modemmanager'. Yes, the sketch can be a problem when sending too much to the usb serial port. It could block something, preventing a restart of the bootloader.

A flawed sketch will not prevent reprogramming of an Uno; the same code on a Leonardo will prevent the logic that can intercept programming requests after the start of a user program from doing so.  But it's still a badly written sketch.

@ChrisStratton, Why is documentation of these shortcomings in the Leonardo so difficult to come by? Where's the list of things not to do so you don't disable your Leonardo? The Arduino community prides itself on documentation, but I found few solutions Googling this problem. Had I known it was so fragile and incompatible with Uno sketches, I would never have bought it. And therein lies the reason why these flaws aren't advertised...

@Jot, These problems began when I flashed the most recent bootloader using the 1.8.2 IDE. That completely disabled sketch uploading via USB. I had to manually use avrdude to flash the bootloader, as I described here, to restore it. What problems does modemmanager cause? I have the modemmanager package installed, but it's a service that's not running.

@Cerin - Actually Arduino documentation is notoriously, and universally, horrible in comparison to that of actual engineering components, libraries, and APIs.  In any other context, the fact that a USB stack can be broken by uncareful use of interrupt disables, clock, or I/O setting changes, or general memory corruption or execution runaway is well known.

@Cerin, remove the modemmanager.

There seems to be quite a few Arduinos without a 32U4, like:

Uno (you mentioned it already)
Mega (same)
Lilypad Snap
MKR1000
Pro
Pro Mini
Zero
Due
Ethernet
Mini
Nano
MKR Zero

See the list at Comparison table.


text:
Avrdude fails at specific baudrates
I'm seeing something very strange. If I run:
ard-reset-arduino /dev/ttyACM0;
/usr/share/arduino/hardware/tools/avr/bin/avrdude -C/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:`pwd`/.build/main.ino.hex:i;

Avrdude uploads my sketch to an Arduino Uno just fine. However, if I change the buadrate to 57600, it fails with the error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I've tried manually pressing the Arduino's reset button just before I upload, but there's no change.
Why is this happening? If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

Arduino bootloaders doesn't have any baud rate detection and baud rate is fixed (for the different boards there might be different baud rates)
Only Leonardo (and others with native USB) are almost idependent on baud rate  except for 1200bauds used as "reset". (However it runs at maximum speed that the MCU can handle)

Details for these modes can be found in boards.txt

If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

The bootloader is a piece of code designed to work at a specific baud rate. As KIIV said in his answer only the USB-based Arduinos would be relatively immune to changing the rate.
What your own code does, after being uploaded, is completely irrelevant.

Avrdude fails at specific baudrates

Your title really should be: "Avrdude only works at one baudrate (the one it was designed to use for a specific board)"


text:
Is there a way to make wiring a bare microprocessor to a shield easier?
I currently do most of my AVR work on breadboards, but the large variety of Arduino shields and code out there makes me wonder if I'm not beating my head against the wall sometimes, and looking up port to pin mappings both wastes time and slows me down. Is there any convenient way to adapt AVRs (other than those pin-compatible with current Arduinos) to Arduino shields?

Are you asking: Is there a way to make wiring a bare microprocessor to a shield easier?

@Cybergibbons: That is exactly what I'm asking.

To that one, I don't have an answer. Honestly, my way of working around this is to almost exclusively use I2C or SPI devices so there are only a few pins to remember.

@JarrodRoberson You have replaced the AVR in the title with microprocessor, AVRs are not microprocessors, they are microcontrollers which is a microprocessor+memory+peripherals etc. You have also removed the word Arduino from the shields but the question refers to Arduino shields, not shields in general.

You could (scrape off and) desolder the chip in an Arduino board and replace it with a '28 Pin IC Socket' (google that term to see what I mean).

You can make adapter boards (one for each mcu model).
The bottom side (male headers) would plug to the breadboard and the upper side would have female headers with the same pinout as an Arduino board (female hearers placed in the appropriate positions to match Arduino shields).
Such a board shouldn't be difficult to design.
Here is an image that resembles what I describe

It would adapt the pinout of a bare AVR to the pinout of a typical Arduino so that shields can by directly plugged on top of it.

Also a pinout diagram may come handy to speedup things when you use a bare chip with Arduino code.
(image source)

Another similar solution is a small printed sticker placed on top of the AVR
(image source)

+1 for the didatic effect of the adapter board picture AND VERY TIDY breadboarding.

@Ricardo Although I do agree it's a good picture, it is from another site (source listed). Otherwise, great answer! BTW: Be cautious if the shield connects to ICSP... the Ethernet r.3 does to add Mega compatibility.

The Arduino-way of doing that is making a lookup table that translates pin number to PORTn / DDRn / PINn SFR and the related bit. You can use the same trick and make GPIO pins count in a convenient way as they are in the package. Only special peripherals (like SPI / PWM) cannot be accounted for in this way because they are hard wired to a pin.
A good start is the below Arduino.h library sniplet if you want to re-use that concept.
// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.

#define analogInPinToBit(P) (P)

// On the ATmega1280, the addresses of some of the port registers are
// greater than 255, so we can't store them in uint8_t's.
extern const uint16_t PROGMEM port_to_mode_PGM[];
extern const uint16_t PROGMEM port_to_input_PGM[];
extern const uint16_t PROGMEM port_to_output_PGM[];

extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];

// Get the bit location within the hardware port of the given virtual pin.
// This comes from the pins_*.c file for the active board configuration.
//
// These perform slightly better as macros compared to inline functions
//
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
#define analogInPinToBit(P) (P)
#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )
#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) )
#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) )

The pinMode, digitalWrite and digitalRead functions are defined in /usr/share/arduino/hardware/arduino/cores/arduino/wiring_digital.c which can be used for further inspiration.

While this answer covers the software part, my question actually asks about the hardware part.

@IgnacioVazquez-Abrams can you elaborate a bit more in your question then? Not sure if I understand what you're asking.

I have bare AVR chips, and I want to use them with existing Arduino shields without having to add a couple dozen jumper wires.


text:
Using an external interrupt alongside serial
I want to read data from an accelerometer sensor, which pushes its data to the Arduino via an external interrupt. I then want the Arduino to relay this data to a host computer via the serial connection.
Will the external interrupt interfere with the serial connection? If the Arduino's in the middle of transmitting via serial, and the accelerometer triggers the interrupt, won't that potentially break the serial connection?

What do you mean by "break the serial connection" exactly?

Transmitting a single character via UART on the ATmega328P (and all other AVRs with a dedicated USART) cannot be interrupted since it is independently clocked. Loading the next character into the transmit buffer can be (since the INTx interrupts have priority over the USART,xxx interrupts), but this will not actually break communications, just slow it down.


text:
Asynchronous control framework
Can anyone recommend an Arduino-based asynchronous scheduling library for controlling a small mobile robot?
I'm writing the control code for a small 2-wheeled Arduino-Uno based robot. It has a few bumper sensors, IR sensors, and ultrasonic sensors. I've written an initial pass from scratch, using loop() to read sensors and set motor values appropriately and then wait for the motor to have effect, but I'm finding this cluggy. Some of the sensors, like the ultrasonic range finders, require a small delay to operate, and the motors require a delay to have an effect. Blocking loop() is the simplest way to achieve this, but it wastes cycles, and can be difficult to time each action properly without throwing off other behaviors. Writing an asynchronous scheduler would be more efficient, but a lot more complicated, and I expect I would be reinventing the wheel.
I found this list, of existing scheduling libraries, but I'm not sure which, if any, would be appropriate.

You may also want to take a look at cosa library on github.

@jfpoilpret, Interesting. I'm not sure I want to throw out the default Arduino library just to use some scheduling componenets. And it's a shame Cosa's documentation is so bad. Why do so many developers think a class index with few comments and no examples is all they need for docs? Looking through that, it's not clear what I should use. It has a Timer, Alarm and Periodic class, as well as a few other classes that may be scheduling related as well.

you're a bit unfair about documentation, it is not bad at all (compared to the standard arduino lib at least). Regarding examples, there are more than 100 of them and they are even a very good way to learn Cosa.

@jfpoilpret, I would agree that standard Arduino docs aren't great either, but the examples are better broken down by features set. I did see Cosa's examples directory, but other than the CosaAlarm example, I don't see anything else that uses the scheduling classes.

Hello, I'm currently testing leOS / leOS2 (see https://github.com/leomil72/ ) which seems to be a very nice scheduler lib for Arduino

I recommend writing your own in C++.  Arduino works well with C++ as it is written in C.  You can focus on getting the asynchronous behavior to do what you need instead of writing drivers.  I don't think it will take any longer to learn enough C++ to make this work than it will to learn to use, and possibly fix, a library. Your C++ knowledge will be much more generally useful than knowing a specific library.
Igor points out the advantages of going to a real time operating system.  I agree and think that, if you want to work on robots long term, you should go with an RTOS and get away from Arduino. Working with C++ and Arduino is one way to get started.

I would recommend ChibiOS: albeit it just got support for Arduino and it lacks a few drivers (I'm writing one for INTx and PCINT), it's got a fundamentally healthy design, a community around it and the author himself is very responsive.
You might have to write or port the drivers for external shields, however the upside is to get rid of the cruft that plagues most of the Arduino libraries.
You can even choose between 2 RTOS:

ChibiOS RT, a full fledged RTOS.
ChibiOS NIL, a minimalistic OS, actually almost a scheduler, which leaves more space and execution time for your own code. -
But if you check the amount of FLASH taken up by a typical binary built with the default Arduino libraries, you will see that it pulls in a large amount of typically unused stuff, so you could trade that for the use of the full fledged RT.

Disclaimer: I'm just a very happy user of the OS, I do not have any other involvement with it, especially the commercial part.


text:
Pinout for Leonardo USB
According to the docs, the Arduino Leonardo uses digital pins 0 and 1 for the USB D- and D+ lines. However, which is which? e.g. is D0=D+ or is D1=D+?
To save space in a very tight project, I want to wire USB directly to these pins instead of using the USB plug, however, I can't find any resource that explains which pin goes to which USB line.

Where does it say that pins 0 and 1 are D+ and D-?

"The ATmega32U4 provides UART TTL (5V) serial communication, which is available on digital pins 0 (RX) and 1 (TX). The 32U4 also allows for serial (CDC) communication over USB and appears as a virtual com port to software on the computer."

I think you are completely misunderstanding what it is saying there. The UART TTL and the USB are two completely different things. The UART is on pins 0 and 1, and a USB CDC/ACM connection is also provided (dedicated pins on the chip).

The USB does not go to pins 0 and 1.  The UART goes to pins 0 and 1 - that is a totally different interface.
The USB is connected to dedicated USB pins on the chip.  If you look at the Leonardo schematic you can see it is pins 3 and 4 on the chip. Note that that is not pins D3 and D4 on the board, but the third and fourth pins anti-clockwise from the "pin 1" dot on the main chip.

As shown in the ATmega32U4 datasheet, D- and D+ connect to pins 3 and 4 respectively of the MCU. But you don't want to wire directly to the chip unless you know what you are doing since the chip does not include the USB termination resistors. Follow the schematics given in the datasheet when connecting to the USB pins of the MCU.


text:
Differential steering drive equation
I'm trying to control an Arduino-powered motorized toy with a differential drive. However, I want to code it the motor movements with a direction vector.
e.g.
(1,0) = forward
(-1,0) = backward
(0,1) = turn left, pivoting on center axis
(0,-1) = turn right, pivoting on center axis
(1,1) = forward-left, pivoting on left wheel
(1,-1) = forward-left, pivoting on right wheel

I thought the equation to convert these to the literal motor signals was:
float mag = sqrt(dirX*dirX + dirY*dirY);
float left = dirX - dirY;
float right = dirX + dirY;

This seems to work for the first 4 cases, but fails for the last two, where it results in an un-normalized vector.
One potential fix would be to simple wrap left and right in min() to stop it from going over 1.0, but that feels like a hack, and would possibly lose resolution. Is there a more elegant fix?

Part of the problem is that "direction vector" is a bit vague in this context. Here are two popular ways of doing this:
(x = right speed, y = left speed)
This is like "tank drive", where two joystick's up/down axis are used to drive; you don't really need to do any math to get motor outputs.
(m = output magnitude, d = left/right balance)
I've heard this called "arcade drive", where one joystick's up/down is m and left/right is d.
Your equations are correct; the bounds check is unavoidable. Linear vector spaces just are not going to arbitrarily bound themselves at 1 for you. you could make it so "full speed ahead" doesn't actually max out the motor speeds; then when you turn it could still speed up one side a bit, but that is obviously still suboptimal.
You could try normalizing left and right, then multiplying by "m" again. The magnitude would be constant so you wouldn't have to do any bounds checking, but you would lose the pivoting on the center behavior you want, and full forward would be slower. You could also try making "d" an angle, and then choosing left and right with sine and cosine, probably shifted 45 degrees. That has the same problems.
I like to try driving it a bunch of different ways and see what handles best.


text:
Cheap weatherproof ultrasonic range sensor?
What's an inexpensive ultrasonic range sensor that's reasonable waterproof or weatherproof that also interfaces easily with an Arduino?
I've used these kinds of ultrasonic range sensors, which are cheap and trivial to wire to an Arduino, but they're not very robust and are easily damaged since you can't cover them without that covering obstructing the soundwave.
Maxbotix sells a "Weather-Resistant" ultrasonic range sensor, but it's around $100, which is a little out of my price range.
I've researched those "parking sensors" used on cars, but I haven't seen anyone successfully interface them with an Arduino. It's also hard to tell how they're controlled. Some sites sell batches of the sensor for $3/each, but I don't think this includes the control electronics. Ebay listings that include what appears to be a bulky controller board seem to go for around $50-$100, which makes them a little pricey.

Those modules are just the ultrasonic transducers. You can see the two pin connector. You can probably get those cheap boards, de-solder the two transducers, and connect the wires from two of the water-proof ones.


text:
SPISettings was not declared in this scope
I'm trying to compile a simple I2C example to read data from an MPU-6050 accel/gyro sensor, but I'm getting the compilation error:
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:27:8: error: 'SPISettings' does not name a type
 static SPISettings settings;
        ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectHigh()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:167:9: error: 'class SPIClass' has no member named 'endTransaction'
     SPI.endTransaction();
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectLow()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:9: error: 'class SPIClass' has no member named 'beginTransaction'
     SPI.beginTransaction(settings);
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:26: error: 'settings' was not declared in this scope
     SPI.beginTransaction(settings);
                          ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::init(uint8_t, uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:3: error: 'settings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
   ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:53: error: 'SPISettings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
                                                     ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:275:7: error: 'class SPIClass' has no member named 'beginTransaction'
   SPI.beginTransaction(settings);
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:279:7: error: 'class SPIClass' has no member named 'endTransaction'
   SPI.endTransaction();
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::setSckRate(uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:14: error: 'settings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
              ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:66: error: 'SPISettings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                                                                  ^
make: *** [.build_ano/uno/SD/src/utility/Sd2Card.o] Error 1
Make failed with code 2

I've commented-out all code until it compiled without error, and I found that the error is caused by the line:
#include <Wire.h>

So my minimal code to reproduce the error is:
#include <Wire.h>

void setup(){
}

void loop(){
}

Why is this include throwing this error? Why is it trying to compile code for accessing an SD card when I have no code that uses that?
I'm using Arduino 1.6.1 and targeting the Uno. I found I can fix this error by copying version 1.0 of the Wire library into my local sketch folder.

If fixed this by deleting this built-in library
/usr/share/arduino/libraries/SD

but then I received the error:
/usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
  Serial1.begin(9600);

so I deleted these libraries as well:
/usr/share/arduino/libraries/Robot_Control
/usr/share/arduino/libraries/Robot_Motor

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.

Can you elaborate any further on this? I tried these steps and it still isn't working for me.

Try a later version of the IDE. Try making a completely new sketch (don't just delete things from your current one). It looks to me like it is trying to compile things it shouldn't.

/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp

That doesn't seem relevant to your empty sketch.

Yes, it's strange, and yes, it's a completely new sketch.

If a sketch containing #include <Wire.h> and then void setup(){} void loop(){} doesn't compile there is something wrong with your installation. That should compile fine. Try IDE 1.6.8.


text:
Using a class instance with Wire.onReceive
Is it possible to register a class instance member function with Arduino's Wire.OnReceive?
I'm trying to make my code object-oriented, and want a specific non-static class function to handle I2C data, but if I'm reading this thread correctly, onReceive is incompatible with classes since it only accepts a function pointer, which won't store context.

A non-static class member function has an implicit ClassName *this parameter inserted as the first parameter in the parameter list.
Because the function prototype required for Wire.onReceive() does not have that parameter specified in its parameter list a non-static member function is not compatible with it.
The same goes for attachInterrupt() and anything else that takes a function pointer.


text:
Connecting via serial with Arduino comand line
Since inotool is dead, I'm trying to transition over to Arduino's built-in command line tool.
It seems largely equivalent, but the one feature it seems to be missing is a serial interface. e.g. Running ino serial would open a simple serial interface to the Arduino, providing invaluable debugging info from any Serial.print() statements.
How is this accomplished with the current Arduino command line tool?

You may want to just use some other command line serial solution.

@ChrisStratton, Such as...?

Well, I use an ever-evolving custom solution, so won't be of much help with that...

What OS are you using? Putty, screen, minicom ...

I ended up simply switching to ano.

If you are using linux, as I guess, you can look at this archwiki page. Even if is a wiki relative to archlinux OS some informations explained are LinuxOS independendent.
For your needs, you can use screen command. Here is an example: remember to substitute the serial port with the one wich arduino is connected (usually /dev/ttyACM* or /dev/ttyUSB*) and to specify the right baud rate.
screen /dev/ttyACM0 9600


text:
How to prevent inclusion of unnecessary libraries?
How do you save space by preventing the inclusion of unnecessary binaries?
When I compiled the ROS Blink example, I received the warning:
Global variables use 1,951 bytes (76%) of dynamic memory,
leaving 609 bytes for local variables. Maxiumum is 2,560 bytes.
Low memory available, stability problems may occur.

Considering the example uses almost no libraries, I was surprised by this, but sure enough, the compiler pulls in a ton of libraries that are never used:
Scanning dependencies of src
Scanning dependencies of arduino
Scanning dependencies of ros_lib
src/main.cpp
arduino/wiring.c
arduino/wiring_shift.c
arduino/wiring_digital.c
arduino/wiring_pulse.c
arduino/WInterrupts.c
arduino/hooks.c
arduino/wiring_analog.c
arduino/USBCore.cpp
arduino/new.cpp
arduino/Tone.cpp
arduino/WString.cpp
arduino/HardwareSerial1.cpp
arduino/Stream.cpp
arduino/HardwareSerial3.cpp
arduino/HardwareSerial0.cpp
arduino/CDC.cpp
arduino/HardwareSerial2.cpp
arduino/main.cpp
arduino/HID.cpp
arduino/HardwareSerial.cpp
arduino/IPAddress.cpp
arduino/Print.cpp
arduino/WMath.cpp
arduino/abi.cpp
Linking libarduino.a
ros_lib/duration.cpp
ros_lib/time.cpp
Linking libros_lib.a
Linking firmware.elf
Converting to firmware.hex

Why are so many files being included in the compilation, and how do I filter them out?

It's 2015. What is compiled does not always become what is linked.

The Arduino IDE build script will actually copy all core source code file to the tmp directory, compile and generate an archive file. The sketch is compiled and linked with this library. Only the referenced (used) functions and data are linked in the binary.
The size (both program and data) of this blink is somewhat larger than the "standard" blink example but this is due to the publisher-subscriber run-time.
Cheers!
PS: If you google you can find commands to listing what is actually in the generated binary. Here is a starting point.

Part of the compilation process is what is known as garbage collection, which is controlled by the compilation flag -Wl,--gc-sections
This process goes through the compiled program and works out which sections (functions, blocks of read-only data, etc, each in its own section controlled by -ffunction-sections and -fdata-sections IIRC) and works out which are not needed in your compiled program.  It then deletes them.
The problem you have though is not with code or read-only data size, but with static RAM allocation size.  This is global variables and local static variables - things used for stiring data, maybe as serial buffers, etc.  Most of that is probably part of the underlying RTOS that you have elected to use. Which is the problem of using an RTOS to just blink an LED. It could be seen as a task that is beneath the RTOS and is complete overkill. Of course, since you're just testing, that is pretty irrelevant, however, as you add more functionality you will most likely find that the memory footprint doesn't increase much since it's the "background" stuff that of the RTOS that will always be there regardless of what tasks you are performing.


text:
How to install a library for a single project
How do you install an Arduino library so it's only available for a specific project?
Say I have a codebase located at /myproject, and I want to install libraries at /myproject/lib/somelib. I can't find how to make arduino myproject.ino find the libraries under ./lib.
Googling "installing Arduino libraries" only finds me examples of installing libraries globally (and through the GUI no less), which is horrible practice and guarantees version conflicts.
When I used ino, it supported a local ./lib directory, but I can't find any equivalent feature in arduino.

I don't think you can "install a library for a single project". A workaround is to simply copy all the header and source files of the library into the sketch folder, as if they were other source files.

Doesn't #include lib/somelib/libheader.h work?

@Gerben, Not for me. Arduino only seems to be able to find includes in the current directory or in one of the expected system library paths.

I ended up switching to ano, which supports a local lib directory.

You want to switch to my UECIDE for that functionality. You can then place libraries inside a folder called libraries in your sketch folder.
You also get the benefits of a much improved IDE :)


text:
How to install Arduino IDE on Raspberry Pi
How do you install the Arduino IDE on the Raspberry Pi running an ARM version of Ubuntu or Raspbian? There doesn't seem to be any official ARM release. Both distros have an "arduino" package in their standard repos, but it only includes an ancient 1.0 version that's missing a lot of features.

have you tried downloading the linux 32 bit version it from arduino.cc? what happens?

Yes, I thought that might work too, but it's compiled for the i386 architecture so it gives me an error when I try to run it on the RPi. Apparently, i386 and 32-bit ARM are not compatible.

The IDE is java, so you might just need to replace the avr-gcc stuff with its arm version

The IDE is indeed written in Java, but build with Ant, which results in a not cross-platform startup file. I do think it should be possible compiling Arduino yourself on the rpi. Lookup a tutorial on ant builds on the rpi and clone the sources from the github repository.

Not sure if this will help, but I have it sort of running on Fedora on a Pi, see Arduino IDE on Fedora. I've had a few (path) issues, to which my post will attest, which I am sure are surmountable.

It's included in raspbian. Also in lemakers raspbian for bananapi.

Arduino at http://playground.arduino.cc/Linux/Raspbian recommends:
sudo apt-get update && sudo apt-get install arduino

but indeed warns that the version is old:

Note: This will install an old version of Arduino, and may not support
  some of the newer boards. You can not download a newer version from
  the website, because there is no ARM version. -- Arduino wiki on Raspbian

Looking at the raspbian respository at http://archive.raspbian.org/raspbian/pool/main/a/arduino/ currently lists 1.0.5
There are folks working newer versions of Arduino for ARM at https://github.com/arduino/Arduino/issues/3334 but it isn't finished yet.

why on earth would you like to run on the Pi? It's hideously slow. A ten-year-old intel machine is faster.


text:
ESP 8266 web server using arduino
I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.

"I do not want to use only the ESP" -- you know you can use the Arduino tooling and all with it? Also, "It gets rgb values through URL and changes an rgb led's value" sounds like it's not a web server, but a client?

Yes but I want a lot of pins like an arduino mega

The ESP communicates using the UART, not SPI. It uses modem-like AT commands. Unless you write your own ESP firmware, in which case how it communicates is up to you - and so is the accompanying Arduino library.

So, the spi pins on the ESP are for master? And what libraries are there to use with serial?

Yes, the SPI pins are for use when you write your own firmware for the ESP. There are a number of libraries around for serial - google is your friend. Or you can just do it manually without a library, the protocol is simple enough.

The following link is a great resource for learning how to use the WiFi module.  It has all the commands you are likely to need.  The guide is written with the intent that the user will use the module as a standalone device without the Arduino, but at the end of the guide the commands given are all the same.  This is the reference I use for projects like this.  ESP8622 Quick Start Guide


text:
bi-directional nrf24 communication
The central arduino

The 1st node

The 2nd node

I want the central to send to the first node the rgb code like a string on the loop

"rgb: 255000255"

but when it detects something to PIR to send a string to central.
In addition every some seconds the 2nd node to send a string to the central the temperature.
As i mentioned in my previous questions i have some problems when it comes to the bi-directional comunication. I have tried a lot of code. Can someone show me how to achieve what i want to do if not with code, with steps. Please help me!!

You cannot (easily) have all nodes on the network with the same address.
There are ways of doing it but they aren't easy.  They basically involve creating a "broadcast" facility in your network, and that has certain caveats involved with it.
The nRF24L01 modules have an "auto-ACK" mode to give reliable communications.  This only works with 1:1 addressing and cannot work with broadcast.  If you want to (as most people do) use the auto-ACK facility then you have to have each node with its own unique address.  After all, if you're sending the ACK to a station, and there are multiple stations with that address, which one will ACK?
So you have to think about if what you are trying to achieve is really the right way of going about it.  It sounds like you want to just program another node with the same code as an existing node without making any changes to that code and "just have it work".  That's a very advanced topic and one that even I would spend quite some time implementing it.  Yes, you can do unreliable communications (i.e., no auto-ACK) then you could have all the remote stations with the same address, but I would certainly keep the master as a unique address.  Better would be for each node to start up with a pre-defined address which it then uses to ask the master for a unique address (a-la DHCP) and the master then keeps a list of what is connected on what address.  From then on it can use reliable communications to send and receive data to each node as it needs to.
A system I wrote for the chipKIT boards gives each node two addresses - its own unique address which you have to provide manually, and a more global "broadcast" address.  They are each on different pipes within the nRF24L01.  To communicate with an individual node you send to its unique address.  To broadcast to all nodes you send to the broadcast address.  If you're sending to the unique address you can then turn on auto-ACK. If you're sending to the broadcast address you don't turn on auto-ACK.
Note that using auto-ACK is a whole topic in itself and requires careful design planning to get it to work properly.
Also you have to think about what happens when you send a broadcast packet out and it's received by other nodes - how do they handle that data? Sending temperature data out globally, it will be received by the RGB receiver, which may try and interpret it, causing problems.  You need to come up with a way of identifying just what it is you're sending out and only having the right nodes responding to the right data.  That means coming up with a strict packet format.  Luckily the nRF24L01 chips communicate in fixed packet sizes (incidentally, all nodes on the network will have to be set to use the same packet size or it just won't work) up to 32 bytes, so implementing a packet structure over that is easy enough.  Just sending strings of data is both hard to interpret and incredibly inefficient.  You should be sending the data as actual data values in variables as part of the packet structure.

Try the RF24Network library from maniacbug. If you don't have too many nodes it's easy to use. It comes with examples easy to test and extend. It also uses different channels for sending and receiving so you should have no collisions.

I want all nodes to have the same transmitting address in order to ad more in the future without changing the code. Is that way any solution?


text:
How to use Arduino Uno as PS/2 to USB converter for typical keyboard usages?
I'm beginner in Arduino and recently programmed an Arduino uno board with various PS/2 to USB converters. They work when typing in Serial Monitor of Arduino IDE, but not in the other programs such as Notepad.

How can I connect the board as HID keyboard for usual works with my PS/2 keyboard?
Update:
As @KIIV mentioned in the comments, Uno hasn't native USB and his suggestion is to start with boards such as Leonardo.
I want to ask, what is the straightforward way of using Uno for this purpose?

Start with board with native USB and not UNO with USB-to-serial on different chip. Arduino leonardo for example

please do not post a picture of text ... post the text instead

Thank you @KIIV, great answer! I googled your guide and found that some types of Arduino haven't built-in USB communication. As new question, is any way to work with Uno, as well?

Thank you @jsotola for your hint about site's laws, I'm not so familiar with them. The question and its text has been edited.

I thought I answered this question.  Oh, I did... https://stackoverflow.com/questions/76755556/my-arduino-uno-ps-2-to-usb-works-only-in-serial-monitor-not-in-other-windows-app

I appreciate you @Delta_G, I sent a comment to your answer there.

As the Uno has no generic USB module, it generally works only as a virtual serial device. Without additional hardware you cannot make a Uno work as a USB keyboard. In principle.
A possible solution is the usage of V-USB. This nice library uses bit-banging to realize low-speed USB communication. A USB keyboard commonly is such a low-speed USB device.
Another possible solution is an accompanying software "driver" on the PC. It will receive the key events via the USB serial port and translate them to key events for the operating system. But I'm sure you will not want this.

I learned new things from your answer, @the busybee. Thanks.

@Khabarkhaan You might want to take the [tour] to learn how this site works. For example, you are not supposed to comment "thanks!" but to mark an answer as accepted. This is the best way to help future visitors on the same issue.


text:
Is defining a function improves speed rather computing average for each analog input separately
My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?
My code:
// Samples average
sample_cnt = 1000;

//// Input the pin number and compute average value
float Average_input_value(int analog_pin){
  float avg_val = 0;
  for(int i=0;i<sample_cnt;i++){
    avg_val += analogRead(analog_pin);
  }
  // Divide by Sample count to get the average value
  avg_val = avg_val/sample_cnt;
  return avg_val;
  }

Writing the code out four times, in line, is a little bit faster than calling a function because the function call and return take some time, and the loop instructions take some time, and neither of those contribute to the average calculation.
Writing a function that you use four times, however, is much more readable, is much easier to fix if you've made a mistake because you can fix it once instead of four times, and is much easier to change or replace for the same reason, if that ever becomes necessary. Besides, a good optimizing compiler can often decide when to rewrite your loop as inline several repetitions of the loop contents (called "unrolling the loop"), so hand optimizing is probably not worthwhile.
Where your function will win over 4 repetitions of the calculation code is in the code-space needed. The function is more compact, but slightly slower.

Just adding some numbers to complement JRobert's answer.
On the Uno, the cost of calling a function and returning from it is
about 0.5 µs. In contrast, calling analogRead() within a loop
costs at least 112 µs per iteration. Given that you are computing
the sum as a float (where a suitably sized integer would suffice), it
may well be more that 112 µs in your case.
I do not know how many readings you want to average, but even if it is
only a handful, the calls to analogRead() will completely dwarf the
cost of using a function.

Thank you very much for your response. I have decided to use the function approach for averaging. Right now I am using a1000 sample count for averaging. Interesting to know that calling an analogRead() actually takes 1000 times more time in the loop than in the function.


text:
Why does the MKR WiFi 1010 LED_BUILTIN sometimes pulsate?
Sometimes the built-in LED pulsates after an upload. It could be after a failed upload but I'm not entirely sure. What does this indicate? I haven't been able to find any information about it.
It doesn't blink like in the Bliky example. It pulsates.
The led is not controlled by a Sketch. Usually this happens after a failed upload, and the previous Sketch doesn't work anymore.

maybe it is the sketch that you loaded

@jsotola Usually it's after a failed update, and my best guess is that it is, but I haven't seen it documented anywhere. It's not in the sketch.

bootloader does it while active


text:
Reading MAX31888 works with Nano, but not with ATtiny85
I'm using the OneWire library to try and read temperatures from a MAX31888 sensor using this Arduino program:
#include <SoftwareSerial.h>
#include <OneWire.h>

#define RX PB4
#define TX PB3
#define OW PB0

SoftwareSerial serial(RX, TX);
OneWire ds(OW);

void setup() {
  serial.begin(19200);
  delay(1000);
  serial.println("TX_INIT");
}

void loop() {
  byte addr[8];
  if (!ds.search(addr)) {
    serial.println("No more addresses.");
    serial.println();
    ds.reset_search();
    delay(250);
    return;
  }
  serial.print("ROM =");
  for (byte i = 0; i < 8; i++) {
    serial.write(' ');
    serial.print(addr[i], HEX);
  }
  delay(5E3);
}

When I test this on an Arduino Nano, with hardware serial instead of software, I get the output I expect:
ROM = 54 36 25 5 0 0 0 3C
No more addresses.

But when I compile and burn the same program to an Attiny85, using the internal 8 MHz clock bootloader, all I get is:
No more addresses.

What could be the issue here? I've read DS18B20 sensors just fine with the 8 MHz internal clock bootloader before.
Software & library versions used:

Arduino IDE ver. 2.2.1
Arduino AVR Boards core for Nano, ver. 1.8.6
ATTiny core ver. 1.0.2
Onewire library ver. 2.3.7

Wiring diagram for ATTiny setup:

Diagram legend:

U1: USB
U2: ATTiny85
U3: MCP2221
J1: OneWire header

Please note that the VUSB pin of the MCP2221 outputs a regulated 3.3V.

If your code shown also doesn't work as shown with a DS18B20 you're likely to get more help. The name and version of the Arduino core in use would help. Same for OneWire, there is not just one of these now, and there are forks of all of them. Same of SoftwareSerial assuming it isn't just part of the core you're using.

@timemage I've added version numbers and sources to my initial post for applicable software and library versions. SoftSerial is indeed part of the core in this case. The DS18B20's work just fine with this on both ATTiny and Nano, the same code reports the DS18B20's ROM just fine on both. But only the Nano reports the MAX31888 ROM, and not the ATTiny for some reason. Response on DS18B20: ROM = 28 AD 45 73 E 0 0 E7 No more addresses. Which seems to be correct, since the family code for DS18B20 is 0x28.

It looks like you have good details now.  Unfortunately I don't believe I have a MAX31888 to test with.  But, I'm voting it up. That is appears to top out at 3.6V makes me wonder how you've been wiring it.

@timemage Both on the ATTiny and Nano, I use 3.3V for powering the sensor. Though both microcontrollers are powered off of 5V from USB. On the Nano I use the 3.3V regulated output and on the nano I have a separate regulator for 3.3V

Does it work if you also use SoftwareSerial on the Nano?

@EdgarBonet I can try, I don't see how that would change anything since I get a serial response with SoftSerial on ATTiny when using a DS18B20, and also a failure message when either nothing, or a MAX31888 is connected.

@EdgarBonet SoftSerial works fine on Nano


text:
How can i reduce my global variable use? Attiny85
I'm trying to compile my code but i keep exceeding my global variable memory by 12%.
Is there anything i can do in my code to further reduce RAM usage?
Or do i have to do modifications to the libraries I'm using?
Here is my main program:
    #include <MIDI.h>
#include <FastLED.h>
#include <SoftwareSerial.h>

#define LED_PIN 3
#define NUM_LEDS 60
#define LEDMAP 0xAB5AB5AB5AB5AB5
#define OFFSET 36
#define RANGECHECK if (pitch > 35 && pitch < 96)

SoftwareSerial softSerial(2, 4);
CRGB leds[NUM_LEDS];

MIDI_CREATE_INSTANCE(SoftwareSerial, softSerial, midiB);

void setup() {
  FastLED.addLeds<WS2811, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.clear(true);
  midiB.begin(MIDI_CHANNEL_OMNI);
  midiB.setHandleNoteOn(HandleOn);
  midiB.setHandleNoteOff(HandleOff);
}

void loop() {
  midiB.read();
}

void HandleOn(byte channel, byte pitch, byte velocity)
{
  RANGECHECK
  {
    leds[pitch - OFFSET] = bitRead(LEDMAP, (pitch - OFFSET)) ? CRGB::NavajoWhite : CRGB::Salmon;
    FastLED.show();
  }
}

void HandleOff(byte channel, byte pitch, byte velocity)
{
  RANGECHECK
  {
    leds[pitch - OFFSET] = CRGB::Black;
    FastLED.show();
  }
}

I've reached my limit in optimizing my RAM usage here. Any suggestions for optimizing my code would be appreciated.

Since i don't use sysex messages, i got my RAM usage down to 84% by setting the SysExMaxSize
in midi_settings.h
to 0.

FastLED needs to keep the colors of all the pixel in RAM, so that is using a lot of RAM.
To get around this, you could use a strategy that generates the pixel data on the fly as you send it out to the strings. Here is an example of a project that does that...
https://wp.josh.com/2021/04/21/build-a-live-scrolling-tickertape/
Also, SoftSerial keeps a buffer (looks like 64 bytes?) which also uses some RAM. You could use a different approach to serial communications that does not allocate such a large buffer. It would take work, but you could even process the midi bytes as they were received and not need any byte buffer.

I already tried redefining _SS_MAX_RX_BUFF in my code, but this had no effect on the global variables used


text:
Switch power of PN532 on and off from ESP32?
I have a strange issue with PN532, by some reason it is not every time recognized, and it turns out that if I switch Off and On the power - it goes recognised , but I am trying no to switch the whole board, so I wonder if I use a transistor to make this switch - like BD139 will it cause some issue, or if there is a better solution ?
Here the circuit I am wondering about :

P.S. I have this board :

Before you get too far down this track you should try the PN532's powerdown/reset signal.

hey @timemage. Well.. How to do that ?

To know that the signal is even exposed on your board, we'd need to know which exact breakout you have, which might also inform other useful answers. You're asking about this circuit where you're try to control the PN532's GND which will have nothing to do with a prospective answer about RESET, again, assuming that's even possible. The NPN circuit itself is perhaps more ESE material. So, I'm not sure how you want to proceed. I'd give details on the breakout your using, code you're using, and how it's wired.

@timemage I jut added the board i have. I am using SPI. ( SCK / MISO / MOSI / SS ).

I've research on the net, and seems like this stall of the board is something common, which caused a lot of projects to fail.

There is a hardware Reset and Power-Down pin on pin38 of the chip, turn your board upside down and you will see a pin RSTPDN or something like that. Read about on-board LDO on page 85 and Hard Power-Down mode on page 91 of the datasheet to get to know more.

Mine has a slightly different silkscreen, otherwise the same. I'd have liked to try their code and wiring scheme to replicate the problem to see that it actually solves it, but that hasn't materialized. Going to be away form the normal setup for a couple of days anyway now. If the code and wiring does show up, someone may answer with something completely different with the new information or be able to actually test your problem.

@YordanYanakiev, are you able to share your code?

I beieve this is the schematic for the PN532 Module shown in the photo https://www.elechouse.com/elechouse/images/product/PN532_module_V3/PN532_shematic_drowing.pdf

Looking now at the datasheet you've posted i realised that both SPI and I2C is marked 5V, while I am powering it from 3.3V ( as it is shown in most examples ) Could this cause the issue?

The manual for the (similar) module from Elechouse suggests it’s voltage tolerant. https://www.elechouse.com/elechouse/images/product/PN532_module_V3/PN532_%20Manual_V3.pdf

therefore this should not be an issue..

Hi @YordanYanakiev are you able to share your code and wiring setup? It would be interesting to see if the module recognition problem can be replicated. There may be a more elegant solution, but if power cycling using the RSTPD_N pin is the way forward suggestions can be made that fit with your code.

hey @RowanP sure. asap as i return from holydays will do.


text:
How to connect an Output to a Pullup Input of another arduino
:tldr; Could problems occur if one connects a HIGH Output of one arduino to a PULLUP_INPUT of another while using differed power sources?
Hi I'm building some devices for a LARP Dungeon (think Escape room).
For that we have interfaces, riddles and switches(triggers).
Interfaces provide access to sound/light/DMX sytems for riddles.
Riddles check conditions and send state information to the interfaces.
To keep things simple, states are boolean (like riddle is solved, a critical mistake has been made,..)
I would like to use PULLUP_INPUTs on the receiving end so I can use simple switches to GND as controls. In some cases a switch might be connected directly to an interface. Mostly there is a riddle in-between. In those cases an OUTPUT of the riddle's Arduino will be connected to the PULLUP_INPUT of the Interface's Arduino. There will be multiple riddle Arduinos connected to one or even multiple Interfaces.
Due to cable length, differed power sources etc. the potential to GND of the involved Arduinos might be differed. So I assume this difference will flow over the pullup resistor of the interfaces into their 5V. The internal PULLUP is ~20kOhms so current should not be a problem but can the voltage, which might be a little higher than the one of the input, cause problems?
Or would it be better to set the Output of a riddle Arduino to INPUT while the signal line should be HIGH so it gets a high impedance? Switching between: OUTPUT:LOW while active and INPUT while inactive.

If a voltage higher than Vcc is applied to a pin, current will barely flow through the pullup but through protection diodes...

Thanks! That should resolve my concerns.

I might have been unclear: that is actually a bad thing. Those clamping diodes are meant to protect IOs from transients, not from a persistent overvoltage. Applying a constant voltage of typ. 0.5V above Vcc can destroy the GPIO... but it is only relevant if the two devices have different Vcc.

Connecting any signal that is within the voltage range of the receiving Arduino is safe. So if you use Arduino UNOs or similar with a 5V operating level, you can connect any signal between 0 and 5V to an input. It does not matter whether the input is in pull-up-mode or not. So connecting an output to an input of another Arduino (or even of the same Arduino) is safe. In addition to the signal values, you do need to connect the ground of both Arduinos.
The only thing you must not do is connect two outputs together (because if one of them is high and the other is low, you have a shortcut that will potentially fry one or both of the boards). And you would need to be careful if you used different types of Arduinos, like a Uno and a Due, because they run at different voltage levels.

All correct, but also note: The two MCUs need the same reference, but they have separate power sources, so you also'll need to connect their grounds together.

True, added that.

Yes all GNDs are connected as well. From my understanding a IO-Pin which is set to INPUT_PULLUP is connected via a internal resistor to the 5V-Pin of its Arduino. An OUTPUT is directly connected to 5VPin when HIGH. Depending on the load and accuracy of each linear converter the real voltage between 5V-Pin and GND might be different for each Arduino. I have read that this voltage is critical for any Arduino and must not change. Load on any Arduino may change. So I fear that current might go back into the INPUT_PULLUP. I guess the difference will be <100mV.. Maybe I'm over thinking this.

@KarlSanathos: The internal resistor that is used to create the pull-up is large enough that whatever current you attempt to draw from it is small enough not to cause any harm. The voltage on an input pins is absolutely not critical, as long as it is not significantly above 5V. If it is around 2.5V, the input reading might be random, but still this won't break anything.


text:
How to combine Read/Write Data Code for RFID tag?
I have the two example codes from MFRC522 Library and I want to combine them together so I can at first read the data from the tag and then write something new on it by using the serial input. I´ve already tried but I cant figure out why it doesnt work. While it waits for an input to write on the chip the Serial Monitor shows: "PCD_Authenticate() failed: Timeout in communication".
This is the code for read data:
* Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read
}

//*****************************************************************************************//
void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.println(F("**Card Detected:**"));

  //-------------------------------------------

  mfrc522.PICC_DumpDetailsToSerial(&(mfrc522.uid)); //dump some details about the card

  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));      //uncomment this to see all blocks in hex

  //-------------------------------------------

  Serial.print(F("Name: "));

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i] );
  }

  //----------------------------------------

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//

and for writing data:
/*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.print(F("Card UID:"));    //Dump UID
  for (byte i = 0; i < mfrc522.uid.size; i++) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
  }
  Serial.print(F(" PICC type: "));   // Dump PICC type
  MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  Serial.println(mfrc522.PICC_GetTypeName(piccType));

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Type Family name, ending with #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 2;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  // Ask personal data: First name
  Serial.println(F("Type First name, ending with #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
  for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

  block = 4;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 5;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  Serial.println(" ");
  mfrc522.PICC_HaltA(); // Halt PICC
  mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

}


text:
How do I recreate the Pong game with two pots and the map function?
I am working on a project for my brothers and anyone else who is interested in playing some LED Pong. I was just stuck on the software part. I don't really know what to do. But, I have an idea: I want to use the map() function to make my life easier, however, I am not sure how to use the map function with the Dot Matrix. All help would be appreciated. All of the stuff came in this kit.
Here is the test code:
#include <LedControl.h>

int DIN = 2;
int CS =  3;
int CLK = 4;

const int playerOnePin = A0;
const int playerTwoPin = A1;

int playerOneValue;
int playerOneValue2;
int playerTwoValue;
int playerTwoValue2;

LedControl lc = LedControl(DIN, CLK, CS, 0);

void setup() {

  lc.shutdown(0, false);      //The MAX72XX is in power-saving mode on startup
  lc.setIntensity(0, 15);      // Set the brightness to maximum value
  lc.clearDisplay(0);          // and clear the display

  pinMode(playerOnePin, INPUT);
  pinMode(playerTwoPin, INPUT);

}

void loop() {

  byte a[8] = {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  printByte(a);

}

void printByte(byte character []) {

  int i = 0;
  for (i = 0; i < 8; i++)
  {
    lc.setRow(0, i, character[i]);
  }
}

void readPot() {

  playerOneValue = analogRead(A0);

  playerOneValue2 = map(playerOneValue, 0, 1023, 0, 180);
}

Here is the other code:
#include <LedControl.h>

int DIN = 2;
int CS =  3;
int CLK = 4;

byte displayImage[8] =     {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// considering a 2d co-ordinate system with origin (0,0) at bottom left corner
int ballX = 3; //X position
int ballY = 7; //Y position - top
int speedX = 0; // no X movement, can be -1, 0 or 1
int speedY = -1; // downward Y movement, can be -1, 0 or 1
int paddleX = 4; // X position of center of paddle - can be 1 to 6. Paddle width is 3
int score = 0;

LedControl lc = LedControl(DIN, CLK, CS, 0);

void setup() {
  pinMode (A0, INPUT);
  pinMode (A1, INPUT);
  lc.shutdown(0, false);      // Keep MAX72XX awake
  lc.setIntensity(0, 15);     // Set the brightness to maximum value
  lc.clearDisplay(0);         // and clear the display
}

void loop() {
  // update ball position
  ballX = ballX + speedX;
  ballY = ballY + speedY;

  // check for ball interaction with walls
  if (ballX == 0 || ballX == 7) {
    speedX = speedX * -1; // bouncing off walls in horizontal direction
  }

  // bouncing off ceiling
  if (ballY == 7) {
    speedY = speedY * -1; // bouncing off the ceiling
  }

  // bouncing off the paddle
  if (ballY == 0 && ballX >= (paddleX - 1) && ballX <= (paddleX + 1)) {
    speedY = speedY * -1;
    score++;    // player earns a point
  }

  // going past the paddle
  if (ballY == 0 && ballX < (paddleX - 1) && ballX > (paddleX + 1)) {
    // going past the paddle - player is out
    Serial.println(); Serial.print("Score: "); Serial.println(score);
    for (int i = 0; i < 8; i++) {
      displayImage[i] = 0x00;
    }
    displayImage[3] = 0xFF; displayImage[4] = 0xFF; // show a line
    renderByte(displayImage);
    while (1); // Freeze
  }
  // clearing the image variable
  for (int i = 0; i < 8; i++) {
    displayImage[i] = 0x00;
  }

  // generating new image
  addPixel(ballX, ballY); // adding the ball position to image
  addPixel(paddleX - 1, 0); addPixel(paddleX, 0); addPixel(paddleX + 1, 0);
  // adding paddle position to image
  renderByte(displayImage); // show the generated image

  // handling paddle control
  if (analogRead(A0) && paddleX > 0) {
    paddleX = paddleX - 1; // move paddle left
  }

  if (analogRead(A1) && paddleX < 7) {
    paddleX = paddleX + 1; // move paddle right
  }

  delay(200);
}

void addPixel(int xVal, int yVal) {
  int newRowval = 2 ^ (7 - xVal);
  int rowVal = displayImage[7 - yVal];
  displayImage[7 - yVal] = rowVal || newRowval;  // inserting a 1 at the required pixel
}

void renderByte(byte image [])
{
  int i = 0;
  for (i = 0; i < 8; i++)
  {
    lc.setRow(0, i, image[i]);
  }
}

Here is the picture of the wiring and the schematic:

Your ball will either go straight or diagonally at 45° ?

Yes, the ball will go straight, I don't know about  the diagonally part, but it won't move the paddle.

First figure out the min and max values that paddleX can have.  I assume if the paddle is two dots wide then its min,max will be 0,6   Then figure out the min and max of your pot, typically 0,1023 for a a 10 bit adc.  Now to map your pot value to paddleX value you'd use the command :
paddleX = map(analogRead(A0),0,1023,0,6);

here is the map documentation : https://www.arduino.cc/reference/en/language/functions/math/map/

For an evenly spaced mapping paddleX = map(analogRead(A0),0,1024,0,7); would provide better results. ( Integer division truncates )

Yes, the paddle is two dots wide.

I don't really know what to do from there.