text:
UART communication - Serial is always empty
I have a payment terminal which uses UART (or simply speaking Rx, Tx, Gnd pins) and I have an Android tablet app which is connected to the terminal using USB to DB9 adapter based on PL2303 chip. The Android app works well and it uses https://github.com/felHR85/UsbSerial to support serial communication. The protocol is very simple, basically Android sends strings like "REQINFO,4", "L2,xxx,xxx,*" etc. and recieves back a string statuses.
I'm trying to replace Android app with Arduino UNO, for which I naively assumed would be enough just to connect Tx,Rx of the terminal with Rx,Tx pins of the Arduino and also to connect Gnd pins. But I can't get it working. The only thing I noticed is when I connect Arduino Rx to terminal Tx, the terminal's screens briefly shows "Connecting..." but that's probably because it detects some incoming voltage. When it comes to reading Serial (or also I tried SoftwareSerial) nothing is ever returned.
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
    } else {
      data += c;
    }
  }
}

So do I miss anyting in order to have a proper communication? Thanks.

It seems this package supports various methods of flow control (for example rts/dts and others) these are used by the two devices to coordinate communications. If your terminal is setup to use flow control, then you will have to add more to your arduino code to support it depending upon the nature of the flow control. You should also consider the message format (parity, start/stop bits and baud rate). https://github.com/felHR85/UsbSerial/wiki/4.-Asynchronous-api

@GMc In the Android code flow control set to NONE, so I presume I can ignore that. Also, just for test I disconnected DB9 from the terminal COM port and connected just Rx,Tx pins and everything continued to function.

Check (e.g. with a multimeter) the DB9 voltages! Mostly RS-232 is used on those kind of connectors with voltages +-12Volts (there are other variants as well, up to 15V), but your Arduino's UART uses TTL levels (0V as logic low or 5V as high on a 5V Arduino). You'll need to convert these, possibly with a chip like MAX232 or similar.
Also, for reverse engineering this I recommend using an Arduino with multiple serial ports (e.g. Mega), or at least multiple software serials (with proper level shifting of course). You connect your Android tablet to your reader through your Arduino, and when you receive a byte from one device, send it to the other one, and also send it to your PC along with the information about direction. This way you can understand all the used commands if you sniff long enough. You could also use an SD card on SPI if you need your sniffer system to be mobile (walking in a warehouse scanning items).
If you have access to a logic analyzer, it can also be used as a sniffer. This has an additional advantage, you can change BAUD rates later if your guess was wrong.
(started as a comment but ran out of characters, so I thought I'll explain it a bit more)
https://www.db9-pinout.com/db9-pinout/db9-pinout.gif
If it's a standard cable for RS-232, this diagram shows which pin is which. DCE-DCE and DCE-DTE cables were different back then (one connects a PC to a modem, the other 2 PCs), so you should check both voltages from 5 (GND) to either 2 or 3. An empty line has logic high, which is 5V in case it uses TTL, and -5 or lower (like -12 or -15) for RS-232.
Test different BAUD rates as well!

I'm pretty sure that whole system functioning using 5V but indeed it's a good idea to doublecheck that. Regarding sniffing, I actually tried something similar by connecting my Arduino to the tablet and staring into monitor window. For some reason that didn't show me any info either.

So, are you suggesting to try a TTL adapter like this -https://m.ebay.co.uk/itm/MAX232-RS232-Serial-to-TTL-Converter-Board-PIC-Adapter/302506517436?ul_ref=https://rover.ebay.com/rover/1/710-53481-19255-0/1?ff3=2&pub=5575376664&toolid=10001&campid=5338268676&customid=CjwKCAjw5_DsBRBPEiwAIEDRWzVL2-w0CSoRPVgEt5tSf8n21N6NC2qCud08araW72RE16h-KPUeZBoC6nwQAvD_BwE&lgeo=1&item=302506517436&srcrot=710-53481-19255-0&rvr_id=2136994577017&rvr_ts=aa3a806616d0a16ef8f4118afffc2a78&_mwBanner=1&_rdt=1&ul_noapp=true&pageci=c3e011ca-5fb3-4b66-b4f0-c31215a3f717 ?

That hardware would do it, yes. You might need 2 of them, one to the tablet, and one for the reader. But first, check the voltages!

today I tried your suggestion with TTL converter and indeed it works well. Now I can sniff data coming from tablet to Arduino. I used Arduino Mega so I hooked terminal to Rx2,Tx2. But for some reason attaching another TTL on between these pins and the terminal didn't bring any value. I wonder do I need it at all, as without TTL for terminal I can at leat recieve some gibberish -- ⸮⸮i⸮v맧⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮u[[⸮⸮_gu}Yu⸮Yucw⸮}⸮gaqmc⸮[uya[w⸮⸮ possible there's a way to adjust something (baud rate?) to see real content. Anyway thanks, you helped me a lot!

If you have access to - even a cheap ($8) - logic analyzer, you can determine the speed. Or you can test common baud values. You can also send to your PC hex values, the data might be binary, and it'll stay gibberish, even when the settings are right.

actually I managed to achieve what I wanted, so two TTLs were necessary. Used this little app to communicate over Serial port on Windows machine: http://www.hobbytronics.co.uk/ht-comm.  And I laughed when reaized what caused the gibberish problem - weak contact. Soldering solved it completely. Thank you, mate!

There is already an answer and comment about possible hardware / flow control issues, so this answer is only dealing with your Arduino sketch. Iv’e added a couple of print statements and the FreeMemory library to test your sketch.
#include <MemoryFree.h>
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    } else {
      data += c;
    }
  }
}

When I repeatedly enter the following text in the serial monitor "1234567890", here is the results of the print statements:
REQINFO,4
1234567890
freeMemory()=1770
1234567890
freeMemory()=1770
12345678901234567890
freeMemory()=1760
12345678901234567890
freeMemory()=1760
123456789012345678901234567890
freeMemory()=1750
123456789012345678901234567890
freeMemory()=1750
1234567890123456789012345678901234567890
freeMemory()=1740
1234567890123456789012345678901234567890
freeMemory()=1740
12345678901234567890123456789012345678901234567890

Every time you receive new data, it is appended to the data string, causing the string to grow and available memory to disappear. Using the String object should be avoided.
Here is a simple sketch that uses a char array as a buffer for the incoming data:
// Set the buffer size to accomodate the largest
// "chunk" of data you will be receiving.
const byte bufferSize = 64;
char inputBuffer[bufferSize + 1];

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

