text:
The IDE says my (brand new) Arduino UNO is on COM 1
I recently bought an Arduino Uno and installed everything necessary. I tried it on both USB ports on my computer. However, the Ports menu only shows COM1. There is a line on the bottom of the IDE which says Arduino Uno on COM1.
Any program I try fails to upload to the board. When I tried the Blink example, the following error message appeared:
Arduino: 1.6.3 (Windows 7), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for
local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x43

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x43

and so on. Until,
This report would have more information with
"Show verbose output during compilation" enabled in File > Preferences.

I have a Windows 7 64 bit desktop.
Any help will be appreciated.

Can you try pressing the reset (hardware on arduino) button directly after pressing the upload button (software in IDE)? - I had this problem on a cheap Nano clone, using the wrong programmer type

It does not seem to be making any difference. Is there something else you think I ought to do?

I read in many places that the Arduino UNO is supposed to be on COM 3 or higher. How do I do that? It always says I'm on COM1. Thanks again.

Can you find the arduino in Windows - Device Manager?

@FuaZe -  No, I cannot.

Could you attach a screenshot of your device manager? There might be an issue with the drivers, might also check the error in google, that's how I fixed mine

its possible that your COM1 device has nothing to do with the arduino and is some other device on your computer, and that your arduino is not being recognized at all. The "Arduino uno on COM*" line reflects your settings, not anything the IDE has detected about the available ports.

@SR1 - which port the Arduino will be on depends entirely on the details of your system.  There is no rule.  On a system with no other serial devices, COM1 is a legitimate possibility.

@SR1 could you indicate what solved your problem, maybe add it yourself as an answer to your question

@Joram - Turns out my USB cable was faulty. While the green light still turned on, the computer did not recognize the Arduino Uno R3. I installed some of the FTDI USB drivers and used a different cable, and it worked!

Here are a few troubleshooting tips:

First check if the board is listed as Arduino Uno in the IDE by going to Tools --> Board
Check this site.
Also, try reinstalling the driver.
Check your cable.
As a last resort you can try re uploading the bootloader.


text:
Powering a 5V Arduino Pro Mini with 3.3V
I want to run the 5V board at 3.3V because I can get the 5V version cheaper than the 3.3V version.
I read that you can power the Arduino Pro Mini with a battery by connecting the battery to the 5V pin, bypassing the regulator.
Somewhere else I read that the only difference between a 3.3V and 5V Pro Mini is the regulator.
Are these assumptions correct? If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

The 3.3v version runs at a slower speed (reason). Note that some voltage regulators don't like it when the have a higher voltage at the output, than on the input. One went up in smoke on some other board I have. Just desoldered it, as I didn't need it. Other than that, no problem.

I just discovered that I knew the answer to this, because I was accidentally running some 5v/16MHz Pro Mini boards at 3.3v without issue.
Short Version
Yes, you can run one feeding it 3.3v, but you need to program it as a 5v/16MHz board to get the clock speeds right.  Also, all your TTL levels (outputs) will be 3.3v, not 5v.  Additionally, at least in my experience, the processor will run at 16MHz and not 12MHz with 3.3v.
Background Story
I had some generic Pro Mini boards that didn't mark their voltage at all, so I tried programming (and running) them using my FTDI at 3.3v using the 3.3v/8mHz option in the Arduino IDE.  I was able to upload programs just fine, but the clock was clearly wrong, as the "Blink" program ran about 2x as fast.  That told me that it was running faster than 8MHz .
So I tried again this time telling the IDE it was a 5v/16MHz chip, and everything ran fine, despite the fact that I was feeding it 3.3v.  I even saw that pin 13 was cycling from 0v up to 3.3v - exactly what I was feeding it.  So for a while I just thought they were 3.3v Pro Minis.
But then thinking about it, I realized that having to tell it to run at 16MHz to get the clock right meant it really was a 16MHz chip - which I didn't think was available with the 3.3v model.
So on a whim (and since I have a ton of these little boards), I changed my FTDI to 5V, and was able to run and program the board just fine.
So from that, I conclude that yes, you can run them at 3.3v, but your TTL levels will be just 3.3v.

Pro Mini 5V has voltage regulator for 5V and 16MHz quartz.
Pro Mini 3.3V has voltage regulator for 3.3V and 12MHz quartz.
According to manufacturer specification Atmega328 chip powered by 3.3V cannot run 16MHz and needs at most about 13MHz. But it's official specification. Some chips are better than specification (faster) some are worse (slower). So you can try whether your Pro Mini is better or not. Or you can change quartz to 12MHz, if you can solder SMD parts.
Or better look for cheaper 3.3V clone, they are not much more expensive as 5V version...

You could also temporarily hook up ISP and use that to set the fuses for an internal 8 MHz, ignoring the crystal.

All the Pro Mini 3.3V's that I've seen run at 8MHz. But you are correct that about 12MHz is the official maximum frequency for the Atmega328 at 3.3V.

I just ran a generic (eBay special) 5v Pro Mini with 3.3v, and saw that it does still run at 16mHz.  I based this on using 1 sec "Blink" program and putting it on an oscilloscope.  So as mentioned above, test it first - it may run at 3.3v and 16mHz just fine.  I outlined some details of this in an answer below.

Im feeding 5V pro mini clone with 2 AA battery, to VCC pin, about 3V and it works normally. It consumes few current compared to 5V.
And you can see what it the setup in here.
Also this video can be useful.

You should feed the battery to the Vcc pin, and not Raw. Raw goes thru the regulator, Vcc will bypass it.  The same 328P chip is used on both 5V and 3.3V boards, the difference is the Resonator (16 MHz vs 8 MHz) and the regulator (5V vs 3.3V).       Running a 16 MHz board at 3 or 3.3V is running it out of spec, you may see some odd behavior, the Arduino forum has seen cases where Serial did work correctly at lower voltages.

Its on VCC already sorry. I don't use Serial function. I read DHT22 and use i2c oled without a problem.

So, just change the fuses to use internal 8 MHz oscillator, and you're within specs, right?

First I am going to say it is very much possible. Allow me to explain.
The 5v version can be powered with 3.3v, but it is not recommended to supply power through the 5v pin, bypassing the regulator. Only regulated 5v power should be supplied through the 5v pin. Any other voltage levels should go in the RAW pin. If you supply the Arduino Pro Mini 5b with 3.3v the chip will only be underclocked to 8-12MHz, and the voltage for Vcc (the board's operating voltage and what it will power its pins with) will be 3.3v; but there is another way.
I primarily source my components from SparkFun due to their reliability, cheap price and awesome support. They provide the Arduino Pro Mini in 3.3v and 5v variants for only $10. I have used both variants for many purposes, but primarily when working with embedded and small solutions. One of those times I was accessing sensors that ran on 5v TTL logic, but I didn't have room to place a >5v battery, only room for a LiPo (which generally powers 3.3v).
I was able to solve this issue with a SparkFun 5v Step-Up Breakout*, which boosts the voltage to 5v without any other major issues. I should warn you that there are some issues you could face if you are using a LiPo to feed into the Step-Up. Even if you aren't I'll list it here for reference. The Step-Up's maximum safe input voltage is 4v, and can be a bit unreliable if the voltage goes above it. Unfortunately a LiPo's discharge curve places it above 4v when it is within the upper 95% soc (state-of-charge), so a 3.3v regulator (which SparkFun also sells) would be needed to reliably power an Arduino Pro Mini 5v through a Step-Up breakout (at least in my experience). Also, power from a Step-Up breakout is regulated.
*Pololu also sells a comparable Step-Up that could handle an input up to 5.5v in theory, but I haven't personally used it.

If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

two options (at least):
1) apply 3.3v at the regulator output pin. there may be already a break-out for that on the board;
2) solder in a 3.3v regulator in place of the 5v regulator -> fairly easy to do as well.

source: Stack Exchange

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

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

sort: votes


text:
Interfacing a CCTV camera (AV output) with Arduino Uno
I have to use a camera to take picture in my major project. I want to use this camera, which has AV output. Please tell me how to interface this camera with my Arduino Uno and use the data from camera and send it to my PC using a Wi-fi Module?
P.S. Please do not suggest me to use wireless camera because firstly they are expensive and secondly I require a board in my project anyway.

Unfortunately, I have to tell you that a UNO isn't enough powerful to work with any type of camera: it hasn't got enough ram and processing power to elaborate your camera's data. (see atmega328P's specs)
I'm not sure you can work with that camera, unless it is digital and has integrated RAM to keep the frames.
A good project which I suggest you to see is arducam.

Can you suggest me any camera to work with UNO?

In the answer I linked you arducam

yeah, I saw that but arducam are not low cost and are not widely available in India. Can you check this blog and tell me the possibilities of it's happening. Thank you

Can you give a link to the camera you want ot use? I need more of a photo.
Also, I have read the guide on Adafruit that you have linked, and it might work but from what I have read to take a photo it takes over two thousand milliseconds, so it isn't very fast

Camera I want to use.

Unfortunately that's analogic, I don't know how to use it.

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


text:
How best to power down an Arduino for ~5 minutes at a time?
Reading over the datasheet it appears the longest it can shutdown for is 8s so should I just keep a counter in the loop method that checks if it's run 38 times and then execute the code I want? Would this wakeup every 8s hurt battery life much if it's doing nothing but incrementing a counter?

Yes, if you want to wake an ATMEGA (the chip in the Arduino) spontaneously (no outside trigger) from Power Down mode at periodic intervals, the you will need to rely on an interrupt generated by the watchdog timer, which has a maxim timeout of 8s.
Your goal should be to wake, increment and check the timer, and get back to sleep as quickly as possible since the amount of time you are awake will dominate your average power usage while asleep.
Some things to keep in mind...

The arduino uses a power regulator which always draws current. If you are going for long battery life, you will need to replace or eliminate this regulator. Much better to have an ATMEGA connected directly to a battery.
Turn off as much of the chip as possible before going to sleep. Take a look at the power control registers.
Make sure you are not driving any unnecessary loads with the GPIO pins when sleeping.