void loop(){
  if(Serial.available() > 0){
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    Serial.print("inputBuffer=");
    Serial.println(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}

Ah, yeah that sketch is just to test the communication is possible in general. But nonetheless, appreciate your input.


text:
Possible to have different torque levels on MG966R servo with Rotary Potentiometer?
I want to apologise first and foremost, and say that I am very new to Arduinos!
I wanted to control the torque on a MG966R servo so that I can separate it into 4 different torque levels. I read that by adjusting the input voltage, you can run the servo at different speed, hence, i was thinking if I could incorporate a rotary potentiometer to adjust the speed of the servo.
Also wondering if changing angle stepsize of MG966R servo will affect torque in anyway?
Thanks all!

Generally it is not easy to control the torque of a standard servo, since mostly they aren't meant for that. A servo has an internal controller, which will read the input PWM signal and control the geared motor, so that the desired position will be reached. And to get there, the most servos will use the maximum torque. Also the torque of a servo motor depends on more variables, for example speed and type of load (See here for more information about this.

I read that by adjusting the input voltage, you can run the servo at different speed

That's not really true. Most servos only support a rather small voltage range, where they will work. You can get more torque, if you use a higher voltage, but it is not a simple linear relationship, since the torque depends on way more variables. One way may be to always drive the servo to it's current maximum torque and change this maximum torque by changing the input voltage inside the working range. Though this might not get you 4 torque levels, that are different enough for you.

Also wondering if changing angle stepsize of MG966R servo will affect torque in anyway?

It is unclear, what exactly you mean by "stepsize" here. If you mean to control the speed of the servo: Yes, it will affect the torque, but not in a linear way. And this greatly depends on the load, that you apply.
In the answer to this question, sensing the current of the servo is suggested as a measurement of (applied) torque. If you use a feedback loop with this, you might be able to control the (applied) torque. I haven't done this kind of thing, so I'm not sure, if this can really work.

That said, you should again think about wether a normal servo is really the best way to go here, since it controls electronics, that you don't control yourself. For example you may use a geared DC motor, which you can directly control without any other electronics getting in your way.

source: Stack Exchange

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

sort: votes


text:
Which sources of randomness are available?
I need a souce of randomness to generate a seed to pass to randomSeed. Where can I get this randomness from?
Well, I hear I can read random noise from an unconnected pin.
But I need to connect 9 LEDs and 9 buttons to the board. There seem to be enough pins for this purpose: digital pins 2-13 + analog pins 0-5 makes a total of 18 pins. But does this leave any free pin for a source of randomness?
There are digital pins 0 and 1 left free but I'm reading these should be left free if the board's USB socket is connected and I'm planning to power the whole device by connecting it to a computer through USB. Does this mean I'm supposed to just left pins 0 and 1 unconnected or is it also forbidden to read noise from them?
Or are there any other available sources of randomness? Can I use any other pins for this purpose?
I remember when I was showing this project to the instructor I specifically asked if I have enough pins, noting that I need a source of randomness in addition to 9 LEDs and 9 buttons. He said there are enough pins. Only sadly I forgot to ask how can I read random noise then...
What are my options to somehow obtain a random seed?

i would use the timing of your button presses to mix the internal seed state.

@dandavis sadly I need to generate random numbers BEFORE the user is supposed to press any buttons.

you should use EEPROM to store the seed so that you eliminate the "no ent on boot" problem inherent in PRNGs. Readup on the fortuna algo on wiki for more info. You don't need to go THAT fancy, but applying some of the principles will solve your issue. You can also set the pins as analog inputs right away, scan them a few times, then set them back up as your device needs to run. You won't get a whole lot, but every bit (literally) counts.

@dandavis Oh my... I definitely don't need cryptographical security :)

here is an interesting video https://m.youtube.com/watch?v=1cUUfMeOijg

I get why this was closed as a duplicate, but you can also free up a good number of pins by using a shift register to control 8 of your LEDSs. https://learn.sparkfun.com/tutorials/shift-registers/all

Whether you need a source of random noise depends on whether your project needs to not run repeatably. Most experiments - Monte-Carlo simulations, for example, benefit by being able to be re-run. In those cases, you need to be able to re-use the seed, and having an non-reproducible seed (and thus, experiment) is a disadvantage.
If you really need something that runs differently each time you run it, then a seed derived from user reaction time, or from some kind of electrical noise, even reading analog values from a floating input pin, should give you plenty of non-reproducibility.

brilliant: get the seeds from the environment.  one can always use millis() as part of the seed as well.

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


text:
What is the difference between Nano 328p-au and 328p-mu?
What is the difference between Nano 328p-au and 328p-mu? Does it have to do with the updated bootloader or is it just a different board design? I want to make sure I order the correct one and I could not find a proper answer so far. Thanks.

The only difference is the MCU package. If you're ordering the pre-assembled Nano boards, it makes no practical difference.

The AU and MU on the chip just refer to the shape of the chip. AU is TQFP and MU is VQFN.
You can see the full list of suffixes here (select the red "Buy Now" tab for a table).


text:
Software I2C - sending data
I'm trying to read a voltage in from a power supply to an Arduino Micro, then send it to an oscilloscope through an I2C (MCP4725). I would use the default pins on the Micro but I want to wire three I2C and the default bus only allows two. As such, I'm trying to use the SoftI2CMaster library
I've looked through examples and documentation but I can't seem to get it to send any data. I've been successful scanning (from examples) and finding the I2C addresses, so I assume that the trouble is at the end of my code.
Any tips would be greatly appreciated!
#define SDA_PORT PORTD
#define SDA_PIN 4 // = A4
#define SCL_PORT PORTC
#define SCL_PIN 6 // = A5
#include <SoftWire.h>

#define I2C_7BITADDR 0x62 //MCP4725

SoftWire Wire = SoftWire();

int aPin;

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

void loop(void){
  aPin = analogRead(A0); //read in from power supply
  Wire.beginTransmission(I2C_7BITADDR);
  Wire.write(aPin); //send voltage to osc.
  Wire.endTransmission();
}

The main problem seems to be, that you are not adhering to the MCP's communication protocol. You just try to directly and only send the pure analog measurement to it.
Look at this image from page 18 of the MCP4725's datasheet:

It describes the operation is Fast Mode, which seems to be the correct mode for this. (Similar descriptions for the other modes can be found below that image). The first byte is done by the SoftWire library, but the following is your responsibility. The
next 2 bytes consist (in this order) of 2 bit's setting the Fast Mode, 2 bit's for the devices power down select (both zero for normal DAC operation) and then the 12 bits of the actual voltage value for the DAC.
At this point I will show another problem with your code. You read an analog voltage with the Arduinos ADC, which is a 10 bit number (of type int) and use it in
Wire.write(aPin);

But the parameter for Wire.write() is defined as uint8_t (see line92 in SoftWire.h of the Softwire library), which means, that your int value get's casted and you loose all bits above 255 (the lower byte), because uint8_t just cannot store more.
What you have to do: You should put the I2C data bytes together in your code and then send them. This may look like this:
byte byte1 = (aPin & 0x0F00) >> 8;
byte byte2 = (aPin & 0xFF);

This code uses bitwise operators. The & will do an AND operation, the >> shifts the bits to the right by the amount after the operator. The 0x denotes a value in hex representation (binary representation would be 0b). So for the first byte we are doing an AND with the value 0x0F00, which will give us a value with only the first 4 bits of the second byte of aPin. Then we shift the result 8 bits to the right, so that the remaining data is nicely aligned to the right of your byte. We don't need to include the mode bits and power down select bits here, since they are zero anyway. If you want to set them non-zero you could bitwise OR them (of course with the correct shift, so that the bits have the correct position in the resulting byte):
byte mode_bits = 0b10;
byte power_down_bits = 0b11;
byte byte1 = (mode_bits << 6) | (power_down_bits << 4) | (aPin & 0x0F00) >> 8;

Then you can send these bytes out with I2C:
Wire.beginTransmission(I2C_7BITADDR);
Wire.write(byte1);
Wire.write(byte2);
Wire.endTransmission();

That should work, though note, that I have not tested this. I just read the datasheet, which is always a must read.
What happened with your original code: The datasheet states for the command "Write DAC Register" (which uses 4 bytes including the address byte) the following:

The device ignores any partially received data  bytes  if  the  I2C
  communication with the Master ends before completing the 4th byte.

So it just drops any I2C messages, that are not complete. Though it is not stated clearly, we can be pretty sure, that the same happens also for the other operation modes. You were sending only 1 byte, so the MCP found the message incomplete and ignored it.

That said, there is a principle to work around the limit of only 2 devices on the same bus, which I also only learned recently about. You might not wanna go this way here, but it's a great idea and a valid solution to the problem with the limit.
Every MCP has 1 address pin A0, which set's 1 bit of the address, resulting in 2 possible addresses. On an I2C bus there must not be more than 1 device with the same address. But if that doubled address is never called, the bus doesn't have a problem.
You would connect the A0 pins of each MCP to one digital output pin of the Arduino each. By setting the state of these output pins you can change the address of the MCPs (requirement is, that the MCP actually checks the A0 pin during operation, but the datasheet seems to suggest this). Now you keep every A0 pin on one level, so that all MCPs have the same address. To communicate with one, you would change the state of it's A0 pin to change it's address. Now this MCP is the only MCP with this address (all other MCPs have the other address). You can now communicate with it. When you want to communicate with another MCP, you reset the first MCPs A0 pin and then change the next MCPs A0 pin.
That way you make sure, that on one of the two addresses, there will always be 1 MCP at maximum, while you never use the other address. You can use as many MCPs, as you have digital output pins to change their addresses.

yes! you legend! worked perfectly. thank you so much for the well written response. i really appreciated the breakdown of why my code wouldn't work.


text:
Arduino digital pin status not transmitting via NRF24L01 where as analog pin status is getting transmitted ,Why?
I am currently working with a project using NRF24L01 which I integrated with my Joystick so that I can make it wireless.While transmitting the information in my Joystick to the receiver only analog pin status is getting transmitted where as digital pin status is not getting transmitted.
Transmitter Code:

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include <Wire.h>

//Define the digital inputs
#define tGL1 7
#define tGL2 6
#define b1 5
#define b2 4
#define b3 3
#define b4 2

const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY;
float angleX, angleY;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY;
float elapsedTime, currentTime, previousTime;
int c = 0;

RF24 radio(9,10);
const byte address[6]="00001";

struct Data_Package {
  byte j1PotX;
  byte j1PotY;
  byte j2PotX;
  byte j2PotY;
  byte button1;
  byte button2;
  byte button3;
  byte button4;
  byte tSwitch1;
  byte tSwitch2;
  byte pot1;
  byte pot2;
};

Data_Package data;

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);

  pinMode(tGL1, INPUT_PULLUP);
  pinMode(tGL2, INPUT_PULLUP);
  pinMode(b1, INPUT_PULLUP);
  pinMode(b2, INPUT_PULLUP);
  pinMode(b3, INPUT_PULLUP);
  pinMode(b4, INPUT_PULLUP);

   data.j1PotX = 127; // Values from 0 to 255. When Joystick is in resting position, the value is in the middle, or 127. We actually map the pot value from 0 to 1023 to 0 to 255 because that's one BYTE value
   data.j1PotY = 127;
   data.j2PotX = 127;
    data.j2PotY = 127;
//  data.j1Button = 1;
//  data.j2Button = 1;
  data.pot1 = 1;
  data.pot2 = 1;
  data.tSwitch1 = 1;
  data.tSwitch2 = 1;
  data.button1 = 1;
  data.button2 = 1;
  data.button3 = 1;
  data.button4 = 1;

}

void loop() {
  // put your main code here, to run repeatedly:
  data.j1PotX = map(analogRead(A2), 0, 1023, 0, 255); // Convert the analog read value from 0 to 1023 into a BYTE value from 0 to 255
  data.j1PotY = map(analogRead(A1), 0, 1023, 0, 255);
  data.j2PotX = map(analogRead(A3), 0, 1023, 0, 255);
  data.j2PotY = map(analogRead(A0), 0, 1023, 0, 255);
  data.pot1 = map(analogRead(A7), 0, 1023, 0, 255);
  data.pot2 = map(analogRead(A6), 0, 1023, 0, 255);

  data.tSwitch2 = digitalRead(tGL2);

  data.button1 = digitalRead(b1);
  data.button2 = digitalRead(b2);
  data.button3 = digitalRead(b3);
  data.button4 = digitalRead(b4);

  if (digitalRead(tGL1) == 0) {
    read_IMU();    // Use MPU6050 instead of Joystick 1 for controling left, right, forward and backward movements
  }

  radio.write(&data, sizeof(Data_Package));
}

This is the Reciever Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);   // nRF24L01 (CE, CSN)
const byte address[6] = "00001";
unsigned long lastReceiveTime = 0;
unsigned long currentTime = 0;
// Max size of this struct is 32 bytes - NRF24L01 buffer limit
struct Data_Package {
  byte j1PotX;
  byte j1PotY;
  byte j2PotX;
  byte j2PotY;
  byte pot1;
  byte pot2;
  byte tSwitch1;
  byte tSwitch2;
  byte button1;
  byte button2;
  byte button3;
  byte button4;
};
Data_Package data; //Create a variable with the above structure
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_LOW);
  radio.startListening(); //  Set the module as receiver
  resetData();
}
void loop() {
  // Check whether there is data to be received
  if (radio.available()) {
    radio.read(&data, sizeof(Data_Package)); // Read the whole data and store it into the 'data' structure
    lastReceiveTime = millis(); // At this moment we have received the data
  }
  // Check whether we keep receving data, or we have a connection between the two modules
  currentTime = millis();
  if ( currentTime - lastReceiveTime > 1000 ) { // If current time is more then 1 second since we have recived the last data, that means we have lost connection
    resetData(); // If connection is lost, reset the data. It prevents unwanted behavior, for example if a drone has a throttle up and we lose connection, it can keep flying unless we reset the values
  }
  // Print the data in the Serial Monitor
  Serial.print("j1PotX: ");
  Serial.print(data.j1PotX);
  Serial.print("; j1PotY: ");
  Serial.print(data.j1PotY);
  Serial.print("; button1: ");
  Serial.print(data.button1);
  Serial.print("; j2PotX: ");
  Serial.println(data.j2PotX);
}