BTW, common wisdom has been that it is best to wake up and run at as fast a clock speed as possible to get your work done and get back to sleep as quickly as possible. However, Jack Ganssle recently published an article that makes a great case for doing the opposite. You will actually get longer battery life if you wake up to a slow clock speed, since this means you can run down the battery to lower voltage (this assumes you don'y need higher voltages for some other part of your circuit). Lots of other great info for designing long running battery-powered systems here...
http://www.ganssle.com/tem/tem275.html
Here is another relevant article about long running Arduinos...
http://www.openhomeautomation.net/arduino-battery/

Looks like you've got some great answers already. For a great deal more info and details on the matter, check out what Nick Gammon has written here too: http://www.gammon.com.au/forum/?id=11497 - Power saving techniques for microprocessors


text:
Analog Input not going zero
Arduino Uno user here
I am building a project with 4 analog inputs A0 dose not work. A1 A2 and A3 work perfectly fine! But for last input when I connect to A4 or A5, then they do not go to zero. They are stuck between 400 to 900. Even when connected to arduino ground it gives 400 instead of 0.
Am I missing something here cause the circuit for A4 connected to A3 gives perfect input value. They both work fine as output.  Same situation with A5.
Is there another way to get one more Analog Input without multiplex?
Thank you!


text:
GSM shield for Arduino Due
Is there any good quality GSM shield compatible with Arduino Due?
I have searched for gsm shield but it seems all shields have operation voltage 5v.
Any suggestion would be helpful.

Most GSM modules have native I/O at 3.3v or even lower (2.8v is common), so you would be looking for one that either didn't have level shifters, or had level shifters to a configurable voltage.


text:
Serial communication problem NodeMCU
this is my first post here. Before I ask you my problem, I'm sorry if I'm wrong to write but my English is bad.
So, my problem is this: I'm developing a "client-server" system with serial communication between my computer and the NodeMCU. The PC will send a message (an integer) to the Node which makes certain things based on the number. At the end of the work the Node will send an ACK to the server (an integer).
I programmed the NodeMCU using the Arduino tool and in the first preliminary tests everything worked: the Node received and answered correctly. Then I wrote a script in Python to automate the thing and that's where the problems start. Communication takes place correctly but the messages that the Node sends to the PC are dirty. At the beginning of the buffer there are some illegible bits while at the end of the buffer there is the correct message. I did the same test with the Arduino Uno and this works perfectly.
Can you give me a reason for this problem and in case a solution?
Thanks in advance!

NodeMCU:
void setup( )
    {
        Serial.begin( 9600 );
        while ( !Serial );
    }

void loop( )
    {
        if( Serial )
            {
                Serial.write( (int)12 );
            }
    }

Python:
#!/usr/bin/python
import serial

port = '/dev/cu.wchusbserial1420'

ard = serial.Serial(port,9600,timeout=5)

x = ard.read(1)
x = int( x )

print x

(I am attaching some screenshots)

post your code as text, not pictures.

Try ard.flushInput() instead of ard.flush()

what about a number >255? hows that work?

Opening the serial port might cause a reset of the NodeMCU through the DTR/RTS pins. You might want to wait a second after opening, then read and flush all the input on the COM port and then start reading.

Use x = ord(x) instead of x = int( x ). ord() converts character to it's DEC value. 'int() ` converts only number characters to number.

try Serial.println(String(x)); to format it for consumption by your python parser. It has more overhead than raw multi-byte binary values, but will work on any int.

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


text:
Ultrasonic sensor underwater calibration
Does anyone knows how to calibrate AJ-SR04M using the Arduino? I am working on AUV. underwater reading from current code; it is giving continuous 20cm while moving inches. http://shop2.hanjindata1.cafe24.com/product/aj-sr04m-ultrasonic-ranging-module/206/

what is the speed of sound in air? ...... what is the speed of sound in water?

have you tested the sensor in air?

Tested on both. Air was giving me correct results as by using scale but underwater around20cm only despite displacement.

the short answer is, that the minimum measurable distance in water with this sensor is 1 m as sempaiscuba explains in his answer

this sensor do not work underwater is only waterproof.

If I understand your question correctly, your problem is probably that the working range of the AJ-SR04M sensor is 20cm - 500cm.
The sensor uses the same transducer to create the sound pulse and to listen for the echo.  It needs time to switch from one mode to the other, which explains why your sensor can't measure distances of less than 20cm.

The speed-of-sound in water is about 5x the speed of sound in air.  More specifically, at 20 degrees Celsius the speed-of-sound in air is approximately 343 meters per second, while the speed-of-sound in water is approximately 1482 meters per second.
This will cause the sensor to 'under-report' the distance in water.  The minimum distance will also be approximately 5x the minimum distance in air.

As an aside, you will also need to make allowance for the differences in the characteristic impedance and absorption between sound and water.
It's worth reading the paper Underwater Sound by P. Vigoureux (Proceedings of the Royal Society of London. Series B, Biological Sciences, Vol. 152, No. 946) for a discussion of all the factors involved.

and sound travels much faster in water

@Juraj Yes, I was trying to edit the answer to include accurate numbers & a reference.  Not easy on a mobile phone, and even less easy now that the Android SE app is no longer working.


text:
Measure voltage changes with unknown baseline
I would like to monitor an audio stream and detect when it is "active" and music is playing or when it is "inactive" and is silent. What is a good way to measure when an audio stream changes state and continues to be "active?"
Each audio stream is amplified with this circuit.
Each audio stream has a different baseline voltage when it is not playing and "silent", but that voltage tends to drift slightly and change. This may be an artifact of my amp. I don't have an OScope and my multimeter is rubbish for low voltage so I can't quite pin down where the drift is coming from.
Currently, I'm using the method shown below, but that isn't as effectivewhen the audio stream is loud (e.g. has a compressed dynamic range).
Also, low volume tracks (e.g. classical music) tends have too low of a dynamic range to measure accurately and I get a lot of false "off" states.
#include <elapsedMillis.h>    //measure elapsed time

const int analogInPin = A0;   //Analog input pin - reads from amplifyer circuit
const int statusLight = 10;   //Digital output pin for indicator light
int sensorValueA = 0;         //Sensor reading now
int sensorValueB = 0;         //Previous sensor reading
int sensorDeltaA = 0;          //Change in sensor reading
int sensorDeltaB = 0;          //Record the last delta - useful for prefenting accidental triggering on start
int sensorThreshold = 50;      //Threshold in delta to trigger action
elapsedMillis turnOverTime;   //Timer for measuring the turnover between changes in sensor reading

void loop() {
  //measure the analog input
  sensorValueA = analogRead(analogInPin);
  sensorDeltaA = abs(sensorValueA - sensorValueB);

 //check if the data is over the threshold and switch on
  if ((sensorDeltaA >= sensorThreshold) and (sensorDeltaB != 0)) {
    turnOverTime = 0;
    powerStateA = true;
  }

  sensorValueB = sensorValueA;

  //check if no sensor data beyond the threshold has been returned within the delay window, switch off
  if (turnOverTime >= delayTime) {
    turnOverTime = 0;
    powerStateA = false;
  }

  //if the powerstate changes act acordingly
  if (powerStateA != powerStateB) {
    digitalWrite(statusLight, powerStateA);
  }
}

Sound like you need to AC couple the signal, and add a few MegaOhms resistor to ground on that.

Where in the circuit would I want to pull to ground? Before or after the amp? And what is an AC couple? I'm pretty new to the audio handling scene and finding out exactly how little I know.

An audio signal consists of two main components:

An AC signal
A DC offset

What you are interested in is the AC signal, but not the DC offset.  That DC offset is what is drifting in your current model.
So you need to AC couple the signal. That is, couple the signal to your Arduino in such a way that only the AC portion gets through.
The simplest way is with a capacitor.
But the Arduino can't handle negative voltages, and an AC signal has negative voltages. So you need to get rid of them.
The simplest way is to add a DC offset.
But didn't we just get rid of a DC offset that we didn't want? Yep. But that was an unknown DC offset. If we then add in a DC offset that we do know, and is stable, then we can work with it.
Here's a very simple circuit:

simulate this circuit – Schematic created using CircuitLab
The capacitor C1 removes the existing DC offset.  R1 and R2 then form a voltage divider giving 2.5V (half of 5V), which is then added to the pure AC signal.
That means that the signal now varies around 2.5V.  Silence is 2.5V, and noise is other values above and below that.
Since 2.5V is half of the 5V the Arduino runs on, silence should read at somewhere near half the ADC value. That's about 512.  Sound will be both above and below that value.
So if you subtract 512 from your analog reading you will effectively be subtracting the DC offset you just added, giving you a value that can be either positive or negative.
For simplicity, since you don't care whether it's positive or negative, you can then remove the sign from the number to just give you a magnitude.
int audio = analogRead(A0); // Get a sample
audio = audio - 512; // Remove DC offset
audio = abs(audio); // Remove sign

You can now compare that to a threshold value:
if (audio > 100) {
    // do something
}

Aren't you making an assumption that the audio signal does not exceed +/- 2.5V? (That may well be a valid assumption).

This answer is exceptionally well described. Thank you! My audio source is coming from the RCA output of a Squeezebox and the headphone jack of a Chromecast Audio. I've measured (poorly, with a junk RadioShack multi meter) the voltage to be well under 1v. Will I need to send the audio stream through an amplifier first before using this circuit?

A standard line level output won't exceed about 1.5v.

If I have two audio sources and I want to measure them independently would this still work? Wouldn't I end up putting two voltage dividers in parallel effectively making each branch of the divider 5K instead of 10K?

No, The dividers are separate entities. Each divider is still a pair of 10K resistors (20K in total). The total resistance across the power supply would halve (10K instead of 20K), but each divider knows nothing at all about that.


text:
Arduino Nano is performing really slowly, even though the calculations are simple and there are no delays
I'm working on a tiny ping-pong game based on Arduino Nano. Its modes are "person vs person" and "person vs computer" (the computer just tries to keep its racket at the same Y position as the ball). There are 2 "up" buttons, 2 "down" buttons, two 7-segment score indicators and 2 shift registers controlling them. The display is SSD1306 (128x32 pixels).
I'm posting here the entire code because I don't know where the issue lies.
#include <Adafruit_SSD1306.h>

// Up/down buttons
#define UP1 2
#define DOWN1 3
#define UP2 4
#define DOWN2 5

// Shift registers that control score indicators
#define DATA1 6
#define CLOCK1 7
#define LATCH1 8
#define DATA2 9
#define CLOCK2 10
#define LATCH2 11

#define RANDOM_NUMBERS A0  // This port isn't connected to anything and is used to get random seed
#define WRAP 118  // Text on display wraps on this position

#define SSD1306_ADDRESS 0x3C  // I2C address of display

Adafruit_SSD1306 ssd1306;

const byte numbers[10] = {  // Arab numbers for score indicators
  0b1111110, 0b0011000, 0b1101101, 0b0111101, 0b0011011, 0b0110111, 0b1110111, 0b0011100, 0b1111111, 0b0111111
};

short currentDirection = -1;
short directionState = -1;  // The sequence number of next move in the period of ball trajectory
short nextMove = -1;
short ballX = 63;
short ballY = 15;
short racket1 = 12;
short racket2 = 12;

short score1 = 0;
short score2 = 0;
bool gameOver = false;

bool playingWithComputer = false;

void setup() {
  pinMode(UP1, INPUT_PULLUP);
  pinMode(DOWN1, INPUT_PULLUP);
  pinMode(UP2, INPUT_PULLUP);
  pinMode(DOWN2, INPUT_PULLUP);
  pinMode(DATA1, OUTPUT);
  pinMode(CLOCK1, OUTPUT);
  pinMode(LATCH1, OUTPUT);
  pinMode(DATA2, OUTPUT);
  pinMode(CLOCK2, OUTPUT);
  pinMode(LATCH2, OUTPUT);

  randomSeed(analogRead(RANDOM_NUMBERS));

  updateScores();

  ssd1306.begin(SSD1306_SWITCHCAPVCC, SSD1306_ADDRESS);
  ssd1306.display();
  delay(2000);  // A delay to show the Adafruit logo
  ssd1306.clearDisplay();

  ssd1306.setTextSize(1);
  ssd1306.setTextColor(WHITE);
  ssd1306.setCursor(0, 0);  // Cursor should be at this position to draw objects correctly

  printLongText(5, 0, "Press \"up\" to play with computer, otherwise press \"down\"");

  while (true) {
    if (!digitalRead(UP1) || !digitalRead(UP2)) {  // Both "up" buttons (as well as both "down" ones) are treated the same unless there's a game "person vs person"
      playingWithComputer = true;
      break;
    }
    if (!digitalRead(DOWN1) || !digitalRead(DOWN2)) break;

    delay(5);  // This delay is here to avoid overloading the processor
  }

  ssd1306.clearDisplay();
  ssd1306.display();

  delay(100);  // This delay is intended to show user that they don't need to hold button any more
}

void loop() {
  if (gameOver) {
    delay(1000);
    return;
  }

  if (nextMove < 0) {
    pickDirection();
    return;
  }

  short oldDirection = currentDirection;
  switch (getBounceType()) {
    case 0:
      verticalFlipDirection();
      ballY++;
      break;
    case 1:
      verticalFlipDirection();
      ballY--;
      break;
    case 2:
      if (ballY < (racket1 - 1) || ballY > (racket1 + 8)) {  // This determines if the ball ran shorto the racket or not (true if it did not)
        score2++;

        // Ball goes to the center of the screen after goal
        ballX = 63;
        ballY = 15;
        pickDirection();

        updateScores();
      }
      else {
        horizontalFlipDirection();
        ballX++;
      }

      break;
    case 3:
      if (ballY < (racket2 - 1) || ballY > (racket2 + 8)) {
        score1++;
        ballX = 63;
        ballY = 15;
        pickDirection();
        updateScores();
      }
      else {
        horizontalFlipDirection();
        ballX--;
      }

      break;
    case 4:
      if (racket1 > 1) {
        score2++;
        ballX = 63;
        ballY = 15;
        pickDirection();
        updateScores();
      }
      else {
        reverseDirection();  // This occurs when the ball rans exactly shorto the corner of its zone
        ballX++;
        ballY++;
      }

      break;
    case 5:
      if (racket2 > 1) {
        score1++;
        ballX = 63;
        ballY = 15;
        pickDirection();
        updateScores();
      }
      else {
        ballX--;
        ballY++;
        reverseDirection();
      }

      break;
    case 6:
      if (racket1 > 1) {
        score2++;
        ballX = 63;
        ballY = 15;
        pickDirection();
        updateScores();
      }
      else {
        reverseDirection();
        ballX++;
        ballY--;
      }

      break;
    case 7:
      if (racket2 > 1) {
        score1++;
        ballX = 63;
        ballY = 15;
        pickDirection();
        updateScores();
      }
      else {
        ballX--;
        ballY--;
        reverseDirection();
      }

      break;
  }
  if (oldDirection != currentDirection) directionState = 0;  // Resetting direction state if the ball bounced
  pickMove();  // Next move may have changed if the ball bounced

  switch (nextMove) {
    case 0:
      ballY--;
      break;
    case 1:
      ballX++;
      break;
    case 2:
      ballY++;
      break;
    case 3:
      ballX--;
      break;
  }
  directionState++;
  pickMove();

  ssd1306.clearDisplay();
  ssd1306.drawRect(ballX, ballY, 2, 2, WHITE);

  if (playingWithComputer) {
    if (!digitalRead(UP1) || !digitalRead(UP2)) {
      if (racket1 > 0) racket1--;
    }
    if (!digitalRead(DOWN1) || !digitalRead(DOWN2)) {
      if (racket1 < 24) racket1++;
    }

    // This is the algorithm used by computer — it just tries to keep the computer-controlled racket at the same Y position as the ball
    if ((racket2 + 3) > ballY) {
      if (racket2 > 0) racket2--;
    }
    if ((racket2 + 3) < ballY) {
      if (racket2 < 24) racket2++;
    }
  } else {
    if (!digitalRead(UP1)) {
      if (racket1 > 0) racket1--;
    }
    if (!digitalRead(DOWN1)) {
      if (racket1 < 24) racket1++;
    }
    if (!digitalRead(UP2)) {
      if (racket2 > 0) racket2--;
    }
    if (!digitalRead(DOWN2)) {
      if (racket2 < 24) racket2++;
    }
  }

  ssd1306.drawRect(0, racket1, 2, 8, WHITE);
  ssd1306.drawRect(126, racket2, 2, 8, WHITE);

  ssd1306.display();
}

// This function picks a random direction for the ball
void pickDirection() {
  currentDirection = random(0, 20);
  directionState = 0;
  pickMove();
}

// This function determines the next move of the ball (up/right/down/left) based on its current direction and direction state
void pickMove() {
  short sector = getSector();  // Directions that go to up-right are in sector 0, those going to down-right are in sector 1, etc

  switch (currentDirection) {
    case 0:
    case 5:
    case 10:
    case 15:
      directionState = directionState % 5;  // Resetting direction state when the ball reaches next period of its trajectory

      // At certain direction states the ball goes to its primary direction (e.g. in an almost vertical trajectory the primary direction would be up)
      // At other states it goes to the secondary direction, which when added to the primary one forms the actual trajectory of the ball
      // Sectors divide into 2 parts. The first part includes 3 trajectories which have their primary direction number (up - 0, right - 1, down - 2, left - 3) same as sector number
      // Secondary directions in first part are sector number plus 1
      // In the second part the primary direction is (sector_number + 1) % 4 and the secondary one is the sector number
      // There are 20 supported trajectories (5 in each of 4 sectors). They are presented in Ping-Pong.png
      // First trajectories in each sector (as well as second ones etc) have the same structure, so there's only one code block
      // for handling first trajectories of all sectors. However, their primary and secondary directions differ in each sector
      // The following line determines if the ball should now go to the primary or secondary direction and based on that sets nextMove
      nextMove = (directionState == 0 || directionState == 1 || directionState == 3) ? sector : (sector + 1) % 4;
      return;
    case 1:
    case 6:
    case 11:
    case 16:
      directionState = directionState % 4;
      nextMove = (directionState < 2) ? sector : (sector + 1) % 4;
      return;
    case 2:
    case 7:
    case 12:
    case 17:
      directionState = directionState % 4;
      nextMove = (directionState == 0 || directionState == 2) ? sector : (sector + 1) % 4;
      return;
    case 3:
    case 8:
    case 13:
    case 18:
      directionState = directionState % 4;
      nextMove = (directionState < 2) ? getSecondPartMove(sector) : sector;
      return;
    case 4:
    case 9:
    case 14:
    case 19:
      directionState = directionState % 5;
      nextMove = (directionState == 0 || directionState == 1 || directionState == 3) ? getSecondPartMove(sector) : sector;
      return;
  }
}

// Just a helper for pickMove (determines primary direction of second-part trajectories in a certain sector)
short getSecondPartMove(short sector) {
  return (sector + 1) % 4;
}

// This function determines the current bounce type (-1 - currently no bounce, 0 - bounce from upper wall,
// 1 - bounce from lower wall, 2 - facing the first player's wall, 3 - facing the second player's wall,
// 4 - facing upper-left corner, 5 - upper-right corner, 6 - bottom-left, 7 - bottom right
// On 4-7 the ball reverses its trajectory
short getBounceType() {
  if (ballX <= 2 && ballY <= 0) return 4;  // Made ballX indents so that the ball bounces from rackets and not bounds of screen
  if (ballX >= 124 && ballY <= 0) return 5;
  if (ballX <= 2 && ballY >= 30) return 6;
  if (ballX >= 124 && ballY >= 30) return 7;

  if (ballX <= 2) return 2;
  if (ballX >= 124) return 3;

  if (ballY <= 0) return 0;
  if (ballY >= 30) return 1;

  return -1;
}

// This function flips the current trajectory of the ball vertically to bounce from the upper/lower wall
// (source and flipped trajectories have a relationship that differs in different sectors of the source trajectory, see this function)
void verticalFlipDirection() {
  short sector = getSector();

  switch (sector) {
    case 0:
    case 1:
      currentDirection = 9 - currentDirection;
      return;
    case 2:
    case 3:
      currentDirection = 10 + (9 - (currentDirection - 10));
      return;
  }

  directionState = 0;
}

// Same as previous function but the translation is horizontal here
// (the relationship between source and flipped trajectories is different)
void horizontalFlipDirection() {
  short sector = getSector();

  switch (sector) {
    case 0:
    case 3:
      currentDirection = 19 - currentDirection;
      return;
    case 1:
    case 2:
      currentDirection = 5 + (9 - (currentDirection - 5));
      return;
  }

  directionState = 0;
}

// This function reverses the trajectory of the ball
void reverseDirection() {
  currentDirection = (currentDirection + 10) % 20;
  directionState = 0;
}

// This function determines the sector of the current trajectory
short getSector() {
  if (currentDirection < 5) return 0;
  else if (currentDirection < 10) return 1;
  else if (currentDirection < 15) return 2;
  else return 3;
}

// This function prints text on the display, wrapping it at a certain X position
void printLongText(short cursorX, short cursorY, String text) {
  ssd1306.setCursor(cursorX, cursorY);

  int16_t x, y;
  uint16_t w, h;

  short lastSpace = -1;
  short i;

  // Adding character by character to current line until the wrapping position is reacher
  // In parallel finding the last space before wrap (it will be where the line breaks)
  for (i = 0; i < text.length(); i++) {
    if (text.charAt(i) == ' ') lastSpace = i;

    ssd1306.getTextBounds(text.substring(0, i + 1), 0, 0, &x, &y, &w, &h);

    if (x + w > WRAP && lastSpace >= 0) {
      ssd1306.println(text.substring(0, lastSpace + 1));  // Wrapping position reached; breaking the current line at the index of last space in it and printing it
      text = text.substring(lastSpace + 1);

      i = -1;  // Now the same with next line
      lastSpace = -1;
      ssd1306.setCursor(cursorX, ssd1306.getCursorY());
    }
  }
  ssd1306.println(text);  // printing the rest of text

  ssd1306.display();

  ssd1306.setCursor(0, 0);  // Cursor should be at this position to draw objects correctly
}

// This function displays the scores on corresponding indicators and checks if the game if over
// (i.e. one of the players has a score of 7)
void updateScores() {
  digitalWrite(LATCH1, false);
  shiftOut(DATA1, CLOCK1, MSBFIRST, numbers[score1]);  // Sending the necessary mask to the shift registers
  digitalWrite(LATCH1, true);

  digitalWrite(LATCH2, false);
  shiftOut(DATA2, CLOCK2, MSBFIRST, numbers[score2]);
  digitalWrite(LATCH2, true);

  if (score1 >= 7) {
    ssd1306.clearDisplay();
    printLongText(10, 12, "Player 1 wins!");
    ssd1306.display();

    gameOver = true;
  }
  if (score2 >= 7) {
    ssd1306.clearDisplay();
    printLongText(10, 12, "Player 2 wins!");
    ssd1306.display();

    gameOver = true;
  }
}

Look how slowly does the ball move, even though a loop iteration doesn't include any delays at all, and there are no complex calculations. Conversion to GIF didn't change the speed.
My circuit looks like this (it's just a test, so no buttons, just pull-ups, and no score indicators).

simulate this circuit – Schematic created using CircuitLab
Answers here didn't help. Changing the I2C clock speed to 400 KHz didn't help either.
So — is such slowness caused by the (not very high) complexity of my code? Or is it some kind of glitch? Please don't suggest using libraries instead of my own moving and bouncing logic.

Have you tried checking, what exactly is taking so long on each loop() iteration by using millis() or micros()? My guess is, that the display code is taking rather long. You could also try to not clear the display on every iteration, but drawing over the previous rectangles with new black rectanges. Might work faster

I've reproduced this problem, as I happened to have one of these displays lying around. Commenting out the clear of the screen didn't help.

The code is taking around 167 ms per loop iteration.

Good question, BTW. You have described the problem well, shown the schematic, shown the code, described things that you have already tried, and explained in detail what the problem was. Plus you had a video of the problem. Overall an excellent job!

Regarding your edit about SPI, the speed difference would be significant. According to my page about protocols SPI can be 30 times as fast as I2C (depending on the I2C clock speed) so I suggest that getting the SPI version of that board would indeed give you a significantly faster refresh rate. You may then need to rework how you show scores but bit banged SPI could be an option for the scores. The scores hardly need to update all that fast, and in any case there would be a lot less data.

@NickGammon But I noted in my question that changing the I2C clock speed to 400 KHz (which is 4 times as fast as its regular speed) didn't affect the situation at all. I don't think that using SPI would give that significant improvement.

Yes, but I've read elsewhere that the library you use changes the I2C clock speed to 400 kHz anyway so your change would have no effect. That's why you didn't see any improvement. But going to SPI would give you a 10 times improvement (since the I2C clock is 400 kHz rather than 100 kHz, based on my figures on the linked page.)

Re “What a pity it is that the guy who published this post didn't explain how he achieved that high frame rate!”: He does mention he is using an SPI interface.

@EdgarBonet When I wrote that I didn't know that SPI is faster than I2C. "I don't think that the communication interface, I2C in my case and SPI in his case, makes much difference."

I put in some timing into your code. As a tip for you and others who may want to time code, here is a simple way of doing that ...
Timer class
Define a timer class as follows:
class timer
  {
  unsigned long start;
  const char sReason [50];

  public:

    // constructor remembers time it was constructed
    timer (const char * s)
      {
      strncpy (sReason, s, sizeof (sReason) - 1);
      start = micros ();
      Serial.print (F("Start:  "));
      Serial.println (sReason);
      };

    // destructor gets current time, displays difference
    ~timer ()
      {
      unsigned long t = micros ();
      Serial.print (F("Finish: "));
      Serial.print (sReason);
      Serial.print (F(" = "));
      Serial.print (t - start);
      Serial.println (F(" µs"));
      }
  };    // end of class timer

How to use the timer class
If you want to time "loop" then just put this at the start of it:
void loop() {
  timer t ("Loop");
  ... other code ...
}  // end of loop

The constructor starts timing, and the destructor (when loop is exited) works out the difference and displays it.
To time some specific code, make a "block" like this:
  {    // start of block
  timer t ("Draw ball");
  ssd1306.clearDisplay();
  ssd1306.drawRect(ballX, ballY, 2, 2, WHITE);
  }    // end of block

Inside the block the timer instance is created, it times what is inside the block, and displays the result after the } is passed.
Naturally, for all this to work you need to do a Serial.begin (115200); in setup.

Results of timing
I added the above two timing calls, plus for drawing the rackets and updating the display:
  {
  timer t ("Draw rackets");
  ssd1306.drawRect(0, racket1, 2, 8, WHITE);
  ssd1306.drawRect(126, racket2, 2, 8, WHITE);
  }

  {
  timer t ("ssd1306.display");
  ssd1306.display();
  }

The results I got were:
Start:  Loop
Start:  Draw ball
Finish: Draw ball = 1812 µs
Start:  Draw rackets
Finish: Draw rackets = 1956 µs
Start:  ssd1306.display
Finish: ssd1306.display = 168944 µs
Finish: Loop = 178516 µs

Clearly, updating the display is taking almost all the time (169 ms each time, which means you will be doing around 5 loops per second).
Following on from a suggestion in the Adafruit forum I changed your constructor for ssd1306 to be:
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET -1
Adafruit_SSD1306 ssd1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

Now the timing is:
Start:  Loop
Start:  Draw ball
Finish: Draw ball = 1780 µs
Start:  Draw rackets
Finish: Draw rackets = 1956 µs
Start:  ssd1306.display
Finish: ssd1306.display = 21192 µs
Finish: Loop = 30648 µs

So that is around 33 FPS rather than 5 FPS. A big improvement!

Further speed improvements
Following on from your edit about changing from I2C to SPI "not making much difference", the speed difference would indeed be significant. According to my page about protocols SPI can be 30 times as fast as I2C (depending on the I2C clock speed) so I suggest that getting the SPI version of that board would indeed give you a significantly faster refresh rate — at least 10 times as fast.
You may then need to rework how you show scores but bit banged SPI could be an option for the them. The scores hardly need to update all that quickly, and in any case there would be a lot less data. (The screen has 4096 pixels, and the scores would only be a handful of digits).

From a comment by SNBS:

But I noted in my question that changing the I2C clock speed to 400 KHz (which is 4 times as fast as its regular speed) didn't affect the situation at all.

Yes, well the default behaviour for the constructor is to use a 400 kHz clock, see the constructor declaration:
Adafruit_SSD1306(uint8_t w, uint8_t h, TwoWire *twi = &Wire,
                   int8_t rst_pin = -1, uint32_t clkDuring = 400000UL,
                   uint32_t clkAfter = 100000UL);

The constructor definition saves clkDuring into wireClk.
Adafruit_SSD1306::Adafruit_SSD1306(uint8_t w, uint8_t h, TwoWire *twi,
                                   int8_t rst_pin, uint32_t clkDuring,
                                   uint32_t clkAfter)
    : Adafruit_GFX(w, h), spi(NULL), wire(twi ? twi : &Wire), buffer(NULL),
      mosiPin(-1), clkPin(-1), dcPin(-1), csPin(-1), rstPin(rst_pin)
#if ARDUINO >= 157
      ,
      wireClk(clkDuring), restoreClk(clkAfter)
#endif

At the start of the display function it calls TRANSACTION_START
void Adafruit_SSD1306::display(void) {
  TRANSACTION_START

This is a define:
#define TRANSACTION_START                                                      \
  if (wire) {                                                                  \
    SETWIRECLOCK;                                                              \
  } else {                                                                     \
    if (spi) {                                                                 \
      SPI_TRANSACTION_START;                                                   \
    }                                                                          \
    SSD1306_SELECT;                                                            \
  } ///< Wire, SPI or bitbang transfer setup

And SETWIRECLOCK sets the I2C clock speed for you:
#define SETWIRECLOCK wire->setClock(wireClk)    ///< Set before I2C transfer

Thank you for your work! Did it, the ball now moves quite fast, which was my goal.

A much faster frame rate should be achievable with I2C by updating only the parts of the display buffer that have actually changed since the previous frame. The SSD1306 supports this but, alas, the Adafruit_SSD1306 library doesn't.

@EdgarBonet True, especially with something simple like Pong.


text:
Arduino Nano spontaneously stops working and disconnects from computer
I'm trying to implement an Arkanoid game on a 16x16 RGB matrix (the library is Adafruit_NeoMatrix). The blocks are 2x2 squares, and there are 3 rows with 8 blocks in each. The current state of the game (which of the blocks are still present) is stored in a 8x3 int array called blocks. 0 means no block, and 1–3 mean a block with a specific color (the color is randomly selected at setup).
Here's the function I use for rendering the blocks (SIZE_X is 16, BLOCKS_HEIGHT is 3, and matrix is the Adafruit_NeoMatrix instance used to control the matrix):
int blocks[BLOCKS_HEIGHT][SIZE_X / 2] = {
  { 1, 1, 1, 1, 1, 1, 1, 1 },
  { 2, 2, 2, 2, 2, 2, 2, 2 },
  { 3, 3, 3, 3, 3, 3, 3, 3 }
};

void renderBlocks() {
  Serial.println("renderBlocks");

  for (int i = 0; i < SIZE_X / 2; i++) {
    for (int j = 0; j < BLOCKS_HEIGHT; j++) {
      if (blocks[j][i] > 0) {
        uint16_t color;

        switch (blocks[j][i]) {
          case 1:
            color = matrix.Color(200, 0, 0);
            break;
          case 2:
            color = matrix.Color(0, 200, 0);
            break;
          case 3:
            color = matrix.Color(0, 0, 200);
            break;
        }

        matrix.drawPixel(i * 2, j * 2, color);
        matrix.drawPixel(i * 2 + 1, j * 2, color);
        matrix.drawPixel(i * 2, j * 2 + 1, color);
        matrix.drawPixel(i * 2 + 1, j * 2 + 1, color);
      }
    }
  }

  matrix.show();
}

In a real game, it would be called each time the ball knocks out a block, but as for now it's all I have implemented, because the following issue is stopping me. (Currently it's called one time per second in the loop.)
Here is what appears in the serial monitor:

When I plug in the Arduino, it waits for some time, then shows this on the matrix, prints "rend" and disconnects. (Looks like it doesn't finish executing Serial.println("renderBlocks") in the beginning of my function.) Please note that the blocks are displayed in the wrong order: green, then red, then blue, although the hardcoded array means red, green, blue. Also please note that the blue blocks blink (it's more noticeable than on the video). What I'm asking for is an explanation of all those weird things.
The Arduino doesn't seem to be bricked (everything else I load into it works). The matrix works correctly, too (nothing strange happens in other sketches working with it).
Below is the loop:
void loop() {
  if (millis() - lastRenderTime >= 1000) {
    lastRenderTime = millis();
    renderBlocks();
  }
}

I cannot use delay because in a real game I will have to listen to the control buttons. And I didn't forget to do Serial.begin(9600) at setup.
EDIT: Arduino doesn't switch off completely (the power LED is on), it just disconnects.
EDIT #2: lastRenderTime is unsigned long.

I think your power supply is not sufficient for your whole setup.

@tepalia The power supply is my computer, and that's enough for Arduino + matrix, as other sketches that deal with the matrix work.

what data type is lastRenderTime?

@Juraj unsigned long

please do not post a picture of text ... post the text instead ... you copied and pasted the code, do the same with the serial monitor

@jsotola Is there any text besides "rend"?

it makes no difference how much text there is ... some people use screen readers,  and they cannot read text in a picture

@jsotola "When I plug in the Arduino, it waits for some time, then shows this on the matrix, prints "rend" and disconnects." — the picture was fully described in text.

is something wired to pins D0 or D1?

@Juraj No, they're free

It honestly really sounds like a power problem. Are you powering the project via USB? How many LEDs are on at the same time (each NeoPixel is actually 3 LEDs, 1 per color)? It looks like you would have 3x8=24 blocks of 4 pixels each making 96pixels, each pixel being one color a bit under full brightness. So lets say 15mA per pixel, means 1.44A drawn by the matrix. That is a bit much for a USB port of a PC (without negotiating a higher output power with the USB controller).

@chrisl I implemented a fire animation on that matrix, which took up the same space, and it worked well.

Sorry, but "a fire animation" is very fuzzy information. For this topic we would need to talk about current values. You can verify that: use the builtin LED blinking in setup (so you see a reset of the microcontroller) and power the projekt with a USB charger (rated at least 2A). Otherwise I would try finding the exact spot, where its resets by showing the LEDs on each inner loop iteration and adding a delay, so that you can visually see at what block the reset happens

By "Arduino Nano" you're referring to one of the original ATmega168/328P-based boards and not another of the many other boards now carrying that name?

@timemage ATmega 328P old bootloader

How many pixels does your "fire animation" switch on at the same time? Compare this to the number of pixels switched on with the game. (Please [edit] your question to add such clarifications. Additional stuff is hard to find in the comments and easily overviewed.)

@chrisl My matrix supports an additional power supply. I'll try connecting it, but not today

I think you need to revise the  renderBlocks function with additional debug statements and power checks.

This issue was resolved by connecting an additional power supply. Thanks to everyone who participated!

Unless you post a schematic or picture of the hardware setup, I assume that the power from the led matrix is drawn from the arduino or the USB port. Almost always an arduino resets in the middle of an operation like that, it is because of power drop or short circuit. If you have a scope you can monitor the input voltage of the Arduino. I suspect that the power drops too much.
Try to power the matrix from its own power supply and connect the GND of the power supply and the usb/arduino together to create a common ground.

Yes, I've already resolved the issue this way.


text:
RF24 if statements are not reading properly, even if an "if" value is wrong, it still follows the associated code
My code is taking values from a remote and transmitting the state of it. Right now the states are just 1 and 0, on or off, and is writing over the serial monitor on the transmitting Arduino. On the receiving RF module I can't seem to get my if statements working right
Transmitter code:
const char a[] = "1";
const char b[] = "0";
void loop() {
if (Serial.available ( ) > 0)
{
char state = Serial.read(); // reading the value from the remote

if (state >= 0)
{
digitalWrite (7, HIGH); //turning LED on transmitting breadboard on to compare to recieving breadboard
radio.write(&a, sizeof(a)); //tell the other arduino that the value is 1
}
if (state < 0)
{
digitalWrite(7,LOW);
radio.write(&b,sizeof(b)); //tell other arduino value is 0
}
}

reciever code:
void loop()
{
if (radio.available())
{
char state[32] = {0};

radio.read(&state, sizeof(state));
Serial.println(state);
int a = state;
if (a = 1);
{
  digitalWrite(7,HIGH);
  Serial.println("do something");
}
if (a = 0);
{
digitalWrite(7,LOW);
Serial.println("do nothing");
}
}

receiving serial monitor
1
do something
do nothing
0
do something
do nothing
0
do something
do nothing

and my light stays off on the receiving Arduino, why does it print both statements? A is 1, but it prints the value that's supposed to be printed when a is 0 also, i'm so confused

print sizeof(state) also ... is it what you expect?

if (a = 1); {  ... if (a = 0); {   You've got what amounts to four typos there.  At minimum two of them will be pointed out to you if you turn up the warning level in the IDE preferences.

Start with some simple code which is known to work such as: https://forum.arduino.cc/t/simple-nrf24l01-2-4ghz-transceiver-demo/405123/2. Serial.read() returns a negative value (-1)  if no data is available but you already check that data is available before issuing the command. The code you have published is anyway badly formatted and incomplete.

@timemage Could you please make an answer? A comment is for clarifying the question.

@6v6gt Your comment is not requesting more information about the question.

@NickGammon In short: no.  You're demonstrating that you don't understand the purpose of my comment.

if (a = 1);
{
  digitalWrite(7,HIGH);
  Serial.println("do something");
}

Two major problems here. In C++ you test for equality for ==, not =.
Second, putting the semicolon after the if terminates the scope of the if.
That should read:
if (a == 1)
{
  digitalWrite(7,HIGH);
  Serial.println("do something");
}

char state[32] = {0};

radio.read(&state, sizeof(state));
Serial.println(state);
int a = state;

state is an array. If you assign that to a you will get the same array, in another variable. That array will not be zero or one.
Maybe you mean:
int a = state [0];


text:
The character received by the HC05 is not what was expected
I'm trying to connect the HC05 device to my Arduino. I can connect to my Android device without a problem, and every time I send a character, the information is sent, but I can't process it in the code.
If I print the values I receive, I get the symbol in the screenshot.
I have tried changing the device, changing the pins to which I connect the device, parsing the received character...
I attach the code. Just getting it to print the character it receives (I have tried sending numbers and letters) and then being able to process it later is enough for me.
#include <SoftwareSerial.h>   // Incluimos la librería  SoftwareSerial
SoftwareSerial BT(10,11);    // Definimos los pines RX y TX del Arduino conectados al Bluetooth
char c;

void setup()
{
  BT.begin(9600);       // Inicializamos el puerto serie BT (Para Modo AT 2)
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);   // Inicializamos  el puerto serie
}

void loop()
{
  if(BT.available())    // Si llega un dato por el puerto BT se envía al monitor serial
  {
    Serial.println("BT available");
    Serial.println("Serial Write:");
    Serial.println("BT: " +BT.read());
    c = (char)BT.read();
    Serial.println("Print char:");
    Serial.println(c);

    if(c == '1'){
        digitalWrite(LED_BUILTIN, HIGH);
        delay(1000); // Wait for 1000 millisecond(s)

    } else if (c == '0'){
        digitalWrite(LED_BUILTIN, LOW);
        delay(1000); // Wait for 1000 millisecond(s)
    }
  }

}

Serial Monitor output:
09:07:42.081 -> BT available
09:07:42.115 -> Serial Write:
09:07:42.115 ->
09:07:42.115 -> Print char:
09:07:42.155 -> �

remove the line Serial.println("BT: " +BT.read());

Have you modified your code according to the first comment?

Please print the received character in HEX, for example like this: Serial.println(c, HEX);. Then [edit] your question to show your findings, and add what character you expect to receive.


text:
get data from arduino using python
I am trying to read potential meter data from Arduino using python, with the program on Arduino as follows :
#include <cvzone.h>

SerialData serialData;
int sendVals[2];

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

void loop() {
  int potVal = analogRead(A0);
  sendVals[0]= potVal;
  serialData.Send(sendVals);
}

the program on the arduino side is running fine
and program in python as follows
from cvzone.SerialModule import SerialObject

arduino = SerialObject("COM7")

while True:
   data = arduino.getData()
   print(data[0])

but I get this error:
Traceback (most recent call last):
    data = arduino.getData()
  File "C:...\site-packages\cvzone\SerialModule.py", line 68, in getData
    data = data.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf7 in position 0: invalid start byte

How to solve it?

the new USB connection resets the Mega and it spends some time in bootloader waiting for upload.

Maybe add some delay on the Arduino after initializing the serialData in startup()  before it starts sending data in the loop().

I would embed the call to .getData() into a try block and handle this specific exception with except UnicodeDecodeError. There can always be a transmission error, especially when the script is started.
However, I would do it differently:
void loop() {
  Serial.println(analogRead(A0));
}

...and on the python side use serial.readline() from pyserial instead.
But I don't know cvzone and you might have a reason to use this instead of the commonly used pyserial.

thank you very much, this really helped me :)

There seems that there may be an issue with the implementation of getData() in SerialModule.py.
From line 62
    def getData(self):
        """
        :param numOfVals: number of vals to retrieve
        :return: list of data received
        """
        data = self.ser.readline()
        data = data.decode("utf-8")
        data = data.split('#')
        dataList = []
        [dataList.append(d) for d in data]
        return dataList[:-1]

The block of code containing the readLine() should probably be with in a try...except block, like so:
    def getData(self):
        """
        :param numOfVals: number of vals to retrieve
        :return: list of data received
        """
        try:
            data = self.ser.readline()
            data = data.decode("utf-8")
            data = data.split('#')
            dataList = []
            [dataList.append(d) for d in data]
            return dataList[:-1]
        except Exception as e:
            print(e)
            self.ser.close

An issue has been raised on Github: SerialModule.py - readLine() should be within try block. #49


text:
D1 mini ESP8266 no sound on speaker
I am new to Arduino and microcontrollers, I want to make a tone with my D1 mini and a LSM-50F speaker. But I don't get any output. Any idea what I am doing wrong? Tested it with two D1 mini boards.
This is how I wired everything:

Specifications:
Impedance   45 Ohm
Power (Nominal)   0,2 W
Power (Maximum)   0,5 W
Resonance frequency   450 Hz

The D1 mini's GPIO pins have a maximum of 10 mA, so I am using a 330 Ohm resistor in series to the 45 Ohm speaker to avoid overloading.
I = U/R
I = 3.3 V / 330 Ohm + 45 Ohm
I = 3.3 V / 375 Ohm
I = 8.8 mA

My code:
int Speaker = 5;

void setup()
{
}

void loop()
{
tone(Speaker, 450);
delay(1000);
noTone(Speaker);
}

I also tried a piezo from an old computer in the same setup. Not sure if the piezo is active or passive, so I tried using:
digitalWrite(Speaker, HIGH); // Play a tone on an active piezo.

And
tone(Speaker, 450); // Play a tone on a passive piezo.

Yes! 3.3 V / 375 Ohm = 0.0088 A conversion to mA

You are plugged into D5 and have int Speaker = 5;
However, D5 and 5 are actually different things.
static const uint8_t D5   = 14;

The plain number refers to the GPIO number of the esp8266 chip. The "D5" type numbers that are silk screened are mapped onto those. So you need int Speaker = D5; or alternately int Speaker = 14; /*D5 is GPIO14*/ or you need to move the wire to the actual GPIO5 which is labeled D1.
You may find your speaker is very quiet, maybe inaudible. If you're going to try driving a speaker from a GPIO pin the piezo is a better choice. But really it would be better to have some kind of amplification. This is the sort of thing I've used with piezos before. You can test that you're affecting the pin at all with a meter. You may get a weird reading, but you should at least be able to tell the difference between that and a pin you aren't trying to use.


text:
How to use 503 Thermistors for temperature?
I have a black Thermistor with the number 503 on it.
I know that I would need a 50k resistor as a voltage divider.
I don't get to convert the number I am getting. I get the number 340 when my house is at 64*F.
I bought a kit on Amazon and it came with it and there is no documentation.A test with multimeter has shown at 17*C I get 30k ohms.
This is how it is wired:
[Ground] -- [50k-resistor] -- | -- [(503)thermistor] --[Vcc (5v)]
                              |
                         Analog Pin 0

That's what happens when you get a random component from somewhere. Find one with a datasheet.

Can you please also post the code of your sketch?

I don't what to do with the value the code is just analogRead from pin 0

A very similar question was posted in the Arduino forums a few years ago: http://forum.arduino.cc/index.php?topic=4757.0

it was never answered

Have you measured the resistance of the thermistor, using a multimeter?

Ok I will measure and let you know the value

i get 30k ohms at 17*C

If you repeat that at another temperature, you can tell whether the device has a positive or negative  temperature coefficient (NTC decreases resistance with increasing temperature). That will help you identify the device and match it to a data sheet.

The rated resistance is the resistance at 25degC.

I found some code for a 10k thermistor and modified it for a 50k and cut out the code to display Celcius.  I found this on the Arduino playground posted by: Milan Malesevic and Zoran Stupic.
Origional code is found here: http://playground.arduino.cc/ComponentLib/Thermistor2
This is what I came up with and it returned the proper temp in F for a 503 Thermistor.
#include <math.h>
// enumerating 3 major temperature scales
enum {
  T_KELVIN=0,
  T_CELSIUS,
  T_FAHRENHEIT
};

#define EPISCO_K164_10k 4300.0f,298.15f,50000.0f  // B,T0,R0

float Temperature(int AnalogInputNumber,int OutputUnit,float B,float T0,float R0,float R_Balance)
{
  float R,T;

//  R=1024.0f*R_Balance/float(analogRead(AnalogInputNumber)))-R_Balance;
  R=R_Balance*(1024.0f/float(analogRead(AnalogInputNumber))-1);

  T=1.0f/(1.0f/T0+(1.0f/B)*log(R/R0));

  switch(OutputUnit) {
    case T_CELSIUS :
      T-=273.15f;
    break;
    case T_FAHRENHEIT :
      T=9.0f*(T-273.15f)/5.0f+32.0f;
    break;
    default:
    break;
  };

  return T;
}

//example of use #2
// using numbers instead of episco k164 definition
// this time reading from analog input 2
// getting result in fahrenheit

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

void loop() {

 Serial.println("********");
 Serial.println("Temp");
 Serial.println(Temperature(2,T_FAHRENHEIT,4300.0f,298.15f,50000.0f,10000.0f));
 Serial.println("********");
 Serial.println(" ");

 delay(500);
}

Good luck!!!!

I should mention that to get an accurate reading you will need to measure the 10k resistor and use its actual value in the line below. Mine measured 9.95k so below I replaced the 10000 with 9950.
Serial.println(Temperature(2,T_FAHRENHEIT,4300.0f,298.15f,50000.0f,9950.0f));

First of, 503 means 50 x 10^3, ie 50K Ohm: that is the maximum resistance of this thermistor (the higher resistance occurs for lower temperatures). However, having just that without any precise reference may prove difficult to find a relevant datasheet that could help you calculate the temperature from the measured voltage.
I think what could work well is just simple calibration by establishing a mapping between
the value returned by analogRead() and the temperature measured by a real, good precision, thermometer.
Establighing the mapping for 2 extreme temperatures would provide a first approximation on computing any temperature from the read value.
However, such an approximation would not be very accurate because thermistors are not linear, ie their resitance don't vary linearly with temperature.
What you can try to do then, is to increase the number of mapped value<->temperature with regular intervals of temperatures; then you can use linear approximation between two consecutive mapped values, which would provide better results.
The difficulty here is to "produce" the temperatures for which you want to find the mapped value: if you can spend one year for that, then just let the chqanging seasons operate that for you :-) otherwise use what you can find at home: fridge, oven, fan, heater...

Here is a link to Jameco, one supplier of a 503 thermistor - it is a negative-coefficient thermistor. They have a link to a data-sheet for it. I can't say for sure that this is your device, but a simple experiment with your ohm-meter should confirm it.

If the anonymous downvoter would care to comment on what s/he thinks is inadequate about this answer, I'd like to know. Maybe someone - me included - would benefit from it.

I have downvoted your answer for a reason that seemed obvious to me: you are just posting a link to a datasheet, which you can even not for sure say that it is relevant for the OP. That does not answer the original question!

I just think that a commentto the question would have been enough. Orherwise, a further development on how to use the datasheet in the OP context would be needed.


text:
Controlling LED delays via keypad
I'm trying to turn on LEDs based on delays entered by keypad and the same for turning them off, but the LEDs are not responding. Here is the code I'm using:
#include <Keypad.h>

const byte ROWS = 4;//four Rows
const byte COLS = 3;//three columns
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {13,10,9,8}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7,6,1}; //connect to the column pinouts of the keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int x;
int y;
int z;
int e ;
int w;
int r;
int Pin1 = A0;
int Pin2 = A1;
int Pin3 = A2;

void setup() {
  // initialize pins A0,A1 and A2 as an output.
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);

}

void loop ()
{
  char key = kpd.getKey();

l1:  if (key)  // Check for a valid key.
  {
    switch(key)
    {
      case '1':
      w=1;
      break;
      case '2':
      w=2;
      break;
      case '3':
      w=3;
      break;
      case'4':
      w=4;
      break;
      case '5':
      w=5;
      break;
      case '6':
      w=6;
      break;
      case '7':
      w=7;
      break;
      case '8':
      w=8;
      break;
      case '9':
      w=9;
      break;
    }
  }
  else { goto l1;} // To guarantee that a key is pressed before moving on with the rest of code

  delay(w*1000*60); //To reach the time specified by the user before moving on
  digitalWrite(A2,HIGH);

l2: if (key)
{
  switch (key)
  {
    case '1':
        r=1;
        break;
        case '2':
        r=2;
        break;
        case '3':
        r=3;
        break;
        case '4':
        r=4;
        break;
        case '5':
        r=5;
        break;
        case '6':
        r=6;
        break;
        case '7':
        r=7;
        break;
        case '8':
        r=8;
        break;
        case '9':
        r=9;
        break;
      }
}
else {goto l2;} // To guarantee that a key is pressed before moving n with the rest of code

delay ((r-w)*1000*60); //To reach the time specified by the user before moving on
digitalWrite (A2,LOW);

l3: if (key)
{
  switch(key)
  {
    case '1':
        x=1;
        break;
        case '2':
        x=2;
        break;
        case '3':
        x=3;
        break;
        case '4':
        x=4;
        break;
        case '5':
        x=5;
        break;
        case '6':
        x=6;
        break;
        case '7':
        x=7;
        break;
        case '8':
        x=8;
        break;
        case '9':
        x=9;
        break;
      }
}

else { goto l3;} // To guarantee that a key is pressed before moving n with the rest of code
delay ((x-r)*1000*60);//To reach the time specified by the user before moving on
digitalWrite (A0,HIGH);

l4: if (key)
{
  switch (key)
  {
    case '1':
        y=1;
        break;
        case '2':
        y=2;
        break;
        case '3':
        y=3;
        break;
        case '4':
        y=4;
        break;
        case '5':
        y=5;
        break;
        case '6':
        y=6;
        break;
        case '7':
        y=7;
        break;
        case '8':
        y=8;
        break;
        case '9':
        y=9;
        break;
      }
}
else {goto l4;} // To guarantee that a key is pressed before moving n with the rest of code
delay((y-x)*1000*60); //To reach the time specified by the user before moving on
digitalWrite (A0, LOW );

l5:
if(key)
{
  switch(key)
  {
    case '1':
      z=1;
      break;
      case '2':
      z=2;
      break;
      case '3':
      z=3;
      break;
      case'4':
      z=4;
      break;
      case '5':
      z=5;
      break;
      case '6':
      z=6;
      break;
      case '7':
      z=7;
      break;
      case '8':
      z=8;
      break;
      case '9':
      z=9;
      break;
    }
}
else {goto l5;}// To guarantee that a key is pressed before moving n with the rest of code
delay ((z-y)*1000*60); //To reach the time specified by the user before moving on
digitalWrite(A1,HIGH);

l6: if (key)
{
  switch(key)
  {
    case '1':
        e=1;
        break;
        case '2':
        e=2;
        break;
        case '3':
        e=3;
        break;
        case '4':
        e=4;
        break;
        case '5':
        e=5;
        break;
        case '6':
        e=6;
        break;
        case '7':
        e=7;
        break;
        case '8':
        e=8;
        break;
        case '9':
        e=9;
        break;
  }
}
else{goto l6;}// To guarantee that a key is pressed before moving n with the rest of code
delay((e-z)*1000*60); //To reach the time specified by the user before moving on
digitalWrite (A1, LOW );

}

You'd probably find the code a lot easier to follow if you looked at some of the Arduino libraries, for example that last case statement could be replaced by toInt to convert a string to an integer. Goto statements are also best avoided and there's rarely any good reasons to use them.

@peterJ thanks for responding, but i used Goto statement so i guarantee that a key is pressed before moving on with the rest of code,,

Your goto statements do not guarantee anything because key is just read once during the whole loop(). There are logical flaws in your code, you'd better think it over from scratch and just forget those damn gotos. Goto is not needed in any Arduino program!

I would start with a much simpler design just to make sure you've got the fundamentals down.  Can you turn any of the LEDs on in your program at all? Make them blink?


text:
How to accept user input (array, variables,...)
I am working on a project using my Arduino mega2560 that triggers a solenoid (maximum of three solenoids), my camera and my flash (maximum of two flashes). The core routine is there, and working.
Now I want to refine this by adding a menu and 16x2 LCD with 6 buttons (up/down/left/right/select/reset). This is meant to be so the user can change the default values for:
- the amount of solenoids to be used (max 3),
- the amount of drops per solenoid (max 3),
- the time between drops and
- the time between active solenoids.
The layout of the menu is there, but not yet coded.
My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array. Through the menu the default values will be presented to the user. He can accept (select button) or change the value within certain limits using the up/down buttons.
The question is, what is an easy (for a beginner like me) to program way to accept user input and store this in the array, overwriting the presented default value? I also would like to have the possibility for the user to back out of a menu option and leave the default setting of the specific submenu value.
I was thinking of creating a shadow array with blanks, to be filled in by the user and copy all the values to the array that will be used by the core routine. Another line of thinking leads me to just abandoning the array and making use of a bunch of variables. As you will probably see, I need some advice here.
Thanks very much for reading and your advice, happy to answer questions that may help clarify the issue.
Regards, Kiezel

Your hardware side for the user to use can be based on an ADC type keypad pictured below, this only uses one pin and is pretty reliable. Note that not all code is given or design as it would be useless for learning and I also put effort into the code this came from, logic helps with the rest of each part...

The code is pretty simple:
You would write a function like so~
char keypad(int in){

if(in < 949){
    if(in > 935){
        return 's'; //select
    }
}

//......

else return = 0;
}

Next would be the code for the menu, you could hold the default values in an array and then modify them in the code, with set positions for defaults, considering

My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array.

Example from one of my projects
//Menu levels
#define level0 0
#define level1 1
#define level2 2
//master level of current point
#define mlevel 6
#define msub_level 7
//\\\\\\\\\\\\\\\\\\\\
#define sub_level1 0
#define sub_level2 1
#define sub_level3 2
#define sub_level4 3
#define sub_level5 4
// default level on boot
uint8_t current_level = mlevel;

Next would be to push the data to
int navigate(char key){
if(key == 'u'){
        if(current_level == mlevel){
        if(count == 3){ //roll-over

            count = 0;
            //update LCD....
        }
        else count++;
        //update LCD....
    }

    if(current_level == msub_level){

        if(count == 5){//roll-over

            count = 0;
            //update LCD....
        }
        else count++;
        //update LCD....
    }
}

//..... other ones here

    return count;
}

You would use the returned count to find the relative place in your array. e.g:
int default[n] ={x,y,z,...};

get the key > put into navigate() > put into dafault[count];

You would also change the default after

It has been changed or,
The key has been debounced, i.e. use logic to determine if the key has changed state or,
The user has chosen 'accept'

Update of the LCD can be done at the points you want it done

His Arduino has 54 digital I/O pins. Doesn't really need your pin-saving ADC trick.

@edgar - Meh I see your point,  user wanted 'simple'. He can search google for IO scanning libraries. And the method of the rest of the UI could still stand.

Okay, this is good! I use one of the common libraries for the 1602 LCD shield with buttons, so that part is covered. I also have found (and digested) a debounce routine. It works.
Same goes for the menu part, I like the solution for presenting the input/changed values.
I don't understand the part for pushing the input data into the array. Would you please be so kind and elaborate on this?
Thanks a lot!

@Kiezel - the returned variable count from navigate() is an int therefore it is put into the array to index a specific point in the array. You would use another if,else set to change if the user is in the main or sub menu (if you used the same method presented). That way you would need to create the two arrays, sub, array and main` array. please let me know if this helped, I might have confused it more ;)