When I print the status of the buttons and Joystick in my transmitter(Joystick) I get the correct status of my push button when I press but the status of my push button remain unchanged in the Serial monitor of my Receiver despite there is change other values (I mean the analog value is transmitting correctly)
This the screenshot of my both serial Monitor

Hint: A common header file with the message struct would help avoid this issue. The layout of the struct's are not the same :)

As Mikael Patel mentions in the comments: your structures do not match between the transmitter and receiver.
Transmitter               Receiver
=====================     =====================
struct Data_Package {     struct Data_Package {
      byte j1PotX;    ->      byte j1PotX;
      byte j1PotY;    ->      byte j1PotY;
      byte j2PotX;    ->      byte j2PotX;
      byte j2PotY;    ->      byte j2PotY;
      byte button1;   ->      byte pot1;
      byte button2;   ->      byte pot2;
      byte button3;   ->      byte tSwitch1;
      byte button4;   ->      byte tSwitch2;
      byte tSwitch1;  ->      byte button1;
      byte tSwitch2;  ->      byte button2;
      byte pot1;      ->      byte button3;
      byte pot2;      ->      byte button4;
};                        };

With structures, what matters is not what each field is called. What matters is the position of the fields in the list.  When you compile your code all the names are lost. All that is left is where in the list each entry is.
The best way of avoiding this problem is to have a single header file (make it a library so it's easy to share) that contains the packet structure. Then if you ever make any changes to the packet all the sketches that use it see that change the next time you compile them.

Does that mean I have to make an file with .h extension and then import them using #include

Yes. If you make that file as Documents\Arduino\libraries\PacketFormat\PacketFormat.h then you can just #include <PacketFormat.h> in any sketch to get the structure.


text:
Why does SoftwareSerial::read() return int?
The documentation on Arduino's website shows SoftwareSerial::read() as returning a char. (link)
The header shows that the method returns an int. (link)
The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values. (link)
Given all of this:

Why would the interface return an int instead of a uint8_t?
Why do the Arduino docs show it as returning a char?
Is it safe to send/receive 8-bits at a time using this library?

For (3) I'm using an HC-06 if that matters.

You'll see in the code just above your third link that the function can return a value of -1 if there is no data present. Thus a 16-bit value is used to cover the range of 8-bit uint8_ts, plus one extra value to show 'no valid data available'.
For simplicity, I guess.
Yes. This is what it's designed for.

In short, for all intents and purposes, only an 8-bit value is returned, but if you were to read into an int, you couldn't differentiate between a valid and invalid value.

Ah awesome! The -1 value makes sense.
So assuming I gate the read() invocation w/ available(), it sounds like I can read it into a uint8_t directly and work with it as a true byte.

All the applications I've seen (for all stream type objects) is if(available()){read();}. The code you linked to reads the data from the ring buffer into a temporary uint8_t before returning into an int, so you're not going to lose any data that way

The actual answer to number 2 is "Because, as in many instances, the Arduino documentation is complete garbage."

I'm a bit surprised no-one mentioned the fact that it's the exact same reason why getchar() and friends return an int in standard C.

The documentation on Arduino's website shows SoftwareSerial::read() as returning a char.

No it doesn't. There is nothing in the documentation that tells you the return type. There is only an example where the returned value is assigned to a char variable. That doesn't mean that it returns a char - it just means that whatever data type it does return can be invisibly cast to a char by the compiler.

The header shows that the method returns an int.

Indeed it does. That is because that is what it returns.

The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values.

Yes, because the valid data that it deals with is 8 bits in size. Just because it handles 8 bit "valid" data doesn't mean that that's all it ever wants to return.  The "no data available" return value of -1 is obviously not something that is stored in the data. It's a status, not data.

Why would the interface return an int instead of a uint8_t?

Because a uint8_t cannot encompass all the functionality stated in the "Returns" section:

the character read, or -1 if none is available

You can't return -1 in a uint8_t.

Why do the Arduino docs show it as returning a char?

It doesn't - as I mentioned above. It makes no claims at all about the returned data type.

Is it safe to send/receive 8-bits at a time using this library?

Yes. It performs serial data transfers using 8-N-1 by default. That's 8 data bits, no parity, and one stop bit.

It's this kind of confusion with return types and bytes and integers and things that make people ask why they keep getting ÿÿÿÿÿÿ on the serial monitor. That's -1 cast as a char. I.e., "no data available" but they ignore that and treat everything returned as a char - most probably because the Arduino documentation shows an overly simplified example that ignores the possibility of a -1 being returned and treats everything as a char.
IMHO much of the Arduino documentation is somewhat sub-par and should not be taken literally - only as a rough guide for what is available. The same goes for much of their example code and projects.

There is hope though, as it seems the Arduino documentation is in the process of being refactored. The documentation for Serial.read(), which comes from the new GitHub-hosted ASCII doc-based repository, clearly states “Data type: int.” The documentation for SoftwareSerial is still in the old format and has presumably not been migrated yet.

@EdgarBonet That's promising. Maybe they'll do the same with all the bad schematics and example projects...

Stream declares read as returning int (look in hardware/arduino/avr/cores/arduino/Stream.h). SofrtwareSerial inherits from Stream, so they have to override that declaration, otherwise there would be two read() methods, one returning int and one returning uint8_t. Since SoftwareSerial::read() would onlyreturn an int between 0 and 255, which would fit in a uint8_t, there is no problem.
As for the Arduino docs, you get what you pay for :)

many words, no answer. the reason of int is to return -1 meaning "no data to return".


text:
Can you start/stop a code from the serial monitor?
pressing and number in the serial monitor to start code and stop code.

I'm glad that you got a satisfying answer, but note that questions like yours are often quickly closed and deleted as low quality. I hope you'll do a better job next time.

@DmitryGrigoryev o and a k

This can be done by using the Serial.read()command as referenced in the Arduino documentation here.
Below is an example of how you might apply this.

/**
 * NAME: Serial interupt
 * DATE: 18/7/19
 * AUTHOR: Jeremy Fox
 * DESCRIPTION:
 *    FLashes LED until recives enter keystroke from serial monitor.
 */
int incomingByte = 0; // for incoming serial data
int LED = 13; // defines the LED to flash
boolean flash = true; // for flashing loop

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  while (flash == true){
    // flash LED
    digitalWrite(LED, HIGH);
    delay(100);
    digitalWrite(LED, LOW);
    delay(100);
  }

  // record data if available:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();
  }

  // checks if enter key was pressed:
  if (incomingByte == 13) {
    flash = true; // enter loop
    incomingByte = 1; // reset incomingByte to avoid feedback loop
  }
}

does the code runs continuously after inputting the command or it only runs once?

It runs continuously.


text:
Making a PID Controller for BAR 30 pressure sensor
I am having issues with my PID controller  for a BAR 30 depth sensor. The issue that I have is my ESC have two initial start up { 1500 - 1900} is min - max respectively clockwise and { 1500-1900} is max respectively counter clockwise.
What I want is for me to set a depth and I can submerge to a certain depth and lock in at that certain depth.
#include <PID_v1.h>
#include <MS5837.h>
#include <Wire.h>
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster1;

// Variables

float current_depth ;
float set_depth = 0.50 ; //  depth u wish to go in meters
float PID_error = 0;
float previous_error = 0;
float elapsedTime,  Time , timePrev;
double pwmvertical_thruster1 = 1440;

int s;

float PID_value = 0;
float PID_p = 0;
float PID_d = 0;
float PID_i = 0;
//PID constants
float kp = 100;
float ki = 0.003;
float kd = 5.2;

void setup() {
  Serial.begin(9600);
 vertical_thruster1.attach(4);
   vertical_thruster1.writeMicroseconds(1500);

 Time = millis ();

 ///Bar 30 Configuration

  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
Serial.println("Init failed!");
Serial.println("Are SDA/SCL connected correctly?");
Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
Serial.println("\n\n\n");
delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

///*
// First read the current value of the depth sensor
sensor.read();
current_depth = sensor.depth();

timePrev = Time;
Time= millis();
elapsedTime = ( Time - timePrev) / 1000;

// calculate the error between the set depth and current depth
 PID_error =  set_depth - current_depth ;

 // Calculate the P Value
 PID_p = kp * PID_error;
   Serial.print("PID_p: ");
    Serial.print(PID_p);
    Serial. println ( "\t\t");
// Calculate the i value in a range on +-0.3

 if (-0.2 < PID_error < 0.2)
 {
  PID_i = PID_i + (ki * PID_error);
 }
Serial.print("PID_i: ");
Serial.print(PID_i);
Serial. println ( "\t\t");
// Calculate the d value
 PID_d = kd*((PID_error - previous_error)/elapsedTime);
Serial.print("PID_d: ");
Serial.print(PID_d);
Serial. println ( "\t\t");
// The total PID value
PID_value = (PID_p + PID_i + PID_d) ;

// range for the blue robotics esc

if ( PID_value < -150)
 {
 PID_value = -150;
  }
  if( PID_value >150)
  {
  PID_value = 150;

  }
  Serial.print("PID_value: ");
  Serial.print(PID_value);
  Serial. println ( "\t\t");
 // calcualte the pwm

 s =  (pwmvertical_thruster1 + PID_value  );
 if(s < 1350)
{
 s= 1450;

}
else if(s> 1650)
{
  s=1550;

}
  Serial.print("Depth: ");
  Serial.print(sensor.depth());
  Serial.println(" m");
  Serial.print ( "Speed s  ");
  vertical_thruster1.writeMicroseconds(s);
  Serial.print( s) ;
  Serial. println ( "\t\t");
  previous_error = PID_error;
  //  */
  delay(300);
 }