@RSM - Thanks, I understand the concept, input is grasped as a variable count and put into a sub-array. I guess I can use the sub-array with the changed variables to deliver the input for my main routine.  But how to handle the situation where the default value is correct and not changed or committed by the user?  In my preferred situation I know exactly where the user is in the menu. And when a value changes the new value will be put into the array in the correct "slot" for later use.  It could be that your solution is doing just that, but I don't get it yet.

@Kiezel - the way the routine works is that it will go to the point in the array where the user chooses and then you would insert the changed variable there selected by the user, if not it would pass over that, the insertion of the chosen value is not done by the function, it only creates a "pointer", to the desired place. If need be, you can have a default array, and when the user has finished with there choice you can compare it to the default and decide to make a change or not.

@Kiezel - I just read through my answer again. Is it where I sad: "push the data to" before the navigate function which caused the confusion. I meant the char from the keypad function.


text:
Trouble reading from multiple analog ports
So I'm trying to read 4 different analog values and store each one to a variable.  I imagine doing this by first initializing the ADC registers and each time it enters the ADC ISR checking which port it read from and saving it to the corresponding variable.  Then setting the ADMUX to the next ADC port and repeating the whole process.  Unfortunately something goes wonky and I just can't figure out what it is.  If I get rid of the switch case and just read from one port it all works fine, but if I put the switch case back in and try to cycle through them it stops working.  Please ignore the rest of code as this is not complete.  I just included everything I could.  Eventually this will take in 4 values.  Then use them for error checking and a PID loop.
Thanks for any help!
/*
 * Throttle_by_Wire.c
 *
 * Basic throttle by wire controller
 * for the 2015 Formula Hybrid car
 *
 *  Created on: Nov 24, 2014
 *  Author: Austin R. Bartz
 *
 *  Pin Connections:
 *      PB2 - Motor Speed (Enable pin) (PWM)
 *      PB4 - Direction control (Counter-Clockwise)
 *      PB5 - Direction control (Clockwise)
 *      PC0 - Throttle Pedal Sensor A (TPA) (Shallower Slope)
 *      PC1 - Throttle Pedal Sensor B (TPB) (Steeper Slope)
 *      PC2 - Throttle Valve Sensor A (TPSA) (Negative Slope)
 *      PC3 - Throttle Valve Sensor B (TPSB) (Positive Slope)
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <inttypes.h>
#include <stdlib.h>

uint16_t TPA = 0;
uint16_t TPB = 0;
uint16_t TPSA = 0;
uint16_t TPSB = 0;
uint16_t analogpin = 0;

long map(long x, long in_min, long in_max, long out_min, long out_max);

int main(void)
{
    //Configure ADC for single shot conversion
    ADMUX |= (1<<REFS0);
    ADCSRA = (1<<ADEN)|(1<<ADSC)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
    DIDR0 = (1<<ADC4D)|(1<<ADC3D)|(1<<ADC2D)|(1<<ADC1D)|(1<<ADC0D);
    //Configure timer/counter1 for FastPWM
    TCCR1A = (1<<COM1B1)|(1<<WGM11)|(1<<WGM10);
    TCCR1B = (1<<WGM13)|(1<<WGM12)|(1<<CS10);
    OCR1A = 800;    //20kHz
    //Set motor control pins as outputs
    DDRB = (1<<PB2)|(1<<PB4)|(1<<PB5);
    PORTB |= (1<<PB5);
    //Enable global variables and interrupts
    sei();

    while(1)
    {
        //Control PWM % to motor
        OCR1B = map(TPA, 0, 1023, 0, OCR1A);
    }
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

ISR(ADC_vect)
{
    //Save current conversion's ADC value
    analogpin = ADMUX & 0b00001111;
    switch (analogpin)
    {
    case 0:
        TPA = ADCW;
        //Increment ADC port to ADC1
        ADMUX |= (1<<MUX0);
        break;
    case 1:
        TPB = ADCW;
        //Increment ADC port ADC2
        ADMUX &= ~0b00001111;
        ADMUX |= (1<<MUX1);
        break;
    case 2:
        TPSA = ADCW;
        //Increment ADC port to ADC3
        ADMUX &= 0b00001111;
        ADMUX = (1<<MUX0)|(1<<MUX1);
        break;
    case 3:
        TPSB = ADCW;
        //Reset ADC Port to ADC0
        ADMUX &= ~0b00001111;
        break;
    }
    //Start next conversion
    ADCSRA |= (1<<ADSC);
}

Case 2 is missing the ~ and does not clear off the low 4 bits

ADMUX &= 0b00001111;

should be this to clear off the MUX selection bits:
ADMUX &= ~0b00001111;

Also, you have no default case.  I would agree that by design the bits can only contain the values 0-3, but what happens if it ends up 4?
The bit manipulation is hard to follow.  I would implement like this:
ISR(ADC_vect) {
  uint8_t nextMux;

  //Save current conversion's ADC value
  analogpin = ADMUX & 0b00001111;
  switch (analogpin) {
    case 0:
      TPA = ADCW;
      nextMux = (1<<MUX0);
      break;
    case 1:
      TPB = ADCW;
      nextMux = (1<<MUX1);
      break;
    case 2:
      TPSA = ADCW;
      nextMux = (1<<MUX0)|(1<<MUX1);
      break;
    case 3:
      TPSB = ADCW;
    default:
      nextMux = 0;
  }
  // set mux for next conversion
  ADMUX &= 0b11110000;
  ADMUX |= nextMux;

  //Start next conversion
  ADCSRA |= (1<<ADSC);

  return;
}

I like the consistent pattern of this because it makes errors easy to see.  With respect to code space, a few bytes should be saved.  Execution time wise, it adds one |= to the case 3.

I looked at the original, and gave up because frankly it is too hard to follow the code. If you followed better programming practice e.g. using a #define for ~0b00001111 it would be easier to follow (and less error prone).

@jdr5ca Thank you!  I changed the code to your suggested segment and it works perfectly now!  I apologize for the unclear bit manipulation.  I just started learning how to do all this last quarter (I'm a second year electrical engineering student) so it's still all relatively new to me.


text:
Can I use a UDOO as an Arduino?
I have a UDOO, and I wonder whether or not it is possible to use the Arduino that it has without starting the UDOO's operating system, i.e., I would like use Atmel Studio to load a program within the Arduino at UDOO.

Yes, but you have to erase the flash (and reset the ATMEL SAM3X8E processor) manually before the programming. You can use the J16 and J22 jumpers to do this.


text:
Arduino Uno + 2 Monster Motor Shields
I've got an Arduino Uno and two Sparkun's Monster Motor Shields.
The aim is to control 4 motors.
There is no problem to control 2 DC motors with single motor shield. There's a manual on how to do it .
But how can I control all of motors (address commands to each of them) when I stack motor shields one on one?
Thanks in advance.

I actually wouldn't stack them. Check which inputs you have on the boards and which outputs you'll take for them on your arduino. Then wire them seperately. Or you could put one in the arduino and wire the other induvidually. Why do you actually need two motor shields if I may ask?

I need a 4WD vehicle being able to carry 50 kgs of weight. Splitting this load between 4 wheel drives helps find cheaper DC motors with moderate characteristics. That's it. Any ideas?

You can make it 4WD with one motor shield. Use one output for the left side and one for the right side. And I guess you should then wire the motors parrallel as then they'll have their own power circuit.
This way you also avoid any possible driving mistakes, where you try to put both motors on one side against eachother.

can you please share the UNO to Monster Motor Shield pinout diagram please... and which Arduino code did you use with this combination? your help will be much appreciated. thanking you in advance.

A shield is simply a PCB that fits on an Arduino. You cannot stack them, because then they would use the same pin layout. Instead, connect each shield to different pins based on the requirements set in the documentation of the shield.

Not really the answer to your question, but an alternative solution, which has proven to work in my case.
We were working on a line-following robot with an ATMega 328P (Same as arduino, but withouth shields) and thus we wired an shield directly. For the shield we used, we only needed 4 inputs (pwm left, pwm right, direction left, direction right). Try to find out what your shield is using, on which pin, and you can drive the shield directly withouth stacking them (as they then would use the same pin).

My alternative solution would be to use 1 driver. And wire the motors parrallel.
If you choose to use 1 shield, you can stack it. But for other shields you have to check which pins to use. There is no drawback on using one shield, the only thing is that the motor driver will draw more current, but they're basically designed for this.

Thank you pals! I have just decided to refuse using 2 shields at the same time because of possible driving mistakes. Converting my device into a tank is indeed a solution. Well, at least it'll drive more predictably. Thank you all one more time :)

You don't actually need to use threads/tracks on your 'car' (though it does look cool). In our application it actually worked with 4 wheels.
Steering, would otherwise also need a servo.
Consider accepting this solution as an 'answer' by pressing the ✓


text:
Global Variable not able to be accessed in function?
I am trying to compile an Arduino program that takes analog input. However, when I declare multiple global variables, it often will not compile and because it throws an error that the variables aren't within scope of the functions within the program. I am not super familiar with Arduino IDE, but this doesn't programmatically make sense to me.
This is the program:
/*
*  By Hannah Perner-Wilson, www.plusea.at
*  Modified 3/30/2012 By Brian E Kaminski, www.AdvancerTechnologies.com
*
*  IMPORTANT!!:
*  Scroll down to set your serial port
*  Scroll down to set your thresholds
*/