A PID controller should be a good match for your application, but it appears that your code doesn't take advantage of the PID_v1 library at all; a PID_v1 object is never declared, and it appears you are attempting to manually compute what the PID library is designed to do for you automatically.
I would recommend you 'start slow and simple' by learning how to use a PID controller in its most basic form.  The PID library has a very basic example, which I have modified slightly to demonstrate how a PID controller works.  I tested this example with a UNO, a potentiometer (variable resistor) and a capacitor. The resistor and capacitor values aren't critical - I used the first things I found in my parts box.  The output on Pin 3 is a PWM pulse train signal, and the resistor/capacitor combination filters this pulse train to a variable level analog signal, which the PID controller sees as the analog 'Input' on A5.
Once you have this running, you can vary the pot value to see how the PID changes the output value in order to achieve the setpoint value on the input, and you can vary the setpoint and PID parameters to play around with different configurations.  Once you are comfortable with basic PID operation, you should then be able to configure it properly for your application.
Hope this helps,
#include <PID.h>

 //Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, 2, 5, 1, DIRECT);

void setup()
{
    Serial.begin(115200);

    //initialize the variables we're linked to
    //Input = analogRead(0);
    Input = analogRead(A5);  //I used A5 as A0 was unavailable
    Setpoint = 100;

    //turn the PID on
    myPID.SetMode(AUTOMATIC);
}

void loop()
{
    //Input = analogRead(0);
    Input = analogRead(A5); //I used A5 as A0 was unavailable
    myPID.Compute();
    analogWrite(3, Output);
    Serial.print("Input = "); Serial.print(Input); Serial.print(", Output = "); Serial.println(Output);
    delay(100);

}


text:
Do You Put a Break after the Last case in a Switch?
The Arduino Switch Case Reference has a switch structure written two different ways:
First in the Syntax as:
switch (var) {
  case label1:
    // statements
    break;
  case label2:
    // statements
    break;
  default:
    // statements
}

and then in the Example code as:
  switch (var) {
    case 1:
      //do something when var equals 1
      break;
    case 2:
      //do something when var equals 2
      break;
    default:
      // if nothing else matches, do the default
      // default is optional
      break;
  }

Is there any reason to (or not to) add a break; in the default: case? Does the need for 'break;' change if the final case is not default:?

This isn't an Arduino specific question and it was already answered on SO.

break is an exit command, since the loop is exiting anyway, you do not need it ..... you should use it though because you may cut/paste code, or add another case statement after the last case statement, and also to form a habit to use it in case statements in general

I'd like to argue that this is Arduino specific because not all C++ rules apply to an Arduino. For example, the lack of an exception system prevents Try and catch.

You can, but you don't have to.
Should you? That's up to you.
I do. That's because it's then simple to add another case at the end of the structure in the future if you want, and you don't have to remember to add the break to the existing last case.


text:
Open Parent Class as Child Class (SD Fat Library)
I'm currently using the SDFat library and am passing a global FatFile

I if have a function that requires an SdFile type and I know that a given instance of FatFile is a valid SdFile what is the best way to reopen FatFile F as SdFile J?
Right now I'm doing:
SdFile ActiveFile;  //Global Active File
...
void SDRun (FatFile &RunFat)
{
  SdFile RunRoot;
  RunRoot.open("/", O_READ);
  ActiveFile.close();
  ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
  ....

However, this only works when RunFat is in the root directory.

If RunFat is an instance of SdFile you can just cast it:
SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

RunRoot and RunFat are now the exact same file in the exact same state (no need to open it or anything) but seen as an SdFile not a FatFile.

Ok, doing SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat); I get an error cannot dynamic_cast 'RunFat' (of type 'class FatFile') to type 'class SdFile&' (source type is not polymorphic)

Did you make sure you got all the & in the right places?

I have, I've also tried a few variants, but the dynamic cast continues to give me a source type is not polymorphic error.

Maybe it's not a proper child->parent relationship then. Or it's not really a class, or something?

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


text:
Make Sure Digital pin is high before Serial.write()
I have the following code for a TTL to RS-485 Adapter Module
[...code]
digitalWrite(DE_PIN, HIGH); //directional control for adapter
Serial2.write(Message, Size);
Serial2.flush();
digitalWrite(DE_PIN, LOW);  // Set To Recieve
Serial2_reading_foo();
[code...]

I've noticed that DE_PIN does not seem to go High fast enough before Serial2.write() executes I confirmed this by adding a small delay(ms) which made the code function perfectly.
digitalWrite(DE_PIN, HIGH);
delay(100);
Serial2.write(Message, Size);
Serial2.flush();
digitalWrite(DE_PIN, LOW);  // Set To Recieve
delay(100);
Serial2_reading_foo();

Unfortunately, there's pretty much universal agreement that you shouldn't ever use delay() in programming. Plus doing any kind of wait function here seems to be insensitive to the real problem. Is there a better way to make sure that DE_PIN==HIGH before the Serial2.write() Function begins?

Short delays are fine. Consider using delayMicroseconds() and tuning it for the minimum delay that achieves what you want.

what is the actual time interval you need? 0.1 s is pretty long for circuits.

I don't know the true interval. Is there any good way to get it mathematically, or is it just guess and check?

check the spec sheet of the module

I couldn't find the spec sheet, but with guess and check, 9ms seems to be the magic number. Is that about right?

How can you not find the spec sheet? It's the first hit in google for MAX485 - or you go to Maxim's website, look for the MAX485, and click on the datasheet. Anyway, the maximum time you should need is a mere 50ns. Do you have the DE and RE pins tied together?

The Arduino's IO pins, with no pin load, takes 10.4ns to rise to the 2V needed to register as a HIGH on the DE pin. One clock cycle on the Arduino is 63ns, which is longer than the propagation time for DE. No delay should be needed.

It sounds like the problem is elsewhere.  Try moving the same amount of delay elsewhere in the loop - maybe what you actually have is a serial message rate or pacing problem.  What is your success/failure verification - are you actually looking at the RS485 on a scope, or are you counting on the unspecified piece of connecting equipment to serially respond or behave in some way as a result??

The MAX485 requires 2V on the DE pin to register a HIGH. It takes no more than an absolute maximum of 50ns for the DE pin to switch the buffers. The Arduino takes 10.4ns for an IO pin to rise to 2V.
That's an absolute maximum of 60.4ns.
One clock cycle of a 16MHz Arduino is 63ns.
That is longer than it takes for the IO pin to tell the MAX485 to switch the buffers.
You can increase that rise time by taking in to account the input capacitance of the MAX485 and the resistance of the connection between the Arduino and the DE pin, but it will still be microscopically small compared to the time between the pin going HIGH and the serial transmission starting.
So there must be something fundamentally wrong with your setup.  Two possibilities spring to mind:

You aren't controlling RE, only DE, so RE is floating and is being capacitively linked to DE through the parasitic capacitances of the board and circuitry, making it rise and fall very slowly.
You haven't set the IO pin on the Arduino to OUTPUT, so it switches between floating and HIGH through a very high resistance, causing slow rise to HIGH and maybe never getting to LOW at all.

Or a combination of the two.

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


text:
Check to see that String only contains .csv style numbers
I'm looking to determine if an Arduino String contains any other character than those that would be in the [number],[number]'\r''\n'where [number] could be positive or negative.
I know I can run a for down the entire string and use if(isDigit([char]) || isWhitespace([char])||[char]=='-') however, I imagine there's a better way to do this.
Could I (for example) convert the String to an array of values and search the array for any value that doesn't correspond to the characters I'm looking for? Or is there a better way to check this out?

ardunio gives you .indexOf(), which saves you the inner loop and is probably faster than hand-coding it.