import processing.serial.*;

// definition of window size
// you can change the size of the window as you like
// the thresholdGraph will be scaled to fit
// the optimal size for the thresholdGraph is 1000 x 400
int xWidth = 1200;
int yHeight = 750;

// xPos input array, using prefix
int[] xPosArr= {0,0,0,0,0,0};

//
int[] messageArr= {0,0,0,0,0,0};

// Arrays for threshholding
int[] threshMax= {0,0,0,0,0,0};
int[] threshMin= {0,0,0,0,0,0};

// variables for serial connection. portname and baudrate are user specific
Serial port1;

//Set your serial port here (look at list printed when you run the application once)
String V3 = Serial.list()[1];
String portname1 = V3;
int baudrate = 9600;

int prefix = 10001;
boolean myCatch = false;
String serialIN = "";
String serialINPUT = "";
String buffer = "";
int value = 0;

// ThresholdGraph draws grid and poti states
ThresholdGraph in;

void setup(){
  // set size and framerate
  size(xWidth, yHeight);
  frameRate(25);
  background(255);
  strokeWeight(5);
  stroke(0);
  smooth();
  strokeCap(ROUND);

  // establish serial port connection
  port1 = new Serial(this, portname1, baudrate);
  port1.bufferUntil('\n') ;
  println(Serial.list());  // print serial list

  // create DisplayItems object
  in = new ThresholdGraph();

  // THRESHOLD VALUES:
  // using the thresholdGraph you can determine the MIN and MAX values
  // of your sensors. Enter these here. They must lie between 0 and 1000.

    //MIN trashhold
    threshMin[0] = 20;   // one
    threshMin[1] = 20;   // two
    threshMin[2] = 20;   // three
    threshMin[3] = 20;   // four
    threshMin[4] = 20;   // five
    threshMin[5] = 20;   // six

    //MAX trashhold
    threshMax[0] = 600;   // one
    threshMax[1] = 600;   // two
    threshMax[2] = 600;   // three
    threshMax[3] = 600;   // four
    threshMax[4] = 600;   // five
    threshMax[5] = 600;   // six
}//end setup