Ok, so I could say give me `String.indexOf([Regular expression for A-z and symbols]) and if I got an index back I could reject the string?

yes, except for the regexp part, you need to match explicit literals

If your string contains 2 comma separated integers, with carriage return, then you could convert the string to a C string, then use the sscanf function, using "%d,%d\n". The return value of the function will tell you if the numbers are not in the correct format.

There is a better way, which is called regular expressions (or regexp). However, afaik these are not supported by Arduino by default.
However, I'm sure you can find some 'generic C++' class that can handle them.
For that, it's best to check on StackOverflow.com probably.
After a short check, on the Arduino forum there is a library available for regexp:
library
It is created by Nick Gammon, so all credits are for him.


text:
7-Segment Display with WS2312B and FastLED
I thought of the idea of using the WS2312B LED strip to drive a custom 7-Segment display. The project will require a large number of these displays, and driving them with a single Arduino (I'm thinking of an Arduino MEGA). For driving the LEDs I am using the FastLED library.

I wrote some code that drives a single display, It works, but I think It's possible to make it simpler, the code I wrote stores the digits in arrays, and uses these arrays in functions customized to each digit. here is an example:
//Digit Arrays:
byte digit0[]     = {0,1,2,3,4,5};
byte digit1[]     = {1,2};
byte digit2[]     = {0,1,3,4,6};
byte digit3[]     = {0,1,2,3,6};
byte digit4[]     = {1,2,5,6};
byte digit5[]     = {0,2,3,5,6};
byte digit6[]     = {0,2,3,4,5,6};
byte digit7[]     = {0,1,2};
byte digit8[]     = {0,1,2,3,4,5,6};
byte digit9[]     = {0,1,2,3,5,6};

The functions are something like this:
void AllOff(){
//Switch off All the LEDs in the segment. Should be off for 1 second
  for(int i=0; i<7; i++){
    leds[i] = CRGB::Black;
    FastLED.show();
  }
  //delay(1000);
}
void AllOn(CRGB myColor){
  //Switch on All the LEDs in the segment (should display 8)
  //The color of choice is #1E78A0
  for(int i=0; i<7; i++){
    leds[i] = CRGB (30,120,160);
    FastLED.show();
  }
  delay(1000);
}
void Print0(CRGB myColor){
  //Prints the digit 0:
  AllOff();
  ArraySize = sizeof(digit0);     //get the size of the array
  for(int i=0; i<ArraySize; i++){
    LED_Number  = digit0[i];      //get the LED number from the array
    leds[LED_Number]    = CRGB (myColor);  //Switch the LED on
    FastLED.show();
  }
}

When I call it in the code, I simply do something like this:
Print0(CRGB::Purple);
delay(500);

I have tried for the best part of the past two days to find a better way to go about this, but I couldn't. What I'm thinking is perhaps to create a function that would store all the digits instead of storing every one as an array, and then call it maybe within a for loop? something like
for(int i=0; i<10; i++){
    displaydigit[i];
    FastLED.show();
  }

Do you know of any library that has something similar, or perhaps any idea on how to achieve this?
Your assistance, as always, is greatly appreciated.
Thank You.

First, for all the digits I'd use an 7 value array, indicating for every segment if it's ON or OFF. So for 0 your get byte digit0[] = {1,1,1,1,1,1,0}, where 1 indicates the segment is ON, and 0 indicates it's OFF. Your code then becomes:
void Print0(CRGB myColor){
  //Prints the digit 0:
  for(int i=0; i<7; i++){
    if( digit0[i] )
      leds[i] = CRGB (myColor);  //Switch the LED on
    else
      leds[i] = CRGB::Black; // Switch the LED off
  }
  FastLED.show();
}

The next step would be to create a two dimensional array containing which segments are on for which digits.
byte digits[10][7] = {
     {1,1,1,1,1,1,0} //0
    ,{0,1,1,0,0,0,0} //1
    ,{1,1,0,1,1,0,1} //2
    ,{1,1,1,1,0,0,1} //3
    ,{0,1,1,0,0,1,1} //4
    ,{1,0,1,1,0,1,1} //5
    ,{1,0,1,1,1,1,1} //6
    ,{1,1,1,0,0,0,0} //7
    ,{1,1,1,1,1,1,1} //8
    ,{1,1,1,1,0,1,1} //9
   }

Now you can generalize you Print0 function to accept any number:
void PrintNumber(byte number, CRGB myColor){
  if( number>9 )
    return;
  for(int i=0; i<7; i++){
    if( digit[number][i] )
      leds[i] = CRGB (myColor);  //Switch the LED on
    else
      leds[i] = CRGB::Black; // Switch the LED off
  }
  FastLED.show();
}

Call the new function in your loop; for example PrintNumber(3, CRGB:White);
If you want to put multiple 7-segment displays in series, you could add and offset argument to the PrintNumber function, and use leds[i+offset] instead. Then call the PrintNumber with offset 0 for the first digit/display, 7 for the second, 14 for the third, and so on.

you could add two more rows to the digits array for all off and all on

@Gerben Thank You! I'm testing the code now. I'm thinking that I will do the displays in series for some segments and using different pins for other ones. The leds[i+offset] is something that I was looking for, so you have actually answered two questions with one post.

@Gerben Thank you! works like a charm, and it's a lot prettier than the code I wrote. I will accept your answer!

@jsotola That's actually a good idea. Implemented

@jsotola what's the difference between all on and the number 8 ? q-;

In general, in many engineering efforts, a definition of the feature(s) and constraints need to be considered.  The feature you are creating is a large-7-segment-display.  Now decide what constraints you are working under.  Normally, in embedded programming, this means limited memory, limited power and interacting with people.
Because of limited memory, consider storing 7-segment patterns in a condensed form.  Also consider creating the simplest code possible.  Usually the more data is compressed, the more complex the code needs to be.  If there is a large amount of data (for example, an mp3 compressed sound track) the cost of high compression and complex code can be justified.  But storing 7-segment patters is comparatively simple.  So, consider expanding the array to include all 7 segments for each of the 10 digits.  Store if each segment is on or off.  Then, remove the "all on" and "all off" loops in your code leaving only one loop to read the array and turn off or on each segment.
Adapting the project to facilitate interacting with people can be confusing and difficult.  Possibly the most common problem with displays are delays and flicker.  For this project choosing the WS* line of LEDs should mitigate flicker problems (at the very least it takes it out of your hands) as the PWM feature is the responsibility of each WS* chip. People have been putting up with (expect) small delays when viewing large displays.  And it is expected this approach could update perhaps 10 digits in less than hundreds of milliseconds.

You are absolutely right. Memory is one thing, and the ease of reading and debugging the code is another. SE is a wonderful platform because people get to share thoughts and solve problems together. Well structured problems, that is :)

Thanks @MDChaara.


text:
Is there a way to combine a 3-axis accelerometer/gyroscope into one value?
I have a three-axis accelerometer that reads me its x, y, and z components.  This results in three graphs.  Is there a way to "combine" these components into one reading, hence, one graph?   Same question holds for a gyroscope.
The datasheet for my device is here:

The answer is: technically, yes, it is possible. The combined result is called Quaternion. This is what is typically used in 3D programs.
But most likely that is not what you had in mind.
Usually one can do a simplification and reduction of dimensions when in presence of some constraint.
Imagine that your moving object is bound to a planar surface: no matter how you tilt and rotate and pan it, it is still a 2D surface, plus a quaternion indicating the rototranslation.
But, once you have established the coefficients applied to the rototranslation, it is 2D.
Similar 1D case: imagine that your moving object is bound to some well-known geometrical shape, say a circumference. Once you have established how the circumference is oriented in the 3D space and its radius, you can express the position of your device by indicating either the angle or the distance from a reference point on the circumference.
In both cases you can simplify the representation because of constraints that do not allow for real 3d movement.
But if your device is a flying drone that can rototranslate freely within certain boundaries (max horizontal range, min/max altitude), there is no way that you can simplify the 3d coordinates.
If, instead, your question was related to the protocol used to read info from the accelerometer, you are bound to the protocol defined in the datasheet, by the manufacturer.


text:
How do I connect a vibration motor to Arduino?
I'm trying to figure out how to connect a vibration motor to my Arduino.  I've come across this resource and it seems pretty straightforward though for a while my eye glazed over at how complicated the circuit was (do I really need all of that to run my vibration motor?).
My real question is that I have a vibration motor similar to the picture in the link and I'm trying to figure out how to actually connect it to my breadboard.  Do I have to solder wires onto those flimsy ends or is that a better way to get this to work?
Thanks!

What application do you need it for? I've seen vibration motors employed as regular motors to drive a tiny worm drive.

Lets break down the circuit and have a look why everything in that circuit is there and what it does.
First we have the 33R resistor before the motor which limits the current to the motor. This particular motor is rated at 75mA and has a starting of 85mA. The 33R resistor limits the current to 130mA maximum through the motor. If the risk of the motor pulling too much current is an issue then stick a fuse in-line
Then there's the motor, not much to say here really. It's whatever motor you're using.
We then have both a diode and a capacitor across the motor. I find this a bit strange, I've seen the use of flyback diodes, I've seen the use of snubbers, but both? The purpose of the diode is to allow a return path for any spikes caused by switching off power to the inductive load (the motor) which stops them from damaging the transistor. For the capacitor, just remove it, it's not got any use here really.
Then comes the transistor, it might be easier to think of a transistor as a switch (especially in this example). When you put a little bit of current on the base, the transistor 'opens' allowing the motor to connect to ground. The reason we have to use a transistor is because the outputs of an arduino are only able to supply a maximum of 40mA, we need more than that to run our motor. Fortunately, the transistor is not going to need any more than 5mA on it's base which is why we use it to 'switch in' components that require more voltage/current. The 1K resistor on the base is to limit the current coming from the arduino and preventing it from killing our poor transistor.
tl;dr - You need everything except the capacitor

There are actually a number of things wrong with that circuit.
First the motor runs from 2.5 to 3.8V, yet they show it running off the 5V supply pin.
Secondly they include a 33Ω resistor to "limit the current". It doesn't! It drops a voltage depending on the current flowing through it, and the current flowing through it depends on the speed and load of the motor at the time.  So the motor itself will be getting a fairly random voltage applied to it, which at times will be below the specifications.
E.g.:

The start current is 85mA.  V=RI, 33*0.085 = 2.805V. 5 - 2.805 = 2.195V: way below the 2.5V required minimum.
The run current of 75mA calculates as: 33*0.075 = 2.475. 5 - 2.475 = 2.525V: only just enough for it to run.

So it should be powered from a 3.3V supply that has enough current capacity to drive it (85mA) and the 33Ω resistor should be removed entirely.

I'm really grateful for your answer. I've been doing nothing but LEDs for so long I'd fallen into a trap and completely forgotten something so basic. Thanks for waking me back up

You could make a simpler circuit by removing the diode, capacitor.  BUT this comes at the cost of having a circuit that could kill your arduino.
Stick with it and build the entire thing.  This isn't a shortcut worth taking.

I wouldn't even give the suggestion of removing the diode. It's general practice to always put a diode across an inductive load. Unless you like dead transistors

I didn't say it was a good idea.  Only that it was possible.

I've never used a vibration motor, but I think you do need all of the circuit.  Its says in the text, but the transistor is needed because the Arduino 'doesn't supply enough current through the output port' and the diode and cap are required to prevent spikes.
As to the flimsy wires you could solder them onto a bit of strip board and then solder "proper" wires of connectors onto the board too.


text:
Is it safe to power an MQ-7 gas sensor with a 9V D.C supply?
I'm looking for a portable power source for an MQ-7 gas sensor. According to my research - it needs 5V D.C power with at least 0.3A of current. I'm not really good with electronics so I need to know if I can use a 9V battery instead which produces 0.5A. Will the cell damage my sensor and if it does may you please recommend me something else.

I don't think a 9V battery can supply 0.5A.

You can, but you will have to reduce the voltage to the 5V the sensor needs, otherwise you will blow up the sensor.
To that end you require a voltage regulator. You can use a linear regulator like the Arduino has on-board, but they are very wasteful of power and will dissipate the excess 4V of electricity as heat.
Better would be to use a switching regulator (commonly and cheaply available on eBay and other sites) to step the voltage down to 5V more efficiently.

Thanks. I was considering a voltage regulator but I'm not sure If that can be shipped to where I live in a week without extra costs. Can I use 4x AAA cells instead?

It requires 5V ±100mV, so 4.9V to 5.1V. 4 AAA alkeline is 4x1.5 = 6V (too high). 4 AAA NiMh is 4x1.2 = 4.8 (too low).  You might get away with 4x NiMh at a pinch, but as they discharge the voltage will drop and it will fail.

Ok, so do  4 AAA NiMh cells provide 0.3A as well?

They can provide considerably more than that. They will last much longer than a 9V PP3 which would be lucky to last an hour.

Thanks, so I can safely use 4 AAA NiMh? I don't mind them not lasting over an hour - I just need to make a demonstration then I order a voltage regulator to create a proper circuit!

Yes, that should work OK.


text:
Strange behaviour with using max
I have this really simple code.
Let's say I have a variable X.
Then all I want to do is create a random value R, if R > X then I want X to become R.
But for some reason, my n_of_buttons_pressed climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.
#define N_OF_BUTTONS 60

int n_of_buttons_pressed;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
}

void loop() {

  n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

  Serial.print("n_of_buttons_pressed:");
  Serial.print(n_of_buttons_pressed);
  Serial.println();

  delay(100);

}

The max() “function” is actually a macro defined in Arduino.h as
#define max(a,b) ((a)>(b)?(a):(b))

This expands in your code into something like
buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                  random(0, N_OF_BUTTONS) : n_of_buttons_pressed

The problem with the macro is that it evaluates at least one of its
arguments twice. In this case, if the test is true, the variable
buttons_pressed gets assigned another pseudo-random number.
The way around this is to store the pseudo-random number in a variable,
to avoid random() being evaluated twice:
int pseudo_random = random(0, N_OF_BUTTONS);
buttons_pressed = max(pseudo_random, n_of_buttons_pressed);


text:
I need help in designing a circuit to connect an Arduino MEGA and a CD-Pickup Reader/Writer
I'm trying to use the IR source and detector of the CD Pickup reader/writer (KSS-213C) along with the lens focussing/tracking system. I want to control them using an Arduino MEGA. So since I will be needing one constant source for the diode, I will connect it separately to a source, not to the Arduino. Since this is a sensitive device, I read that you need to have constant current sources and so on. Now, I'm new to designing circuits of my own, I found this picture in an article, but it is for a DVD writer. Could someone tell me if I could use the same circuit with some modifications or should I try something else. Now note that my main output is that of the IR sensor that my Arduino would read.

I don't know how to answer most of your question, but one caution. The relay in that circuit should either be a "digital" relay that's separately powered and designed to be controlled with a CMOS logic signal, or you need to drive it using a power transistor protected with a "flyback diode". (Inductive loads like relay coils have "back EMF" that will destroy solid state components like transistors or Arduinos.)

@DuncanC, there was a circuit given in the question of this link: https://electronics.stackexchange.com/questions/278887/how-to-determine-the-operating-voltage-and-current-of-a-laser-diode. Can I use the same instead of the LM317-Constant Current Source circuit from my question?
By the way, I'm sorry I don't know if my relay is a digital one. I'm using a HE-LQC3FC Relay, would that work?


text:
Pro Micro with Atmega32U4 - reset - reprogramming
i am a new user on arduino card. i have a question about "Pro Micro with Atmega32U4".
- is this product programmable several times ? and the third pin (RST) - (Reset). so, does reset mean it erases memory?
Thank you in advance for your answers.

Yes, the microcontroller on Arduinos (in this case the Atmega32U4) can be reprogrammed many times, only limited by the write limit of the flash memory (As I remember Microchip garantuees about 100,000 write cycles at minimum). You can program it over the USB port of the board or through an ISP programmer.
The Reset pin will do the same as a power cycle (turning off an on again) would do. If you program the Arduino, this program will start, when the Arduino get's power (after the Bootloader, which is used to program over USB without ISP programmer). This program will then run until the power is turned off, or until a reset is done by pulling the RST pin to ground. When the RST pin is released again, the Arduino will again start up. The flash memory and the EEPROM stay untouched and will not loose any data. But the data, that lies in SRAM (like any normal variable in the program) will be lost.

Firstly, thank you for your quick response.
So, and if i want to erase completly the memory of my arduino card with the arduino App, is it possible ?
PS : because i found several subject talks about erasure memory arduino card and it isn't possible.

You are always talking about an "Arduino card". I think you mean a standard Arduino board (board is the better term here). 2. If programmed over USB, the current program will be overwritten, except for the bootloader, which you need to program it this way. There is no need to do an extra erase step. You can just write a program in the Arduino IDE, connect the Arduino, choose the correct port and board type and then hit upload. The Arduino IDE will then compile your code and upload it onto the Arduino.

Thank you very much for your help

If you think my answer is correct and good, you can upvote it and accept it as correct :)


text:
Arduino as Slave on I2C bus to read data from other I2C devices
Good afternoon;
I am a bit new to the world of I2C bus. I'm trying to implement a project that have  Arduino MEGA as a master and Arduino nano as slave. I have some I2C sensors that i want the slave (Arduino nano) to read. Please how can i implement this.

Am I understanding correctly, that your I2C slave Nano should also be a master for the I2C sensors?

A uC having only one hardware i2c interface can only be master OR slave, not both at the same time.

Thank you for your response, I understand now. I'm thinking the best approach will be to use other pins of the Arduino Nano to interface the I2C sensors. But because these sensors are I2C sensors, i believe they will not just work directly with other pins except the dedicated I2C pins. Do you know how i can enable other pins of the Arduino Nano to be used for the I2C sensors?

An Arduino can be both a master and a slave.  Nick Gammon's page on I2C describes how to do it.   http://www.gammon.com.au/i2c

Communicating with other devices
So all this I2C stuff is great, you can use just two wires (plus ground) to talk to up to 119 devices. But what if you have a device (like a keypad) that doesn't support I2C? Well, the simple answer is that you can use something that does as an interface. For example, a second Arduino. My examples above do just that, using one as the master and second one to display text on LEDs.
In fact, the "master" can also act as a slave, since you can have multiple masters on one wire. The example below shows how you can send data from one Arduino to another, whilst waiting for information to be sent from the second back to the first.

See the link for code examples.

Does the Wire now support bus arbitration, so that multi master can be done without locking the bus?

No idea, I've rarely used I2C, preferring instead the much faster SPI.

Thank you for your response, I have seen what he did and it was great. However because my sensors are I2C sensors, it may not work well as he did.  I'm thinking the best approach will be to use other pins of the Arduino Nano to interface the I2C sensors. But because these sensors are I2C sensors, i believe they will not just work directly with other pins except the dedicated I2C pins. Do you know how i can enable other pins of the Arduino Nano to be used for the I2C sensors?

What are your sensors? Part numbers?

Proximity sensor, VCNL4040, Time of Flight Sensor VL6180

"VCNL4040 applies single slave address 0x60 (HEX) of 7-bit addressing following I2C protocol. "   "The VL6180X is controlled over an I2C interface. The default I2C address is 0x29 (7-bit). "  So, two different addresses. Connect both to SDA & SCL, talk to one, then talk to the other.


text:
Why does the arduino respond so slow to serial input
I have this really simple sketch where I blink a led light.
If I send another value threw the serial monitor then first there is always a brief second where the light doesn't blink anymore. Why is that, and how can I get rid of that?
int the_delay = 300;

void setup() {
  Serial.begin(115200);
  pinMode(12, OUTPUT);
}

void loop() {
  digitalWrite(12, HIGH);
  delay(the_delay);
  digitalWrite(12, LOW);
  delay(the_delay);
}

void serialEvent() {

  if (Serial.available()) {
    the_delay = Serial.parseInt();
    Serial.println(the_delay);
  }
}

In case it helps, eventually I would like to send values with 60fps.

It's because you're using Serial.parseInt().  It uses a timeout to find the end of the data on the serial port, and while it's waiting for that timeout it can do nothing else.
You would be better off manually reading the serial data a character at a time to build up an input string (C-string, not Arduino String) with a proper line terminator (line-feed, \n) and then convert that into an integer with atoi().

Try typing a non-digit character after the delay value; even Enter should work if your terminal is configured to send any kind of end-of-line. Serial.parseInt() waits the full timeout (default: 1000 ms) after each digit, for the next one. A non-digit will end the input value immediately.

See How to process incoming serial data without blocking. An interim solution is to get the Serial Monitor to send a newline automatically when you press Send.
Here is example code that processes input without blocking:
// Example of processing incoming serial data without blocking.

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

Edit as follows:
Serial.begin(115200);
Serial.setTimeout(10); //Maximum time in ms that it should wait for data
The default delay is 1000ms.
The code above sets it to 10ms.
Play around with the Timeout value and check for faults.
https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/

This is good so far as it goes. But, it seems mostly a repeat of an existing answer.


text:
What does serial monitor send with 'Both NL & CR'
There is something I don't understand about serial monitor.
As far as I know the Newline option is \n.
The Carriage return option is \r\n.
But does that make the Both NL & CR option \n\r\n?

Newline is \n
Carriage Return is \r
Both NL & CR is \r\n

It would be wonderful if this could be called "CR & NL" (note the sequence) or maybe just say \r\n. Because when you read "Both NL & CR" you then scratch your head and say "hm, does this actually mean \n\r".

"Both" means 1 Carriage Return and 1 Newline (formerly known as "Line Feed"). Our present day "standards" are descended from mechanical teletypes that used those separate codes for the two separate mechanical functions: Returning the print carriage to the left side of the page, and scrolling the paper up one line.
The DOS/Windows world adopted the teletype standard (both) as is.
The unix world dropped the carriage return as unnecessary, letting a single character stand for the end of a line, and more modern hardware (or its software drivers) could figure out what to do for the particular device.
The Apple world chose Carriage Return for its standard back in the mists of time, dropping it in later years for a selectable end-of-line sequence where appropriate, but more usually using the unix standard once it's OSes became hosted on unix.

Baudot had separate CR LF. It was common to use CR and duplicate part of a line to get "Bold" characters.


text:
How to know my Arduino core version and its location on my Ubuntu laptop?
Bakground:
When compiling a demo project about e-paper, I got this problem
./GxEPD/src/GxIO/GxIO_SPI/GxIO_SPI.h:39:5: error: ‘SPISettings’ does not name a type
     SPISettings _spi_settings;
     ^

which on the Internet, people often say your Arduino core is not up-to-date and the one installed from
sudo apt install arduino-core

is ancient. And you have to install the latest version.
Regardless of whether this solves my original problem or not, I want to have the latest Arduino core on my  laptop.
From arduino.cc I grabbed a zipped file and ran ./install.sh which did not provide enough results to know what it exactly did. Now, I am concerned that I have multiple installation in several places.
Main question:
When I run my make file and it is processed by arduino-mk, which version of arduino-core is it referred to and where is it located?
I am looking for a full proof method. I do not want to open somewhere from / directory accidentally. Because maybe this is not the arduino-core in use.

On Linux install.sh creates a shortcut on Desktop.  A version of AVR boards package is part of IDE installation, but other version and other boards packages managed with Boards Manager are in ~/.arduino15

@Juraj,
Actually, I do not use AVR board package. I use make file which calls avr-gcc.
I think I could find the answer a bit easier by paying attention to the logs coming out of make such as /usr/share/arduino/hardware/tools/avr/bin/avr-gcc -MMD -c -mmcu=atmega328p ... as well as ARDUINO_DIR = /usr/share/arduino and ARDUINO_VERSION = 105. Now the question is whether my Arduino core is recent?

@Juraj, at arduino.cc, the version of Arduino Software (IDE) is 1.6.2. Is this only the version of IDE or is it the version of core too?

IDE is at version 1.8.10 on arduino.cc. AVR core is at 1.8.1, but last good version in my opinion is right now 1.6.21

/usr/share/arduino/hardware is the location of boards packages bundled with IDE

The ancient version installed by apt lives in
/usr/share/arduino/hardware/arduino/cores/arduino.
If you download and unpack a recent version, it will stay wherever you
left it. For example, I have an Arduino core in
/home/edgar/Downloads/arduino-1.8.10/hardware/arduino/avr/cores/arduino.
The installation script doesn't really install those files. It does
install some icons and desktop shortcuts, but neither the core nor the
Arduino IDE. Instead, it assumes the downloaded package will stay
wherever it was when you ran the script.
If you want a somewhat cleaner installation, I suggest you move the
package to /opt, recursively chown it to root, and run the setup script
there. The core will then be in
/opt/arduino-<version>/hardware/arduino/avr/cores/arduino.

Thank you very much. Then how to tell arduino-mk to which version to use?

Can I insall it in a temp directory and then overwrite it on the ancient arduino core?

@ar2015: Read the comments at the beginning of /usr/share/arduino/Arduino.mk. They tell you the variables you can use for selection the version. It would seem ARDUINO_DIR is the main one.


text:
SPI command versus data?
I have bough an LCD screen display TFT Touch Screen Board For Arduino UNO R3.
Aand the following commands are given to me for the initialization:
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
delay_nms(5);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
delay_nms(10);

write_SPI_commond(0xB0);
write_SPI_data(0x00);

write_SPI_commond(0xB3);
write_SPI_data(0x02);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x10);

write_SPI_commond(0xB4);
write_SPI_data(0x11);//0X10

write_SPI_commond(0xC0);
write_SPI_data(0x13);
write_SPI_data(0x3B);//
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0x00);//NW
write_SPI_data(0x43);

write_SPI_commond(0xC1);
write_SPI_data(0x08);
write_SPI_data(0x15);//CLOCK
write_SPI_data(0x08);
write_SPI_data(0x08);

write_SPI_commond(0xC4);
write_SPI_data(0x15);
write_SPI_data(0x03);
write_SPI_data(0x03);
write_SPI_data(0x01);

write_SPI_commond(0xC6);
write_SPI_data(0x02);

write_SPI_commond(0xC8);
write_SPI_data(0x0c);
write_SPI_data(0x05);
write_SPI_data(0x0A);//0X12
write_SPI_data(0x6B);//0x7D
write_SPI_data(0x04);
write_SPI_data(0x06);//0x08
write_SPI_data(0x15);//0x0A
write_SPI_data(0x10);
write_SPI_data(0x00);
write_SPI_data(0x31);//0x23

write_SPI_data(0x10);
write_SPI_data(0x15);//0x0A
write_SPI_data(0x06);//0x08
write_SPI_data(0x64);//0x74
write_SPI_data(0x0D);//0x0B
write_SPI_data(0x0A);//0x12
write_SPI_data(0x05);//0x08
write_SPI_data(0x0C);//0x06
write_SPI_data(0x31);//0x23
write_SPI_data(0x00);

write_SPI_commond(0x35);
write_SPI_data(0x00);

//write_SPI_commond(0x36);
//write_SPI_data(0x00);

write_SPI_commond(0x0C);
write_SPI_data(0x66);

write_SPI_commond(0x3A);
write_SPI_data(0x66);

write_SPI_commond(0x44);
write_SPI_data(0x00);
write_SPI_data(0x01);

write_SPI_commond(0xD0);
write_SPI_data(0x07);
write_SPI_data(0x07);//VCI1
write_SPI_data(0x14);//VRH 0x1D
write_SPI_data(0xA2);//BT 0x06

write_SPI_commond(0xD1);
write_SPI_data(0x03);
write_SPI_data(0x5A);//VCM  0x5A
write_SPI_data(0x10);//VDV

write_SPI_commond(0xD2);
write_SPI_data(0x03);
write_SPI_data(0x04);//0x24
write_SPI_data(0x04);

write_SPI_commond(0x11);
delay_nms(150);

write_SPI_commond(0x2A);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0x3F);//320

write_SPI_commond(0x2B);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0xDF);//480

//write_SPI_commond(0xB4);
//write_SPI_data(0x00);
delay_nms(100);

write_SPI_commond(0x29);
delay_nms(30);

write_SPI_commond(0x2C);

These commands do not look like Arduino commands to me. I have placed them like this
#include <Arduino.h>
#include <SPI.h>

void setup()
{
    Serial.begin(9600);
    Serial.println("Test!");

    SPI.begin();

    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    delay_nms(5);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    delay_nms(10);

    write_SPI_commond(0xB0);
    write_SPI_data(0x00);

    write_SPI_commond(0xB3);
    write_SPI_data(0x02);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x10);

    write_SPI_commond(0xB4);
    write_SPI_data(0x11);//0X10

    write_SPI_commond(0xC0);
    write_SPI_data(0x13);
    write_SPI_data(0x3B);//
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0x00);//NW
    write_SPI_data(0x43);

    write_SPI_commond(0xC1);
    write_SPI_data(0x08);
    write_SPI_data(0x15);//CLOCK
    write_SPI_data(0x08);
    write_SPI_data(0x08);

    write_SPI_commond(0xC4);
    write_SPI_data(0x15);
    write_SPI_data(0x03);
    write_SPI_data(0x03);
    write_SPI_data(0x01);

    write_SPI_commond(0xC6);
    write_SPI_data(0x02);

    write_SPI_commond(0xC8);
    write_SPI_data(0x0c);
    write_SPI_data(0x05);
    write_SPI_data(0x0A);//0X12
    write_SPI_data(0x6B);//0x7D
    write_SPI_data(0x04);
    write_SPI_data(0x06);//0x08
    write_SPI_data(0x15);//0x0A
    write_SPI_data(0x10);
    write_SPI_data(0x00);
    write_SPI_data(0x31);//0x23

    write_SPI_data(0x10);
    write_SPI_data(0x15);//0x0A
    write_SPI_data(0x06);//0x08
    write_SPI_data(0x64);//0x74
    write_SPI_data(0x0D);//0x0B
    write_SPI_data(0x0A);//0x12
    write_SPI_data(0x05);//0x08
    write_SPI_data(0x0C);//0x06
    write_SPI_data(0x31);//0x23
    write_SPI_data(0x00);

    write_SPI_commond(0x35);
    write_SPI_data(0x00);

    //write_SPI_commond(0x36);
    //write_SPI_data(0x00);

    write_SPI_commond(0x0C);
    write_SPI_data(0x66);

    write_SPI_commond(0x3A);
    write_SPI_data(0x66);

    write_SPI_commond(0x44);
    write_SPI_data(0x00);
    write_SPI_data(0x01);

    write_SPI_commond(0xD0);
    write_SPI_data(0x07);
    write_SPI_data(0x07);//VCI1
    write_SPI_data(0x14);//VRH 0x1D
    write_SPI_data(0xA2);//BT 0x06

    write_SPI_commond(0xD1);
    write_SPI_data(0x03);
    write_SPI_data(0x5A);//VCM  0x5A
    write_SPI_data(0x10);//VDV

    write_SPI_commond(0xD2);
    write_SPI_data(0x03);
    write_SPI_data(0x04);//0x24
    write_SPI_data(0x04);

    write_SPI_commond(0x11);
    delay_nms(150);

    write_SPI_commond(0x2A);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0x3F);//320

    write_SPI_commond(0x2B);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0xDF);//480

    //write_SPI_commond(0xB4);
    //write_SPI_data(0x00);
    delay_nms(100);

    write_SPI_commond(0x29);
    delay_nms(30);

    write_SPI_commond(0x2C);
}

void loop(void)
{
    delay(1000);
}

and I get many errors like
error: ‘write_SPI_commond’ was not declared in this scope

Even fixing the typo to write_SPI_command does not work. I have no problem with using the default SPI.transfer of the Arduino library. But, I am wondering how to translate write_SPI_commond and write_SPI_data into a proper SPI.transfer?

What do you mean by “the following commands are given to me”? Given by whom? Is that a documentation accessible on the Web? If so, please provide the link.

@EdgarBonet, By the vendor. Under "Initialization Code".

To answer the question in the title "SPI command versus data?":
TLDR
Some SPI drivers will separate the data sent on the COPI/PICO lines into subsections to make it easier on the programmer.
SPI command versus data?
I am currently working with the ESP32 myself and have come accross the more generic question of "What is the difference between command and data when using SPI?". After some reading around, I have come to the conclusion that certain SPI drivers will allow users to separate the generic data sent in SPI protocal into subsections such as ADDRESS, COMMAND, and ADDITIONAL_DATA. This is simply to make it easier for the programmer to understand what they are sending.
Not all applications will require the an ADDRESS, COMMAND, and ADDITIONAL_DATA. For example, some chips will have pre-programmed commands such as this Inclinometer (SCA61T) which then may or may not require ADDRESS and ADDITIONAL_DATA. But others, such as the MAX7219 (which I am using), only require an ADDRESS and ADDITIONAL_DATA, no COMMAND.
Example
Using the ESP32 SPI driver, I played around with setting the length of the command bits and address bits from 0 to some nonzero number as seen in the code snippet below.
spi_device_interface_config_t devcfg={
                .command_bits=4,           ///< Default amount of bits in command phase (0-16), used when ``SPI_TRANS_VARIABLE_CMD`` is not used, otherwise ignored.
                .address_bits=4            ///< Default amount of bits in address phase (0-64), used when ``SPI_TRANS_VARIABLE_ADDR`` is not used, otherwise ignored.
}

Then I specified the data to be sent in the command and address bits (along with the data to be sent in the tx buffer) as seen in the code below.
     char data[1]= {0x97};

            spi_transaction_t spi_trans={
                .cmd={0x05},          ///< Command data, of which the length is set in the ``command_bits`` of spi_device_interface_config_t.
                .addr={0x00},         ///< Address data, of which the length is set in the ``address_bits`` of spi_device_interface_config_t.
                .length=8,            ///< Total data length, in bits
                .rxlength=0,          ///< Total data length received, should be not greater than ``length`` in full-duplex mode (0 defaults this to the value of ``length``).
                .rx_buffer=data,      ///< Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used.
                .tx_buffer=data,      ///< Pointer to transmit buffer, or NULL for no MOSI phase

            };

where spi_trans.cmd = {0x05} with 4 bits length corresponds to a binary 0101, spi_trans.addr = {0x00} with 4 bits length corresponds to a binary 0000, and spi_trans.tx_buffer = {0x97} with 8 bits length corresponds to a binary 10010111.
When using an o-scope to measure the chosen COPI and clock pins, we see the following waveform.

We realize the ordering of the data sent over the COPI pin is command, then address, and lastly tx data. This ordering may differ depending on which driver is used (I am using the ESP32 SPI Master driver).

The “commands” provided by the vendor are not code meant to be copied
as-is. They are pseudocode. If you need to know the real difference
between “write command” and “write data”, you have to look at the
datasheet of the interface chip.
See for example the ILI9481. On pages 28–29 you can see a data
transfer mode compatible with SPI (type C interface, option 3). Here you
have to wire one digital output of the Arduino to the D/CX pin on the
interface chip. This pin is used to tell whether you are writing a
command (pin LOW) or data (pin HIGH).

It is very cryptic. Can you please explain the data and command in a clear language?

@ar2015: No, I only know what I saw by looking at the datasheet. A careful read would be needed for fully understanding the protocol. I could do it. So can you.


text:
Why my arduino board does not blink properly?
I have two files
blink1.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

blink2.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

The difference between these two files are the definition of only a few unused ports in blink2.
I compile and upload them to the board by
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex

The first one does not blink properly but the second one does. What is the problem of the first code?

Do both files behave the same when using avr-g++ -Os blink1/2.cpp -o blink1/2 for compilation?

@MaximilianGerhardt, using -Os both act as before.

I think ddrB = (port_type) 0x20; should be *ddrB = (int8_t) 0x20; no?

@MaximilianGerhardt, You are correct. However, this fix does not change anything. The board behavior highly depends on the variable you define after ddrB and its value.

@MaximilianGerhardt, it is interesting that when I use *ddrB = (int8_t) 0x20;  with -Os, the LED turns on but does not blink. If I do not use -Os it will blink fine.

Maybe you're killing the contents of registers that are being used. Check the disassembly to see if the registers you are using in assembly are being pushed to the stack before use and popped off afterwards - if they aren't then you should be doing that manually.

https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Clobbers-and-Scratch-Registers

You may want to exchange the assembly code for C code for a test and see if that's the problem, e.g. with the code https://pastebin.com/Z5m2fvWt

@MaximilianGerhardt: Your delay_500ms() is more than an order of magnitude slower than the original.

There are a couple of issues here.
One of them has already been raised in a comment:

 int main()
 {
-    ddrB = (port_type) 0x20;
+    *ddrB = (int8_t) 0x20;

     while(true)
     {

The more serious issue is in the command line you used to compile the
program. When compiling for an Uno, you should add the option
-mmcu=atmega328p. This way the compiler knows which version of the C
runtime it should add to your program. Otherwise the compiler will
include no runtime at all.
The C runtime does some important initializations. For example, it
clears the register r1, which is required by the ABI, and assumed
to be the case by the compiler. For example, when you write *portB = (int8_t) 0x00;, the compiler copies r1 to the port, without first
clearing it. Another important role of the C runtime is to call
main(). Without it, the program will start by executing whichever
function happens to be at the start of the flash. Unless you program in
assembly, you have no control over that. If the first function happens
to be main(), the program may work as expected. If it is another
function, that function may then return to the bootloader. Any seemingly
innocuous change in the program can then change the behavior.
Then a few minor issues, that should not prevent the program from
working:

int8_t is meant to be a signed type. If you want the unsigned
version, use uint8_t instead. Sure, these are your own type
definitions, but creating a type that conflicts with a standard type
can only create confusion. Best option is to drop the definition and
include <stdint.h> instead.

Whereas port_type should certainly be a “pointer to volatile” data,
there is no point in making the pointer itself volatile. That can only
hinder valid optimizations.

portB and ddrB should be const, and that may allow the compiler
to better optimize them. But why not use PORTB and DDRB from
<avr/io.h>?

I confirm using avr-g++ -mmcu=atmega328p instead of avr-g++ has fixed the problem. Thank you so much.


text:
Any reason to acquire more watts than really needed?
Basic question (again):
I have a LED-strip that requires 5V, and each LED (150 in total) requires about 60 milliamps.
Calculating everything, I need 3 of these LED-strips (450 LED in total). This in turn tells me that they require 27 000 milliamps (27 amps), which is about 135W.
Which means I need an external power supply to power them.
I think about buying a 5V 40A (200 W), which should be sufficient(?).
But, is there any reason that I should not buy anything with more watts (250 or 300)?
Thanks for any help!

i would actually rather have 3 different 10A (or 12A for margin) supplies, so that my cables weren't heavy and/or a burn risk.

Are you sure every led is 60 mA? Or you mean maybe each Red, green and blue led inside each led (3 x 20 mA).
You always should buy slightly more than you need (but you think about 200W instead of 135W) already which is more than enough safety overhead.
Why would you need more? If you mean to control it with an Arduino Uno, that MCU (including the LEDs etc) is high likely more than a few hundred mA. So the only reason why you need more, is if you want to control later more LED strips, or any motor or other power hungry external devices.

Thanks for your reply! Yeah, I meant 20 mA each red, green and blue.
Based on what you write it seems fine to go with 200W, so I will try that. Thanks again for making things clear! :)


text:
Reading incoming/outgoing bytes from SIM card / ATR
I am trying to read data from a two-way I/O uart pin of a sim card on Arduino. It is attached to the GPRS Arduino shield (with SIM900 modem). I believe I have a baud rate issue.
I am supposed to receive ATR (Answer to Reset) bytes which should be easily recongnized but all I get is a almost-random stream of bytes.
I soldered a wire on the SIM I/O pin and attached it to arduino's software serial RX, I set the baud rate to the same baud rate of the modem which goes up to 115,2K and read. Here's my code
#include <SoftwareSerial.h>
SoftwareSerial IO(9, 10);
void setup() {
Serial.begin(115200);
IO.begin(115200); // my said wire on SIM card's I/O    enter code here
}
void loop() {
if (IO.available())
Serial.print(IO.read(),HEX);
}

and here's the output after a cold reset :

I also tried other baud rate within the SIM900 range of baud rates, still almost same.
Any idea why it's not showing bytes correctly? I appreciate it if anyone could help.

what is "GPRS Arduino shield (with SIM900 modem)"?

why do you print it as HEX and without spaces between? the print(,HEX) doesn't add leading zeros


text:
Make one button print different sentences on LCD
I am very new to arduino and I've been scratching my brain on how to make one button print out three different sentences. When I press it the first time, a " I am " is suppose to appear, when I press it the second time " very" and then the third time " late". I can't have three different buttons because a tone follows this button as well.

You can start with the https://www.arduino.cc/en/Tutorial/StateChangeDetection and try to count to three and use the count to display different messages.

but how do I do that with a text?

When the counter is incremented, then you can do a few if-statements to show text according to the value of the counter.

@chase if you want me to break it down more in the answer, post a follow up note under my answer below.  But regardless of what you call it, you will eventually create a state machine.  If the code is nice an clean it will be easy to maintain and add to.  If you go about it piecemeal then it might turn out to be difficult to manage.  Remember to start simple, test then add more features.  Don't try and do it all at once.  Hence why I said make a 3 state machine w/o the messages the 1st go around.

I have no idea where to start.

Consider using what is commonly called in programming as a Finite-state machine.  Advance to the next state each time the button is pressed.  Start out with 3 states and advance to the next after pressing the button.  You many need to double the number of states after adding your message to the program.  This is because you will want to press the button and only print the message once then advance to a new state where all you do is wait for the next button press.
Note, a mechanical device such as a button will need to be de-bounced either in hardware or in software.  This is because the processor may see individual makes and breaks as the button is closed and opened causing it to advance to the next state in unexpected ways.

Put more simply: Make sure your code to respond to button presses "debounces" the button presses. Then add a global variable pressCount, initialized to 0. In the code that handles button presses, increment pressCount and use it to display the appropriate message. (Then you need to decide what to do on the 4th button press. Do you reset to 0 and start over? Do you ignore button presses after the 3rd?)


text:
D1 mini / esp8266 WifiManager
So i have a D1 mini that I want to connect to the wifi.
I found the following code on the internet that is supposed to start a web server, that you can visit and then connect to the chosen wifi through the website. It will then remember the settings and try to connect to that wifi next time before it starts a web server - which is just what I need!
The problem is that when I connect to the wifi the d1 mini thinks it did just than - but when I visit my router and check it is not connected.
I cannot figure out why it thinks it's connected but is not, can anyone help me?
#include <FS.h>                   //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

void setup() {

  Serial.begin(115200);
  Serial.println();

  //WiFiManager

  WiFiManager wifiManager;

  //reset settings - for testing
  wifiManager.resetSettings();

  IPAddress _ip = IPAddress(192, 168, 0, 35);
  IPAddress _gw = IPAddress(192, 168, 0, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
  if (!wifiManager.autoConnect("WemosAP", "ConfigureMe")) {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.reset();
    delay(5000);
  }
  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}
void loop() {
}

btw: the ip 192.168.0.35 is free, and I have checked both the gateway and the subnet mask from my laptop by running ipconfig in cmd.

remove resetSettings()

So it seems like the code is just broken. I found an example from the WifiManager library that is called "autoconnect". This just seems to do the exact same thing, just by also working:
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager

void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

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

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if(!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

}

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

}