// draw listens to serial port, draw
void draw(){

  // listen to serial port and trigger serial event
  while(port1.available() > 0){
        serialIN = port1.readStringUntil('\n');
        //println((int)float(serialIN));
        if(serialIN != "")
          serialEvent(serialIN);
        else
          Serial.println("found empty");
        }

  // threshold serial input
  threshHolding();

  // draw serial input
  in.update();
}//end draw()

The error that are being thrown are:
testproject.ino:100:17: error: 'threshHolding' was not declared in this scope
testproject.ino:103:3: error: 'in' was not declared in this scope
Error compiling.

Looks more like a Processing sketch. Where is the threshHolding function defined? (PS threshHolding and in are functions, not variables)

Agreed. It looks like that's a Processing sketch which was written to communicate with an Arduino. Perhaps the wrong code was added to the question?

I thought that "processing.serial" does not need to be imported in a .ino code?

Can anyone answer why that has been written ?

@Gerben , Do you know why?

Or @PeterR.Bloomfield , do you know?

@Mathsman100 It's there because this is a Processing sketch, not Arduino. import is a Java keyword which doesn't exist in C++, so it won't work in the Arduino IDE.

@PeterR.Bloomfield ,   But I thought the sketch is saved as a .ino, so it should work just like one that is written using Arduino IDE?

@Mathsman100 It's not really feasible to convert Java code to C++ automatically for microcontroller programming. The result would probably be very inefficient at best.

The @rsheeler might have done a mistake in that part.

The problem is that this is not an Arduino Sketch, but a processing file which is noted by the initial import statement that is Java based. Because the Arduino IDE is not very sophisticated, it didn't shout out obvious errors such as import type not defined or even ThresholdGraph not defined.
To use this file it is necessary to use the following IDE: https://processing.org/reference/environment/