text:
Nodemcu and NRF24L01
I will start by asking can the nodemcu and nrf24l01 be setup as a receiver.Im trying to read basic pir sensor data sent from arduino nano and  a nrf24l01 set as transmitter. I want to receive this data on nodemcu and a nrf24l01 set as a receiver. The problem is nodemcu serial monitor and tft display is showing nothing. The nrf's rec/transmitter work perfectly when connected to arduino nanos. My loop code will not cyle on the esp8266 and nrf24l01, which is verified by no data on the tft display and serial monitor showing no received data. If I disconnect either sck, mosi or miso the loop code will cycle but no data is received.
My connections
Nodemcu       NRF24L01
D8 -----------> CE
D3 -----------> CSN
D5 -----------> SCK
D6 -----------> MISO
D7 -----------> MOSI

My connections
 Nano           NRF24L01
Pin  7 ---------> CE
Pin  8 ---------> CSN
Pin 13 ---------> SCK
Pin 12 ---------> MISO
Pin 11 ---------> MOSI

!!!!!!Nodemcu and NRF24 Code!!!!!
#include <SPI.h>
#include "RF24.h"

#define CE D8
#define CSN D3
RF24 myRadio (CE, CSN);

 byte addresses[][6] = {"0","1"};

struct package
{
  int id=0;
  float VALUE = 0.0;
  char  text[100] ="empty";
};
typedef struct package Package;
Package data;

int led = D0;

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

  myRadio.begin();
  myRadio.setChannel(115);
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate( RF24_250KBPS ) ;
  myRadio.openReadingPipe(1, addresses[0]);
  myRadio.startListening();
  delay(1000);
}

void loop()
{

  if ( myRadio.available())
  {
    while (myRadio.available())
    {
    myRadio.read(&data, sizeof(data));
    Serial.print("\nPackage:");             //Serial Monitor Text
    Serial.print(data.id);                  //id of data packag
    Serial.print("\n");                     //newline
    Serial.println(data.VALUE);       //text to receiver line 2
    Serial.println(data.text);  //text to receiver line 3

    digitalWrite(led, HIGH);
    delay(500);
    digitalWrite(led, LOW);
    delay(500);
   }

   }
}

!!!!!!Nano and NRF24 Code!!!!!

#include "RF24.h"

RF24 myRadio (7, 8);
byte addresses[][6] = {"0", "1"};

struct package
{
  int id = 1;
  float VALUE ;
  char  text[100] = "Sensor <1> Transfer";   //text to receiver
};
typedef struct package Package;
Package data;

const int pinSensor = 4; // output signal pin of laser module/laser pointer
int PirSensor = 3;

int led = 2;
void setup()
{
  pinMode(pinSensor, INPUT); // set the laser pin to output mode
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(115200);

  myRadio.begin();
  myRadio.setChannel(115);
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate( RF24_250KBPS ) ;
  myRadio.setCRCLength(RF24_CRC_16); // Set CRC length to 16-bit to ensure quality of data
  myRadio.openWritingPipe( addresses[0]);
  myRadio.stopListening();
  delay(1000);
  }

void loop()
{
 PirSensor = digitalRead(pinSensor); // receiver/detector send either LOW or HIGH
  if (PirSensor == 1){
    data1.VALUE = 1.00;
    Serial.print("Motion ");
    Serial.println(data.VALUE); // send value to console

    myRadio.write(&data, sizeof(data));

  Serial.print("\nPackage:");
  Serial.print(data.id);
  Serial.print("\n");
  Serial.println(data.VALUE);
  Serial.println(data.text);

  digitalWrite(led, HIGH);
  delay(500);
  digitalWrite(led, LOW);
  delay(500);
  }
else{
    data.VALUE = 0.00;
    Serial.print("No Motion");
    Serial.println(data.VALUE); // send value to console

    myRadio.write(&data, sizeof(data));

  Serial.print("\nPackage:");
  Serial.print(data.id);
  Serial.print("\n");
  Serial.println(data.VALUE);
  Serial.println(data.text);

  digitalWrite(led, HIGH);
  delay(500);
  digitalWrite(led, LOW);
  delay(500);
}
}

You should probably start by validating the SPI and control connections.  Perhaps you can write a simple sketch to read an nRF24 register and print that via serial.  Do you have a scope or logic analyzer you can probe with?   At the least double check that your ESP8266 pin assignments are correct for an SPI peripheral.

you might want to look into ESPNOW, it kinda obsoletes the nrf chip...


text:
(Neopixels) How to keep the pixels of the same colour despite increasing brightness?
I've been doing a fade function for the NeoPixels. However, the moment I have maximum brightness for the pixels, I noticed there 2 colours even though in my function I have only specified one colour.
Some strips are one colour and the others are another colour. I
specified the colour to be blue for the strips however many strips are blue and the strips nearer the end are green (but closer to a blue-green colour).
Is there any way to keep the colour even when the brightness changes? I've read somewhere online a different colour is seen with different brightness levels i.e. setPixelColor(brightness, r,g,b).
I've also tried FastLED library and followed documentation. However, the lights are not doing what it has said in the codes, I've tried leds[i].fadeLightBy(200) and it has given me no result.
My code for the fade function (edited from http://moving-rainbow.readthedocs.io/en/latest/guide/fade-in-and-out/):
void fade(uint32_t color) {
  for (int i = 0; i < 255; i++) {
    for (int q = 0; q < strip.numPixels(); q++) {
      strip.setPixelColor(q, Wheel((color) & 255));
    }
    strip.setBrightness(i);
    strip.show();
  }

  //decreasing brightness
  for (int l = 255; l > 255; l--) {
    for (int p = 0; p < strip.numPixels(); p++) {
      strip.setPixelColor(p, Wheel((color) & 255));
    }
    strip.setBrightness(l);
    strip.show();
  }
}

The method "Wheel" is from the Arduino Neopixel strandtest example.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

Any advice on how I should go about doing it?

Please edit your question to clarify what you mean by "2 colours". Do you mean that some of the LEDs on the strip are one color and other LEDs are a different color? If so, is there a particular pattern to which LEDs are which color? How different are the colors?

@per1234  I've edited the question to make it easier to understand. Sorry about that. Yes, the strips nearer the end are a different colour to the one I specified i.e. at the end it's more green than blue.

I have some simple NeoPixel fading going on in this example sketch:
/*
 *
 * NeoPixels demo - fades colours (in array) up and down
 *
 */

#include <SPI.h>
#include <NeoPixels_SPI.h>

const unsigned int PIXELS = 8; // Number of pixels in the string

void setup()
  {
  ledsetup();
  } // end of setup

float patterns [] [3] = {
  { 1, 0, 0 },  // red
  { 0, 1, 0 },  // green
  { 0, 0, 1 },  // blue
  { 1, 1, 0 },  // yellow
  { 1, 0, 1 },  // magenta
  { 0, 1, 1 },  // cyan
  { 1, 1, 1 },  // white
  { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
  { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

};

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

void loop()
  {

  for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
    {
    // fade up
    for (byte m = 0; m < 100; m++)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for

    // fade down
    for (byte m = 100; m > 0; m--)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for
    } // end of for each array item

  } // end of loop

This is using the simple NeoPixel library that I wrote using the SPI hardware. The library with the exact code above is available here.
Basically the fading is done by multiplying the floating-point values for the R/G/B values by a constant from 0 to 100 (you could make it 0 to 255).
Since the colours themselves are expressed in the range 0 .. 1 then the result of the multiplication would be 0 to 255. To my naked eye the colours seem true at all brightnesses.
To use the library on your Uno just connect +5V, Gnd, and the data pin is MOSI (D11 on the Uno).

source: Stack Exchange

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

sort: votes


text:
Strange discrete errors when reading HC-SR04 sonar sensor
I'm experimenting with an HC-SR04 sonar sensor. Basically I'm measuring the distance to a cardboard box twice a second with these lines of code running on an ESP32:
unsigned long sonarMeasure() {
    digitalWrite(TRIGGER, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGGER, LOW);
    return pulseIn(ECHO, HIGH);
}

double distance = duration * 0.03455;

The results are a bit strange. I know, that I can't expect millimeter accuracy. But why are there rather discrete jumps of about 4 mm? And when looking closer, there is another frequent jump of <1mm:

(As far as I can tell, the jumps increase at larger distances.)
Is this an issue of how I read the sensor on the ESP32, or is it something happening internally on the HC-SR04?
I'd love to understand the reason for this effect to be able to improve the accuracy of my measurements.

And how exactly are you calculating the distance?

@gre_gor: double distance = duration * 0.03455 (I'll add it to my question.)

I think it's from the HC-SR04... it uses echos and it seems your bad readings are some kind of echo reflections.
What you should do is either remove the bad readings, or take the average/most common value of the last x readings.
Or throw away values too far off some default (like the last average) and average the rest.

Sure, I could implement some kind of filter. But actually I want to use it on a moving platform, so I can't repeat any measurement.

No, the spacing is much to small to be multiple reflections.  For that to occur, you'd be seeing multiples of the base reading, rather than a distribution around a basic value.

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


text:
Transmitting signal from a Photon Redboard to an Arduino Uno
I am doing a basic electronics course revolving around the Internet of Things*, and we have to make a final project to present what we have learnt.
* Hear me out - I don't think this belongs on IoT SE, since the question is electronics-based
My project involves lighting up an LED matrix with predefined input from the web.
There are three factors causing a problem for me:

The LED matrix only seems to work on an Arduino (even though the programming language and setup are very similar), and we only have Arduino Unos available to us.
We are required to use a Photon Redboard to receive/send data through the internet.
The code running the LED matrix interferes with the TX/RX terminals on the Arduino since it uses the SPI bus, so after turning on the LED board I cannot receive any data from the Photon Redboard through the TX/RX pins (0 and 1).

Main question (to avoid the XY problem):
How could I receive digital data on the Arduino Uno from the Photon Redboard without using the serial ports?

What I have done to try to fix the problem:

Google-fu didn't turn up anything.
Changing the location of serial use in the programming - it works before the SPI bus is initialised but not after, which is useless for me since changing the board in response to an input from the Photon Redboard is the point of my project, and I can't change the board if it's not on.
Connecting a digital port programmed for output on the Photon Redboard to a digital port programmed for input on the Arduino Uno — this gives a value on the Arduino Uno that seems to switch between HIGH and LOW every few seconds, regardless of how the Photon Redboard is programmed to send values.

Subquestion(s):
If I am connecting the boards as described above, do I need to ground/insert current into the connection, and if so, is there a particular board this needs to be done on?
(Out of curiosity, also, what is causing the value to flip like this?)

Checking the components individually - the LED matrix works fine by itself, serial over TX and RX works fine by itself, the digital pins work fine by themselves (NB: tests were carried out with an LED or a button to provide visual feedback).

Here are pictures of both the Photon Redboard and the Arduino Uno for reference (click on images for better resolution, Arduino just shows circuitry without chips etc.):

Sources: Sparkfun and Arduino main websites

The code that seems to interfere with the Serial is below (directly copied from online here):
//----------SPI BUS SETUP----------
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR1);  //Enable SPI HW, Master Mode, divide clock by 16

//Set the pin modes for the RGB matrix
pinMode(DATAOUT, OUTPUT);
pinMode(DATAIN, INPUT);
pinMode(SPICLOCK,OUTPUT);
pinMode(SLAVESELECT,OUTPUT);

//Make sure the RGB matrix is deactivated
digitalWrite(SLAVESELECT,HIGH);
//----------END SPI BUS SETUP----------

The four lines of pinMode(PIN,I/O) refer to pins 10-13 (in standard SPI order, but I can't remember what order that is and I don't have access to the code).

A quick google search says the photon board has an spi port.  So, send the LED commands directly from the photon board to the LED controller and leave out the Arduino.

Then start from the datasheet of the LED module and write your own code for the photon board.

The code running the LED matrix interferes with the TX/RX terminals on the Arduino since it uses the SPI bus - the TX/RX pins are not used for SPI.

Why would you presume that? What internal variables?

@NickGammon I assumed that since when moving lines of code around I observed that serial worked before SPI bus setup and serial did not work after SPI bus setup. I cannot think of another reason that that could happen - everything else works fine. (As an aside, maybe we should move this conversation to chat?)

I don't see any lines of code in your question.

@NickGammon I've edited it in.

Hmmm. I'm reminded of the web page Snippets R Us. Without knowing what the constants DATAOUT etc. have as values, your snippet tells us nothing.


text:
Const data optimisation for Arduino
I'm taking a course on Arduino Uno programming and on today's talk I heard that the const data is optimized by Arduino, so that it occupies less space than the actual data type (namely, a const int occupies less than an int).
If instead of int I use const uint8_t, const uint16_t etc. is the optimization still applied, or does using the 8 and 16 bit ints represent bad practice?

Your interpretation is not accurate.

This question is not really about the Arduino. It is about GNU C/C++ compiler optimizations.
By adding the keyword const the compiler can do a lot of optimization. One is that the value does not need to be stored in SRAM. The value can end up as part of an instruction, become part of an expression that is evaluated at compile-time, etc.
In the Arduino-GPIO library static const member data is used to allow the compiler to optimize to a single instruction digitalRead() with almost X100 performance improvement (on Arduino Mega).
Check GCC and AVR optimizations for further details.

http://www.nongnu.org/avr-libc/user-manual/using_tools.html
https://gcc.gnu.org/wiki/avr-gcc
http://www.linuxjournal.com/article/7269

Cheers!

You can write code in such a way that the compiler can use further optimizations. You can also use compiler options to tell the compiler to "try harder". The IDE gets the compiler options from the platform.txt file. See "compiler.c.flags" etc.

@LookAlterno I went digging for iron and found gold

Const memory will still store ts value both in Flash and in SRAM. For arrays PROGMEM can be used and for strings F() to remove the copy to SRAM.
Normal (non const) memory will be stored in SRAM. And if it is initialized with a value, that value is stored in Flash.
However, uint8_t will always occupy 1 byte, and uint16_t always two bytes.
You can read more about the different types of memory and F here.
You can read more about program here.
Update:
Test with const:
const uint8_t  Amount1 = 4;
const uint8_t  Amount2 = 4;
const uint8_t  Amount3 = 4;
const uint8_t  Amount4 = 4;
const uint8_t  Amount5 = 4;
const uint8_t  Amount6 = 4;
const uint8_t  Amount7 = 4;

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print(Amount1);
  Serial.print(Amount2);
  Serial.print(Amount3);
  Serial.print(Amount4);
  Serial.print(Amount5);
  Serial.print(Amount6);
  Serial.print(Amount7);
}

Result: 1758 bytes of program storage space, 184 bytes of dynamic memory.
Same without word 'const:
Result: 1758 bytes of program storage space, 184 bytes of dynamic memory.
No difference
using #define Amount1..7 4
Result: 1702 bytes of program storage space, 184 bytes of dynamic memory.
Conclusion: to save Flash space, use #define instead of (const) uint8_t.
However, also see Jot's experiment, it seems that code optimalization is smarter than my conclusion.

So const uint8_t will be also automatically be stored in flash?

I updated my answer, it seems there is no difference between using const or not, to save space for simple variables #define should be used.

The difference you see is probably due to #define loosing the type information: you are calling a different print() method. When AmountX is typed as uint8_t, you are calling Print::print(unsigned char, int). When you #define it with no explicit type, you are calling Print::print(int, int). It is not a general rule that #define saves flash, and loosing the type information is generally considered a misfeature.

Such a simplistic experiment can't show you what is really going on. The compiler will be optimizing out all those variables (if they even exist they will just be in registers, not RAM) - chances are it will just optimize them out to the literals since nothing else is being done with the variables. Optimization is very much a black box and can scupper any attempts to second guess it.

MichelKeijzers and @Majenko I did a few tests, and the 184 bytes means that the const data does not use any sram memory. The compiler optimizes it out of the sram memory. When I put it in sram, the sram size becomes 192. The code size can be reduced with a for loop. With a for loop, the const array makes the sram size 192, because that is indeed copied from flash to sram as you wrote. However, you underestimated the optimization of the compiler. This is for the AVR chips only, because they can not read data from flash memory (a function is needed for that).


text:
Bridging the wifi networks on nodemcu: how to set the esp8266 as wifi extender, simplest case
It seems to me that humidity is getting high in one room in the basement in my house. To monitor the situation temporarily, I would like to build a very small wifi-mesh network to exchange these humidity data to a locally installed raspberry pie server. Most of the time the networking would be in idle state, every some 5 minutes sending the humidity sensor data over mqtt to the server.
What is the simplest code that sets up an esp8266 to connect to an existing wifi network and act as an access point and wifi extender a couple of yards further?
I tried this code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "SSID_Internet";
const char* password = "qaz12345";

const char* newssid = "SSID_Extender";
const char* newpassword = "qaz12345";

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

  // set both access point and station
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAP(newssid, newpassword);

  Serial.print(newssid);
  Serial.print(" server ip: ");
  Serial.println(WiFi.softAPIP());

  WiFi.begin(ssid, password);
  int wifi_it = 0;
  int wifi_status;
  while ((wifi_status = WiFi.status()) != WL_CONNECTED) {
    Serial.println("Trying to connect to wifi");

    wifi_it++;
    delay(500);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  long rssi = WiFi.RSSI();
  Serial.print("Signal strength: ");
  Serial.print(rssi);
  Serial.println("dBm");
}

void loop(void){

}

It successfully registers the esp8266 to the wifi, sets up an AP, but if I connect to SID_Extender with my mobile phone, the internet traffic is not forwarded further.
There are projects that allows to configure multiple esps in user friendly manner, but I am wondering how to setup such an esp myself.

it's not a router, it's just something hooked up to two networks. I've never been able to get IO from both in such a situation (ap+sta), though i was trying to access an internal server, not internet. The only way i've been able to "bridge" is via a 2nd ESP and serial comm between them, but maybe there's something I don't know...

The esp8266 will not bridge the networks. You can perhaps bridge the communication from your other ep8266 on the TCP level with WiFiServer and WiFiClient. Send the sensor value to middle esp8266 running AP and it sends the value to Raspberry.
With MQTT you could create some MQTT proxy. Receive the data with WiFiServer and forward it with WiFiClient. without parsing or anything, only copying the chars between servers client and local client in booth directions
something like this (not tested):
void loop() {

  if (!serverClient || !serverClient.connected()) {
    serverClient = server.available();
  }
  if (!serverClient || !serverClient.connected()) {
    if (client.connected()) {
      client.stop();
    }
    return;
  }

  if (!client || !client.connected()) {
    if (!client.connect(raspiIP, MQTT_PORT)) {
      Serial.println("Can't connect to MQTT");
      delay(1000);
      return;
    }
  }

  while (serverClient.available() > 0) {
    client.write(serverClient.read());
  }
  while (client.available() > 0) {
    serverClient.write(client.read());
  }
}

https://www.youtube.com/watch?v=NH1rjk3Q_MU this is what most probably you mean. Do you maybe have the nodemcu C code for that?

how do you send and receive the sensor value?

How do I sent the sensor value? Over MQTT. I have a TLS enabled broker on an internal server (raspberry) inside the "home network"

then you could create some mqtt proxy. receive the mqtt message by WiFiServer and forward it with WiFiClient. without parsing or anything, just copying the chars between servers client and local client in booth directions

great idea. Do you think you have an example code for that ready maybe?

I added a  code snippet to answer

nice!!!! (I know I should not write only nice, but I cannot stop myself)

@arthur, did it help?

on the process :-)

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


text:
Having problem in coding Arduino Uno
I'm making a timer program which takes the Time Duration as input from the user by two button switches (one for 'up' and one for 'down'), and after pressing an another button switch ('start'), the timer starts. During countdown, an LED glows, and after the end of the countdown, it turns off.
The elapsed time is displayed on a 7 seg. display, as a minute count.
#define segA 2
#define segB 3
#define segC 4
#define segD 5
#define segE 6
#define segF 7
#define segG 8
#define pinsig 0

const int buttonPinUp = 12;
const int buttonPinDown = 10;
const int buttonPinStart = 9;

int COUNT=0;
int buttonStateUp = 0;
int buttonStateDown = 0;
int buttonStateStart = 0;
int flag;

void setup()
{
    for (int i = 2; i < 9; i++)
    {
        pinMode(i, OUTPUT);
    }
    pinMode(pinsig, OUTPUT);
    pinMode(buttonPinUp, INPUT);
    pinMode(buttonPinDown, INPUT);
    pinMode(buttonPinStart, INPUT);
}

void loop()
{
    buttonStateUp = digitalRead(buttonPinUp);
    if (buttonStateUp == HIGH)
    {
        COUNT++;
        delay(200);
    }
    buttonStateDown = digitalRead(buttonPinDown);
    if (buttonStateDown == HIGH)
    {
        COUNT--;
        delay(200);
    }
    buttonStateStart = digitalRead(buttonPinStart);
    if (buttonStateStart == HIGH)
    {
        flag = HIGH;
    }

    if (flag == HIGH)
    {
        if (COUNT > 0)
        {
            digitalWrite(pinsig, HIGH);
            COUNT--;
            delay(2000);
        }
        if (COUNT == 0)
        {
            flag = LOW;
            digitalWrite(pinsig, LOW);
        }
    }

    switch (COUNT)
    {
        case 0:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, LOW);
            break;
        case 1:
            digitalWrite(segA, LOW);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, LOW);
            digitalWrite(segG, LOW);
            break;
        case 2:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, LOW);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, LOW);
            digitalWrite(segG, HIGH);
            break;
        case 3:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, LOW);
            digitalWrite(segG, HIGH);
            break;
        case 4:
            digitalWrite(segA, LOW);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 5:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, LOW);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 6:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, LOW);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 7:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, LOW);
            break;
        case 8:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 9:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
    }
}

But the program is not working as I expected.
I'm new in programming, so know a little basics. Can anyone help me in that ?

Have you tried to have a program to only light the LED for a hardcoded amount of time?

This will only run while you hold the start button, and will only update after each minute, but you won't see anything until you've held it down for a full minute.  Your program is full of oddly redundant statements.

You also need to describe exactly how the program is working...don't just say "not as I expected".

see the BlinkWithoutDelay example in IDE Examples menu

what is the purpose of COUNT = COUNT;?

as chris mentioned it will only run when you hold the start button, you can define a boolean and when start button pressed change that to TRUE and IF that's true rest of your code will run, ELSE do something else... also change that 1 minute delay to 10 seconds for testing, you can increase it later on...

Thank you for the suggestions. I made some changes in my code. But, I didn't have the idea about defining a boolean, I used  an integer 'flag' (experimentally), which remains HIGH, even after releasing the Start button, until the countdown is completed. It served the purpose properly. Now the program is working as expected. Thank you for your help.

I re-indented your code in order to make it human-readable (we are humans here). In doing so, I noticed an extra closing brace. If your code doesn't compile, that's the reason. If it does compile, please, make sure that the code you post is the same as the one you are discussion in your question.

I properly didn't know the formatting code for uploading c++ programming code here. Thank you for editing that in a proper way, Mr. Edgar Bonet. Now it looks normal to me too. And yes, there was an unnecessary closing brace in the program. I deleted it from my program, after seeing the compilation error. I forgot to change it here. Sorry about that. But, the actual problem in the working of my project was for a different reason. I didn't use the 'flag' in the code (for keeping the switch case function running). Now, after using that 'flag', it is running properly.

To format your code, press Control-T in the IDE.  It handles all that infection for you and makes brave errors stick out like a sore thumb.

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


text:
Using an NPN transistor as a switch to turn on/off a DC Motor
I am trying to control a 3V DC motor (FA-130) with my Arduino Uno, and am trying to do that using an NPN transistor (2N3904) as a switch, as shown in this diagram.

I used the Blink example and modified the pin used for the output to be the one attached to the transistor's base (e.g. pin 2 in the diagram).
The motor does nothing. If I replace the motor with an external LED component it works, blinking on/off every 1 second. If I connect the motor directly to my Arduino's 5V and GND (or even 3.3V and GND) then the motor runs fine.
Why does the motor not run when connected using the transistor? Is there a significant enough drop in voltage/current/something else?

It depends on the transistor. You might not be driving it to full saturation, or it's "on resistance" may be too high to pass enough current to drive the motor. You'd need to tell us the specific transistor, as well as the specs on the motor before we could figure out what's going on.
An LED draws a whole lot less current than a motor, so the transistor may not have any problem powering your LED. (You usually need a current limiting resistor when you drive an LED from 5V to avoid burning it out.)
I would suggest using a MOSFET transistor instead. This one, for example, can drive up to 30A at 60V: https://www.adafruit.com/product/355
It has very low on resistance, and is fully turned on by a 5V CMOS logic output, and requires very little current through the base to turn it on.
As CrossRoads pointed out, if you're using an NPN or other BJT transistor you really need a current limiting resistor between the Arduino output and the gate so you don't draw too much current from the Arudino pin and fry it.
Note that regardless of what type of transistor you use, you need a "flyback diode" on the motor to protect the transistor from back EMF from the motor's inductive coils. Without a flyback diode you run the risk of destroying your transistor.

The transistor is 2N3904. The motor is FA-130, I will update the question with that info. What specs do I compare? Arduino "Output Current Limit", transistor "peak collector current", and DC motor "Stall current"?

Collector current is 200mA, its peak is 300mA. DC motor's "no load current" is 150mA, and Arduino's "output current limit" is 500mA~1A. It seems like the motor should draw enough current to at least start turning?

Arduino has no output current limits. If you attempt to draw too much current, the 5V regulator may just overheat and shutdown, or it may fail catastrophically, or the reverse voltage protection diode may die.  If current is coming from the USB connection, the USB polyfuse may overheat and open, or the PC for example might complain of a surge and shut down the port.

The IO pins are similarly not current limited.  You may have blown the pin driving the transistor base.  The base pin acts like a diode to Gnd, with Vbe from 0.6V to 0.85V  https://www.mccsemi.com/pdf/Products/2N3904(TO-92).pdf  If the '328P is hot to the touch, that's an indication you blew the output pin's internal protection diodes.  Replace the chip.  If not, try a different pin and put a 120 to 150 ohm resistor between the Arduino pin and the transistor base to limit current flow.

@CrossRoads I thought the Arduino's 5V regulator had a protection circuit and would shut down if you drew too much current. I was mistaken?

I would say you are partially mistaken.  I have answered numerous questions in the Arduino.cc forum where the regulator failed outright from overheating. At the same time, I have personnally seen it work as intended. I made a project powering 4 MAX7219 chips driving 8x8 LED matrices. Powered from 9V, after a few minutes the regulator would shutdown, restart, shutdown, restart. Powered from 7.5V, the power was steady.  So I would offer that whether the shutdown works as intended seems to depend on how fast the regulator heats up. 12V into the barrel jack and high current is a no-go.

@CrossRoads I doubt that I've blown the pin as the setup above does work when I switch out the motor for an LED (as described in my question). I also tried using a separate power source for the motor (but connected the grounds together) but still no movement on the motor.


text:
MOSFET dimmer IR controlled
I am trying to make a group of LED dim with PWM to a MOSFET. The code seems to work for this, but the trouble is that the IR receiver will only receive the signal to turn on the lights and then IR receivers onboard LED goes to a permanent dim state (which is suppose to be off completely).  It then refuses to take input until a Arduino reset is preformed.  I purchased another IR receiver and placed it in the same configuration and it work exactly as intended I could brighten the LEDS and I saw the PWM stretch on my oscilloscope with every click of my remote.  The trouble is that the receiver quickly quit working at this point I think there is a problem with my circuit.  I am attaching the circuit diagram in hopes that someone can help.
Thanks,
Billa
#include <IRremote.h>

int led = 9;
int led2 = 10;
int brightness = 0;    // how bright the LED is
const int RECV_PIN = 7; //IR Receiver Pin
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();

}

void loop() {

  analogWrite(led, brightness);
  analogWrite(led2, brightness);

  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == 0xFF906F) //if the button press equals the hex value 0xC284
    {
        Serial.println("Triggered U");
        brightness = brightness + 5;
    }

    if(results.value == 0xFFE01F) //if the button press equals the hex value 0xC284
    {
        Serial.println("Triggered D");
        brightness = brightness + 5;
    }

    irrecv.resume(); //receive the next value
}

  delay(100);
}

What is the receiver?

that sure is an ugly schematic

what's mosfet part number? why there isn't a resistor between arduino and mosfet?

I don't think, that a resistor between Arduino and MOSFET is really necessary, since a MOSFET normally has only a very small capacitance. But a current limiting resistor for the LEDs would be good

@jsotola That's what you get for using Fritzing...

@chrisl It is probably LED strips with built in resistors (since it's powered from 12V). Also the LEDs are backwards, but we'll overlook that ;)

@newbie A resistor is not strictly needed. I add a 100Ω resistor normally just to limit inrush current to the gate when switching, but then I usually use more powerful MCUs with a lower current rating on each pin than an 8-bit AVR.

The receiver is a MagicW Digital 38khz Ir Receiver. The MOSFET part number is P30NO6LE. I have also appended the code to the bottom. Sorry for the ugly schematic. If there is a recommend format for Stack Exchange schematics I'd be happy to remake it in that more readable format.

@ZackGarris - There is a recommended format for drawing schematics: https://electronics.stackexchange.com/questions/28251/rules-and-guidelines-for-drawing-good-schematics

Question about MOSFET gate resistor: https://electronics.stackexchange.com/questions/68748/question-about-mosfet-gate-resistor

@VE7JRO So you think this could be caused by Ringing (parasitic oscillation)?

The first error I see with the sketch is right under this line of code Serial.println("Triggered D");. You are incrementing the variable brightness when you probably meant to decrement it.
The second error is with your call to analogWrite(). This function accepts an integer between 0 and 255. You do not constrain the value to that range, and can see what I mean by adding this line of code Serial.println(brightness); right above this one irrecv.resume(); in your sketch. Going from 0 to -5 turns the LED from off to maximum brightness. Is this what you want it to do?
The errors with your MOSFET circuit is a "General Electronics" question, and should be asked on electronics.stackexchange.com. As I mentioned in one of my comments to your question, there is a recommended format for drawing schematics.
My other comment was regarding this Q+A at EE. You won't find a consensus on exactly how to use a MOSFET there either, but the image in this answer may be helpful to you.

Thank you for your help.  I tried the ringing solution with no luck. I'll move my question to over the General Electronics and see.


text:
My device doesn't recognize my Arduino
I'm planing to use the ESP8266 to create a web server as a start. My set up is: Arduino nano- Esp8266- Logic level converter  as shown in the diagram.

After I connected everything my device doesn’t recognize the Arudion’s USB serial port, but when I disconnect everything from the breadboard and connect the Arduino alone it show up as COM3 and when I put the circuit back again and hock up the USB to my device it no longer show up.
I’m having the issue on both win 10 and mac.
Whenever I connected the usb cable to my computer the ESP8266 flashes a light for ones.

what is your question?

Why doesn't my device recognize the Arduino when the ESP8266 is connect

The Nano cannot power the ESP8266. It has an absolute maximum limit of about 50mA from the 3.3V pin, since it is provided by the USB interface chip. By drawing too much current (the ESP8266 needs hundreds of mA) the USB chip stops functioning.
You need an external 3.3V regulator to power the ESP8266.

I will try using an external source. but both the 5v and 3v are Connected to the chip doesn't that provide enough?

@Jacob No. You need at least 350mA but you only have 50mA. You need lots lots more power.


text:
My push button code doesn't work properly
I'm using an OLED display connected to a push button.  I am trying to get my display to show two different values independently  by using the push button to switch between them. Here is a snap of my code from the loop function:
    if (buttonState == HIGH) {
    x=x+1;
  }
  if (x == 1) {
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print(T);
  display.print(" degree");
  display.display();
  display.print(x);

}
    else if (x == 2) {
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print(perventage);
  display.print(" %");
  display.display();
  display.print(x);
}
    else  {
      x=1;
      }

  delay(10);
}

x is defined as 1 initially out side the loop.
What happens is that when the circuit is turned on, the screen displays the value of T then what should happen is when I push the button it switches to the second value which is percentage, and I push again to go back to T. My issue is that the Arduino doesn't response to the push button all of the time sometimes it takes 1 click and other times it takes 6 or 8 fast clicks to switch between them and it doesn't stick to a specific number of pushes to switch.
What would you suggest me to change to fix it.
Edit: here is pic of my wiring diagram

How is your button wired?

It should switch between the values from 1 push as it's designed from the code, but In reality it rarely switches between values from 1 push, it takes 4,5,6,8 pushes just to get it to switch between values. I don't understand why it behave like that

Yes, that's what you said in your question. But I asked "How is your button wired?", not "Reiterate what you said in your question about how you want it to behave".

Please show a picture of how you have your button connected to the Arduino.

how i the push button connected to the oled display?

the picture shows that the pushbutton is not connected to any data lines

sorry I for got to add a wire from one of the top pins to pin number 2 in the picture, I have it connected on my breadboard circuit

One core problem is that you have a simple "If the button is HIGH then cycle through the numbers". The longer you hold the button the more times it will cycle through the numbers.  It's pure 50/50 chance that you happen to release the button on a different number to the one it started on.
Instead you need to look for a change in the state of the button. Has it changed from LOW to HIGH:
static uint8_t oldState = LOW;

uint8_t buttonState = digitalRead(BUTTON_PIN);
if (buttonState != oldState) {
    oldState = buttonState;

    if (buttonState == HIGH) {
        // This only runs once at the moment of pressing
        // the button - not continuously while you're
        // holding the button in.
        // Cycle through your displays here.
    }
}

You are reading the raw button state without debouncing it, so you may be getting 2 (or 4, or ...) pulses so quickly - off the same button-push - that the display or your eye can't respond that quickly. Here is Nick Gammon's tutorial on switches and buttons, including debouncing.
Also make sure you use a pull-down resistor on the button input-pin. Floating inputs are noise and will give you a lot of false signals.


text:
Using Arduino to Record analog signals with SPI ADC + Sampling Rate Issue
I am using Arduino UNO to Read 8-channel, 24-bits resolution Analog signals using ADS1299 Analog-fornt-end. ADS1299 use SPI interface to talk with Arduino. Currently, I can record the analog signal with arduino based on the SPI protocol and send the data via serial port to the PC.
The ADS1299 has 8 channels with 24-bits resolutions. The sampling rate can be defined from 250s/s to 16Ks/s. As you can see in the below code, when the data is ready I put the device in reading data mode and store 8-bits (1-byte) in each run and concatenate 3 bytes to make a full sample. I repeat these procedures to obtain the whole samples of all channels. At the end I have sent a sample of one channel to the serial port using serial.print command.
Here is my problem: If I want to increase the sampling rate of device to e.g 10 Ks/s the arduino fails to provide this sampling rate due to  delay produced by Serial.println command. Is is possible to store the data into a big array and then send the whole array via serial port?  Is it possible that other types of microcontroller such as ARM types handle this issue? Generally how it is possible to avoid the delay of serial print?
    #include <SPI.h>
    #define WAKEUP 0x02
    #define STANDBY 0x04
    #define RESET 0x06
    #define START 0x08
    #define STOP 0x0a
    #define RDATAC 0x10
    #define SDATAC 0x11
    #define RDATA 0x12
    #define TESTaa 0xaa
    #define TEST55 0x55

    #define CONFIG1 0x01
    #define CONFIG2 0x02
    #define CONFIG3 0x03
    #define CH1SET 0x05
    #define CH2SET 0x06
    #define CH3SET 0x07
    #define CH4SET 0x08
    #define CH5SET 0x09
    #define CH6SET 0x0A
    #define CH7SET 0x0B
    #define CH8SET 0x0C

      const int PIN_START = 7;
      const int IPIN_DRDY = 9;
      const int PIN_CS = 10;

      const int DOUT = 12;
      const int DIN = 11;
      const int PIN_SCLK = 13;
      const int PIN_RESET = 8;

      byte chSet;
      byte chSet2;
      boolean flag = false;
      long t0, t;

    void setup(){

      // You can use serial communication for debugging
      Serial.begin(2000000);
      Serial.flush();
      delayMicroseconds(100);
      // You have to set SPI communication according to datasheet
      SPI.setDataMode(SPI_MODE1);
      //SPI.setClockDivider(SPI_CLOCK_DIV16);
      SPI.setBitOrder(MSBFIRST);
      SPI.begin();

      pinMode(DOUT, OUTPUT);
      pinMode(PIN_SCLK, OUTPUT);
      pinMode(PIN_CS, OUTPUT);
      pinMode(PIN_START, OUTPUT);
      pinMode(IPIN_DRDY, INPUT);
      pinMode(PIN_RESET, OUTPUT);

      //reset communication, see datasheet
        digitalWrite(PIN_SCLK, LOW);
        digitalWrite(DIN, LOW);
        digitalWrite(PIN_CS, HIGH);

      digitalWrite(PIN_CS, LOW); //Low to communicated
      SPI.transfer(RESET);
      digitalWrite(PIN_CS, HIGH); //Low to communicated

      // Wait longer for TI chip to start
      delay(500);
      send_command(SDATAC);
      delay(10);
      chSet = read_byte(0x00);
      Serial.println("-- ID CHIP is:" + hex_to_char(chSet) );

      // Write Config 1 and 2: see datasheet page 47
      // Config 1: Bits 7 6 5 4 3 2 1 0 --- 1 DAISY_EN=1 CLK_EN=0 1 0 DR[2:0] (110-- 250 Sample/S)  --->   0b11010110
      // Config 2: Bits 7 6 5 4 3 2 1 0 ----  1 1 0 INT_CAL=1(Int/Ext test sig) 0 CAL_AMP=(calibration signal amplitude)
      // CAL_FREQ[1:0] (calibration signal frequency)  ----->  0b11010100

      // for normal operation write to config1 0x02, config2 0xA0. For test signal write 0xA3 to config2
      write_byte(CONFIG1, 0x96);   // Daisy chain Enabled: D6 , Daisy chain Disabled: 96
      delay(10);

      write_byte(CONFIG2, 0xD1);   // Test signal Enabled: D0   Test signal  Disabpled: C0
      delay(10);

      write_byte(CONFIG3, 0xE0);   // INT Reference Enabled: E0    else  INT Reference Disabled: 60

      delay(1000);
      //this part is just to check if you send and read correct data
      Serial.println("Check Configs");
      chSet = read_byte(CONFIG1);
      Serial.println("CONFIG1: Received " + hex_to_char(chSet) );
      chSet = read_byte(CONFIG2);
      Serial.println("CONFIG2: Received "  + hex_to_char(chSet) );
      chSet = read_byte(CONFIG3);
      Serial.println("CONFIG3: Received "  + hex_to_char(chSet) );

      //remember that ch1 is used for respiration! use channel 2 for ECG measurements

       // Ch1 Setting: Bits 7 6 5 4 3 2 1 0 ---  PDn(channel power mode) GAINn[2:0] (PGA gain-- 101:  12 110 : 24)
       //SRB2 (SRB2 connection) MUXn[2:0] (channel input selection: 000 : Normal electrode input , 101 : Test signal )

       /// Input Channel Shorted  ---> 0b00000001 0X01;   Test signal Activated ---> 0b00000101 0X05;
      delay(1000);

      write_byte(CH1SET, 0x05); //
      write_byte(CH2SET, 0x05); //
      write_byte(CH3SET, 0x05); //
      write_byte(CH4SET, 0x05); //
      write_byte(CH5SET, 0x05); //
      write_byte(CH6SET, 0x05); //
      write_byte(CH7SET, 0x05); //
      write_byte(CH8SET, 0x05); //

      Serial.println("Check Channel Settings");
      chSet = read_byte(CH1SET);
      Serial.println("Ch1: Received " + hex_to_char(chSet) );
      chSet = read_byte(CH2SET);
      Serial.println("Ch2: Received  " +   hex_to_char(chSet) );
      chSet = read_byte(CH7SET);
      Serial.println("Ch7: Received  " +   hex_to_char(chSet) );
      chSet = read_byte(CH8SET);
      Serial.println("Ch8: Received  " +   hex_to_char(chSet) );

      // Start communication, you can use RDATAC or RDATA according to datasheet
      send_command(RDATAC);
      digitalWrite(PIN_START, LOW);
      delay(150);
      send_command(START);
    //  digitalWrite(PIN_CS, LOW); //Low to communicated
    //  SPI.transfer(START);
    //  digitalWrite(PIN_CS, HIGH); //Low to communicated

    }

    boolean gActiveChan [2];
    int nChannels = 1;
    int gMaxChan=1;

    void loop(){

    // Based on the Page. 36 For the 8-channel ADS1299, the number of data outputs is
    //[(24 status bits + 24 bits × 8 channels) = 216 bits].

      delayMicroseconds(10);

         if(digitalRead(IPIN_DRDY) == LOW){
          t0 = micros();

            digitalWrite(PIN_CS, LOW);

            long output[9];
            long dataPacket;
            for(int i = 0; i<9; i++){
                for(int j = 0; j<3; j++){
                    byte dataByte = SPI.transfer(0x00);
                    dataPacket = (dataPacket<<8) | dataByte;
                }

                output[i] = dataPacket;
                dataPacket = 0;
            }

            digitalWrite(PIN_CS, HIGH);
            Serial.println(output[1]);

    // t = micros()-t0;  // calculate elapsed time
   // Serial.print(1000000/float(t));
    //Serial.println(" samples per second");
    //delay(200);

     }

            }

        String hex_to_char(int hex_in) {
      int precision = 2;
      char tmp[16];
      char format[128];
      sprintf(format, "0x%%.%dX", precision);
      sprintf(tmp, format, hex_in);
      //Serial.print(tmp);
      return(String(tmp));
    }

    // see datasheet 38
    int read_byte(int reg_addr){
      int out = 0;
      digitalWrite(PIN_CS, LOW);
      SPI.transfer(0x20 | reg_addr);
      delayMicroseconds(5);
      SPI.transfer(0x00);
      delayMicroseconds(5);
      out = SPI.transfer(0x00);
      delayMicroseconds(1);
      digitalWrite(PIN_CS, HIGH);

      return(out);
    }

    void send_command(uint8_t cmd) {
      digitalWrite(PIN_CS, LOW);
      delayMicroseconds(5);
      SPI.transfer(cmd);
      delayMicroseconds(10);
      digitalWrite(PIN_CS, HIGH);
    }

    //see page 38
    void write_byte(int reg_addr, int val_hex) {
      digitalWrite(PIN_CS, LOW);
      delayMicroseconds(5);
      SPI.transfer(0x40 | reg_addr);
      delayMicroseconds(5);
      SPI.transfer(0x00);
      delayMicroseconds(5);
      SPI.transfer(val_hex);
      delayMicroseconds(10);
      digitalWrite(PIN_CS, HIGH);

    }

Yes (though limited by the small SRAM), yes (the ones faster than the Uno) and have you tried using higher baudrates? What baudrate are you actually using? And maybe dont print, but write them to Serial

Please provide the full code. And why are you printing only the second element of output?

@chris: could you help me how can I store the output[1] in the loop and serial print the big array after a specified time. in this code I am just printing one channel, but I can print the whole channel separated by a comma and then retrieve them in the host PC.

@chris  I tried to send the whole code but the text does not seem great. Is it possible to upload the code separately?

@chrisl I figure out and add the whole code. I checked with different baudrate but I could not see any obvious effect on the sampling rate

Try changing the order of these:
  SPI.setDataMode(SPI_MODE1);
  //SPI.setClockDivider(SPI_CLOCK_DIV16);
  SPI.setBitOrder(MSBFIRST);
  SPI.begin();

I think SPI.begin() needs to be started before the other two calls.
Instead of digitalWrite to control the chip select, use Direct Port Manipulation, much faster.
Does the ADC support 8 MHz SPI clock? From 7.6 & 7.7 of the datasheet, I would say yes.
You can get rid of all the delayMicroseconds(5), (1), (10), as well, they are not doing anything for you.
"Unpack" this and just do 3 SPI.transfers in a row to read the data, doing it in a loop slows it down:
        for(int i = 0; i<9; i++){
            for(int j = 0; j<3; j++){
                byte dataByte = SPI.transfer(0x00);
                dataPacket = (dataPacket<<8) | dataByte;
            }

I would go so far as to do all 27 in a row even, then do the array manipulation/data combining when all 27 bytes are captured.

Thank you, How can I put the the whole 27 bytes in an array?

dataByte[0] = SPI.transfer(0x00);  dataByte[1] = SPI.transfer(0x00);  dataByte[2] = SPI.transfer(0x00);   ... dataByte[25] = SPI.transfer(0x00);  dataByte[26] = SPI.transfer(0x00);

Thank you for your assistance. I managed to store bunch of bytes (e.g 270 bytes) at the reading part and send the big size array in the next part. But, the problem is that during sending the big array, I lose new incoming data. Is there any way to define an interrupt and do multi-task (Sending and receiving)?

The delayMicroseconds is to allow the ADC chip time to load its registers. 5uS may be a bit long, but some delay will be necessary.  You should consult the datasheet for the ADC.

@Abed.  The Serial data is already interrupt driven.  When you call Serial.print all you are doing is loading a buffer.  It only becomes blocking if the buffer is already full.  If that is what is happening then the problem is that you have more data than you have time to send.  Adding more interrupts won't solve that problem.


text:
About split string
Sorry my English is poor.
I use nodemcu to get a json data.
By this String alldata = client.readString();
But it turn this:
  HTTP/1.1 200 OK
  Server: nginx
  Date: Sat, 10 Aug 2019 04:53:16 GMT
  Content-Type: application/json; charset=utf-8
  Content-Length: 152
  Connection: keep-alive
  X-RateLimit-Limit-day: 20000
  X-RateLimit-Remaining-day: 19968
  Cache-Control: no-cache
  Pragma: no-cache
  Expires: -1
  X-Powered-By: ASP.NET
  Access-Control-Allow-Origin: *
  X-Kong-Upstream-Latency: 23
  X-Kong-Proxy-Latency: 2
  Via: kong/0.14.1
  Strict-Transport-Security: max-age=63072000; includeSubdomains; preload

  [{"Direction":0,"EstimateTime":364,"StopStatus":0,"MessageType":0,"SrcUpdateTime":"2019-08-10T12:53:00+08:00","UpdateTime":"2019-08-10T12:53:05+08:00"}]

I need '364' to display on oled.
Is it possible to split it.Thanks!

yes it is possible to extract the value ... google arduino parsing strings

cut away the HTTP headers (until the empty line). use ArduinoJson library to parse the payload

Thanks I have solve it.


text:
Parallel I/O - maybe use Machine code function call
I'm a newbie to arduino but been programming lots.
I have a project where I would like to output 4 bits to adjacent pins and read 4 bits from another (4) adjacent pins. (Imagine a matrix keyboard application).
To do it in C-C++ would take lots of instructions (and time) but machine code
OUTPUT:
OR (mask) -> output port      ; this clears bits target bits while leaving other bits as they were
AND (newdata) -> output port  ; this sets new data into target bits
INPUT:
port -> register
AND (register) (mask) -> register
Is there a way of implementing this as a call from IDE for instance.
I have come across many systems where multi language components can be compiled into one executable.
If it is not normally done, why not? Is it something that I should avoid for some reason?
Thanks
Dave

Looks at the PORT and PIN registers (assuming AVR). They can be manipulated directly from C or C++, no need for assembly.

If you have an AVR Arduino (like Uno, Nano, ...) this is a must read for this topic in the documentation.

What do you mean by "a call from IDE"? You might want to do some tutorials to learn the basics and technical terms. There are examples for matrix keyboards, I'm sure.

Thanks Mat and Chris. Excellent info.  Juraj, I'm using a 'clone' UNO but want the thing to work efficiently keep programme to minimum. Busybee, Sorry. I know IDE is not the correct term but wanted the question to be as elementary as possible.

If it's about manually triggered mechanical buttons, rather take care to be SLOW enough to get rid of bouncing effects. While waiting a few ms until a button settles, it does not matter how you read the button states.

You can manipulate the I/O ports directly from C++ without having to resort to assembly code.
The AVR micro in your Arduino (ATmega328P) has three ports (PORTB, PORTC and PORTD) with eight pins each (Px0, Px1, ... Px7). You control the ports using three 8-bit registers. Each bit in a register represents one physical pin (LSB is pin 0, MSB pin 7):

DDRx: data direction register. A bit set to "1" corresponds to output mode, "0" to input.
PORTx: data register. In output mode, "1" sets the port HIGH, "0" sets it LOW. In input mode, controls whether pull-ups are enabled ("1") or not ("0").
PINx: input and toggle register. Read it to get the status of all eight pins of the port at once. Writing to it toggles (LOW -> HIGH or HIGH -> LOW) the selected pins (e.g. PINC = 0b00100001; toggles pins PC0 and PC5).

With an Arduino, you don't have access to all the pins of all the ports. To get the mapping between Arduino pin names and ports, look at any good Arduino pinout reference (e.g. on the Arduino Uno page in the "Documentation" tab). You can see for example that all pins of port D are available as Arduino digital pins D0 to D7 on an Uno for example. The analog pins are from PORTC.

Macros are provided (by the AVR toolchain) for port and pin names to make things easier.
For example, PORTB is an alias for the PORTB register, you can assign to it as if it was a regular C++ variable. PB5 is the index of pin 5 in port B. So setting port B pin 5 to output without affecting the others can be written as:
DDRB |= (1 << PB5);

If you wanted to set the 4 lower pins of port D to output, and the 4 others to input, you could:
DDRD = 0b00001111; // or 0x0f

Here's an example of a minimal blink sketch:
void setup() {
  // Set PB5 (D13 - builtin led) LOW
  PORTB &= ~(1 << PB5);
  // Set PB5 mode to OUTPUT
  DDRB |= (1 << PB5);
}

void loop() {
  delay(1000);
  // toggle PB5
  PINB |= (1 << PB5);
}

The assembly generated is optimal, single instructions to set or clear a bit in I/O memory:
(See See compiled assembly output (Visual Micro) for how to get it)
// setup
  PORTB &= ~(1 << PB5);
 1f4:   2d 98           cbi     0x05, 5 ; 5
  DDRB |= (1 << PB5);
 1f6:   25 9a           sbi     0x04, 5 ; 4

// loop
  PINB |= (1 << PB5);
 246:   1d 9a           sbi     0x03, 5 ; 3

Another example, that blinks a led connected to A3 only when A2 is high:
void setup() {
  // Set PC2 and PC3 LOW (A2 and A3)
  PORTC &= ~((1 << PC2) | (1 << PC3));
  // Set PC2 to input, PC3 mode to output
  DDRC = (DDRC & ~(1 << PC2)) | (1 << PC3);
}

void loop() {
  delay(1000);
  // toggle PC3 only if PC2 is high
  if (PINC & (1 << PC2)) {
    PINC = (1 << PC3);
  }
}

Again, assembly generated is quite terse:
  if (PINC & (1 << PC2)) {
    PINC = (1 << PC3);
 202:   18 e0           ldi     r17, 0x08       ; 8
 252:   32 99           sbic    0x06, 2 ; 6
 254:   16 b9           out     0x06, r17       ; 6

(The SBIC instruction is fun: skip the next instruction if a bit in I/O memory is clear.)
You can even save the use of that register r17 by using PINC |= ... in this case:
  // toggle PC3 only if PC2 is high
  if (PINC & (1 << PC2)) {
    PINC |= (1 << PC3);
 250:   32 99           sbic    0x06, 2 ; 6
 252:   33 9a           sbi     0x06, 3 ; 6

Of course you can also resort to inline assembly, but that is an art in and of itself, and the syntax a bit peculiar. But for simple things, it is straightforward:
asm("sbi 0x03, 5;"); // toggle PB5

Some references:

ATmega328P Datasheet linked from here: Microchip ATMega328P page. See section 14 "I/O ports", and 36 "Register summary" for the I/O port addresses.
The AVR Instruction Set Manual (PDF) if you want to dive into that.
The AVR-GCC Inline Assembler Cookbook for details on using GCC's flavor of inline assembly for AVR


text:
What are SerialNina and SerialHCI supposed to be used for? (Arduino Nano RP2040 Connect)
Essentially, I'm trying to figure out how I can use Bluetooth Classic using the on-board U-blox w102 Wifi/Bluetooth module. I'm assuming that SerialNina and SerialHCI are somehow connected to it and maybe the way to use Bluetooth Classic on the Nano RP2040.
The ArduinoBLE library uses SerialHCI in HCIUartTransport.cpp. It also messes with NINA_RESETN and SPIWIFI_SS a bit in  BLELocalDevice.cpp, but I'm not too worried about those.
The WiFiNINA library uses SerialNina to update the wifi firmware in SerialNINAPassthrough.ino and ESP32BootROM.cpp.
From this, I'm assuming that SerialHCI can be used to control BLE and SerialNina updates the Wifi's firmware. Am I right about this? If so, what part of the Nina-w102 module is SerialHCI connected to?

what part of the Nina-w102 module is SerialHCI connected to?

from ArduinoCore-mbed/variants/NANO_RP2040_CONNECT/pins_arduino.h
#define SerialNina      Serial3
#define SerialHCI       Serial2

#define SERIAL2_TX          (digitalPinToPinName(25))
#define SERIAL2_RX          (digitalPinToPinName(26))
#define SERIAL2_CTS         (digitalPinToPinName(27))
#define SERIAL2_RTS         (digitalPinToPinName(28))
#define SERIAL3_TX          (digitalPinToPinName(25))
#define SERIAL3_RX          (digitalPinToPinName(26))

Serial2 is configured with flow control pins, but both Serial2 and Serial3 use the same RX/TX pins wired to ESP32 NINA RX/TX.

the way to use Bluetooth Classic on the Nano RP2040:

To use classic Bluetooth on Arduino boards with esp32 NINA module you have to replace the Arduino nina-fw in the esp32 with the SerialToSerialBT.ino sketch for esp32 Arduino core.
You can flash NINA over the host MCU (rp2040) with SerialNINAPassthrough.ino sketch of WifiNINA library. More details about that are in this Arduino forum thread. (Ignore the part before my first comment there).
But with this modification there is no nina firmware, so no WiFi, no cloud. The esp32 is then like a HC-05.

Yeah I went through that thread a few times before and it seems it only worked for people with certain boards. I uploaded SerialNINAPassthrough.ino to my RP2040 without any errors. Then I attempt to upload SerialToSerialBT.ino to my RP2040 as the esp32 u-blox NINA-w102 with an upload speed of 115200. I get the error "serial.serialutil.SerialException: could not open port 'COM3': WindowsError(5, 'Access is denied.') Failed to execute script esptool the selected serial port Failed to execute script esptool  does not exist or your board is not connected." The builtin led flashes a bunch of times.

"Access is denied"? do you have the Serial Monitor open?

I closed the Serial Monitor and retried it. Now I'm getting the error "serial.serialutil.SerialTimeoutException: Write timeout Failed to execute script esptool An error occurred while uploading the sketch." I'm following the same steps I listed above. Also, the builtin led doesn't flash this time.

maybe try the upload with esptool from command line and disable the reset before upload  with -before no_reset


text:
Arduino not reacting sometimes when reading serial commands
When I am sending hex numbers via computer to the arduino leonardo, it sometimes won't react, but the serial monitor says that it was sent. My code;
    void setup()
{
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  pinMode(A0, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop()
{
  delay(100); // Wait for 100 millisecond(s)
  Serial.println(Serial.read());
  if (Serial.read() == 49) {
    Serial.println("left");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 50) {
    Serial.println("right");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 51) {
    Serial.println("backwards");
    analogWrite(9, 1023);
    digitalWrite(A0, LOW);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 52) {
    Serial.println("forwards");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, HIGH);
  }
  if (Serial.read() == 48) {
    Serial.println("stop");
    analogWrite(9, 0);
    digitalWrite(A0, LOW);
    analogWrite(10, 0);
    digitalWrite(11, LOW);
  }
}

When I send the numbers 1,2,3,4, and 0, it reads what the command does. Pins A0 and D11 are direction control for the motor controller, and pins D9 and D10 are speed.

the serial monitor prints a different byte from the one that controls the motors

Serial.println(Serial.read());
if (Serial.read() == 49) {

You are doing two reads here, not one. So you are reading and displaying, and then reading a second byte (not the one you displayed).
Much better would be:
int cmd = Serial.read();
Serial.println(cmd);
if (cmd == 49)  {
  ... do something ...
} else if (cmd == 50)  {
  .. do something else ...
}

And so on.
Also, why use numbers when you can show the ASCII characters? eg.
int cmd = Serial.read();
Serial.println(cmd);
if (cmd == '1')  {
  ... do something ...
} else if (cmd == '2')  {
  .. do something else ...
}

You may also want to consider using:
if (!Serial.available())
    return;

That way you don't test for serial data that does not exist.
Why the delay?

When I made it delay, it seemed to work better.


text:
Saving EEPROM after programming on Arduino uno
I am using an Arduino Uno,  and I use the EEPROM to store some presets. It works fine. But, when I reprogram the Arduino, the EEPROM gets wiped out. Is there a way to prevent this, and have the EEPROM not change after the Arduino is programmed?
I am using a USBtinyISP programmer.
Thank you very much for your help, and advance.
Here is the verbose result of my programming:
Sketch uses 5,298 bytes (16%) of program storage space. Maximum is 32,256 bytes.
Global variables use 286 bytes (13%) of dynamic memory, leaving 1,762 bytes for local variables. Maximum is 2,048 bytes.
/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/bin/avrdude -C/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cusbtiny -Uflash:w:/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
        Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
        Copyright (c) 2007-2014 Joerg Wunsch

        System wide configuration file is "/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
        User configuration file is "/Users/fed/.avrduderc"
        User configuration file does not exist or is not a regular file, skipping

        Using Port                    : usb
        Using Programmer              : usbtiny
avrdude: usbdev_open(): Found USBtinyISP, bus:device: 006:003
        AVR Part                      : ATmega328P
        Chip Erase delay              : 9000 us
        PAGEL                         : PD7
        BS2                           : PC2
        RESET disposition             : dedicated
        RETRY pulse                   : SCK
        serial program mode           : yes
        parallel program mode         : yes
        Timeout                       : 200
        StabDelay                     : 100
        CmdexeDelay                   : 25
        SyncLoops                     : 32
        ByteDelay                     : 0
        PollIndex                     : 3
        PollValue                     : 0x53
        Memory Detail                 :

                                 Block Poll               Page                       Polled
          Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
          ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
          eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
          flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
          lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
          signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

        Programmer Type : USBtiny
        Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
        To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex"
avrdude: writing flash (5298 bytes):

Writing | ################################################## | 100% 7.80s

avrdude: 5298 bytes of flash written
avrdude: verifying flash memory against /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
avrdude: load data flash data from input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
avrdude: input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex contains 5298 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 4.98s

avrdude: verifying ...
avrdude: 5298 bytes of flash verified

avrdude done.  Thank you.

I believe avrdude allows access to each type of memory independently, so this is probably an issue with the commands the IDE issues.  Another option is to use avrdude to backup the eeprom and then re-write it after.  Basically you need to become familiar with avrdude and figure out how you can change the way the IDE uses it.  Or else only have the IDE build your sketch, and use avrdude manually to load it.

I should clarify my previous comment was more about using avrdude for ISP; off the top of my head, I'm not sure what subset of this the bootloader supports.

You can change the fuses for Atmega328 to preserve EEPROM during chip erase (for ISP programming). Basically, if you are using USBTiny connected to the UNO by 3x2 pin header, you are using ISP programming. Which means chip erase erases also EEPROM if fuse EESAVE is 1 (unprogrammed).
Uploading over the Arduino bootloader (it means you have the UNO connected directly into the computer and there is no other device like USBTiny). The EEPROM should be preserved then.

So, are you saying that changing fuses (I have no idea how to do that) may or may not work.  But not using Arduino IDE, but rather using AVRdude in  command line should work?

@Fed EEPROM can be changed by avrdude but Arduino usually won't do anything with it (you can see whole command in the Arduino IDE if you enable verbose upload).

I updated the verbose output of Arduino IDE when I program the Arduino.  Any suggestions?

@fed The most important thing is USBTiny - it performs chip erase and without EESAVE fuse programmed to 0, it erases EEPROM too.


text:
Delay In receiving data when SoftPWMBegin(); is used from SoftPWM.h library
when i use SoftPWMBegin() function in setup there is some delay while receiving data over bluetooth. And if i pressed o and 1 fastly (see in below given code), some time it receives data and sometime not receives.
when i not using SoftPWMBegin() it receives data fastly . I think SoftPWMBegin() function creating some problem.
I want use SoftPWM.h library for controlling RGB led brightness. So please give me any solution for that...
#include <"SoftwareSerial.h">
#include <"SoftPWM.h">

SoftwareSerial Genotronex(0, 1);

int redPin = A5;

int greenPin = 3;

int bluePin = A0;

int BluetoothData;

void setup()

{

 Genotronex.begin(57600);

  SoftPWMBegin();

  }

void loop()
{

if (Genotronex.available())

   {

      BluetoothData=Genotronex.read();

   if(BluetoothData=='0')

   {

  SoftPWMSet(redPin, 0);

   }

   else if(BluetoothData=='1')
{

    SoftPWMSet(redPin, 20);

   }

}

}

I don't understand why are you using SoftwareSerial on pins where hardware one is available and why are you using SoftPWM when there are six harware PWM pins available. There is also a slight difference between Arduino Uno and Mega. So which one is really used?

Maybe you need to change the class that contains the SoftPWMBegin() or Genotronex.read() methods.
I don't know this library, can you give the link for donwload it and to try it...?

https://www.pjrc.com/teensy/arduino_libraries/SoftPWM.zip  This is the link for downloading SoftPWM library in which you find SoftPWMBegin() function...

Software PWM is quite complex and uses interrupts to emulate PWM using a timer. SoftwareSerial also uses interrupts. You can't have two things happening at once, so one wilk take precedence over the other. In this case the timer interrupt is taking precedence over the Pin Change interrupt, so the reception is delayed, which breaks SoftwareSerial since it relies on a prompt response to the interrupt to work.
You basically have to avoid the use of both software emulations together. Either switch to using the hardware UART, or hardware PWM or, even better, ditch both and go for 100% hardware driven.


text:
Error: void value not ignored as it ought to be done = radio.read(&Irms, sizeof(float));
Good morning everyone, I had this sketch that worked now when loading the program gives me an error:
#include <Wire.h>
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

float Irms ;
RF24 radio(9, 10);
const uint64_t pipe = 0xE8E8F0F0E1LL;

void setup(void) {

  radio.begin();
  radio.openReadingPipe(1, pipe);
  radio.startListening();
  Serial.println("setup() - Inizializzazione completata");
  delay(300);
}

void loop(void) {
  if ( radio.available() )
  {
    bool done = false;

    while (!done)
      delay(1000);

    {
      delay(1000);
      done = radio.read(&Irms, sizeof(float));

BTW, be careful as while loop is infinite (there is only delay(1000) and done never changes)

This statement:
done = radio.read(&Irms, sizeof(float));
is not compatible with the current <RF24.h> library.
The read() method now has this signature:
void read (void *buf, uint8_t len)
You can either adapt your code or use the ancient "maniacbug" library https://github.com/maniacbug/RF24
which has the following signature for read():
bool read( void* buf, uint8_t len );

Can you help me modify my code? Thanks

@ksalva Your code in the question appears to be truncated. Show your entire code and I will attempt to suggest a fix and add it into the answer.


text:
Can I connect a servo directly to arduino uno without a transistor?
I am going to mount an ultrasonic sensor on the servo.

Please post a link to the servo you intend to use.

The data pin you can drive directly from an arduino. The power, you have to drive from something better.

What does a sensor have to do with the question? And for that matter, what is the question about? Connect what to what? Are you talking about the power or the signal?

The Arduino's GPIO pins can drive the signal of most model servos directly, without any extra transistors.
Driving a model servo signal input is not the main problem with driving servos from an Arduino.
The main problem is trying to use the Arduino's power supply to power the model servo. With many model servo's, the amount of current the model servo needs to start, or when it is almost stopped is so big that the Arduino's power supply can't maintain 5V. As the Arduino's power supply voltage drops, the Arduino often gets reset, and the program restarts from setup.

You need a supply that can deliver current spikes and longer durations of higher current. Using  capacitors may help for the spikes.


text:
Serial Communication
When I send data using
Serial.println()
in what format does it go? I want to observe the data using the software 'Terminal'. When I observe there, if I've sent 255 using Serial.println(), I get a series of numbers 0 0 224 on the terminal. I've kept the baud rate same in both places(9600), Stop Bits as 1 in Terminal.

Bytes. Always bytes.

On the Arduino Serial.print() method web page it says:

Prints data to the serial port as human-readable ASCII text.

...which is suitable for most terminal programs.  ASCII or American Standard Code for Information Interchange is (usually) an 8 bit code for printing characters.  It is not a code which you can do normal math with.  That is the integer 1 (which is, in binary, b00000001) is not the same as the character '1' (which is, in binary, b00110001).

Example: If you want to print "123" on most terminals you can use the Serial class method print:
Serial.print(123);

Now, you have to understand that the Arduino paradigm is to make programming simple.  So the print method in the Serial class will assume you want to see the characters "123" on the terminal.  So, guessing, the print method will convert each decimal number into an ASCII character and print them out as 3 values to the terminal.  That is, the ASCII value for 1, followed by the ASCII value for 2 finally followed by the ASCII value for 3.
If this is not what you want there are other variations for the print method in the Arduino Serial class.  But all tend to print using ASCII codes.
If you want to print out the binary values, see the Serial.write() method.  This method will send the value of the argument to the terminal with out converting into ASCII code.

Example: If you want to print "1" on most terminals you can use the Serial class method write:
Serial.write(49);

...as 49 is the decimal equivalent of the ASCII code for the character '1'.

Try using terminal program on PC side. NOT Arduino Serial port monitor built into Arduino IDE.
For example try http://docklight.de/
With this or some other similar terminal program, you can see each byte not only as ASCII representation, but also in HEX or binary format.
So you will easily in no time understand difference between ASCII "224" string and single byte 224 value.
With binary format you can have much much faster PC communication especially when sending float numbers. 4 bytes vs 3.7348823457458743 for example :)
On docklight you even have possibility to define macros for sending back to Arduino i ASCII or in binary format. Or even adjustable macros to send most of the string fixed, but change one byte inside string every time when sending.
But even basic ASCII or binary representation of data is enough for now to help you understand this problematic.


text:
Problems / doubts on battery-powered Arduino Nano WiFi weather station I built
I've almost finished my first Arduino project and I'm realizing I might have gone a bit over my head - I'm a web programmer, I have a very basic electronics knowledge and started tinkering with Arduino with just a couple simple, tutorial-like small circuits.
I then started building this project of a battery-powered Weather Station that sends sensors data via WiFi to my server - I managed to have a working product but I'm bumping into issues that are starting to look a bit bigger than what they initially seemed.
The workflow (schematics follow):
On the +5V pin of the Arduino Nano (actually a cheap chinese clone) I've put an AMS1117 to stabilize down the voltage to 3.3V (the 3.3V ArduinoNano output wasn't powerful enough), and from there I power several modules; a DS3232 wakes up the Arduino (pin 2) when put in deep sleep mode (every 30 mins); when woken up I read data from the DHT11 (humidity), the BMP085 (pressure), the DS18B20 (temperature) and FC-37 (rain), I connect to my WiFi using the ESP-01, send data to my server, and put the Arduino back to sleep until the next cycle.

Everything worked when on the breadboard, worked after building the circuit with a perfboard; heck, it worked even when connected to my power supply, which is something similar to this project:
https://www.arduinolab.net/solar-li-ion-charger-and-power-supply-for-arduino/

My battery is a 3,7V 2500mA  instead, but all components are almost the same and I use a regular USB - type B cable to connect this to my Arduino Nano
But after an hour or so it stopped working - I checked again by connecting the Arduino to my PC and it appeared to be fine, but when connected to the battery everything was powered up (all leds on!) but the ESP wasn't trasmitting (never saw the flashing blue led).
So I started some reading around and I tought it might be a problem of too much current needed, and the battery wasn't enough anymore after it got under a certain voltage (I still measured 3.80V on the battery terminals though..)...
This is what I'm thinking:

to cut/remove the LEDSs from all the modules (dht, rtc, fc-37 has two!, AMS1117) to save power (it's 5 LEDs + the arduino power on LED). Is it safe? Will they still work with the LED circuitry interrupted?
connect my power source directly to the Vin+ of the AMS1117, instead of using the +5v Arduino output pin (but I read it can safely outsource 500mA, which is the limit for the USB power in anyway, so it shouldn't be an issue...)
for the "long run", use a transistor to power on the sensors when Arduino is awaken, keeping them off the rest of time to spare battery juice, if nothing else...But I really don't know how to start for this, I thought of an NPN transistor (I have a PN222A available) with Base to Arduino (through a 1k Ohm Resistor), Collector to +5V and Emitter to the AMS1117 Vin+, is this sensible?
increase power output? but how? the power source lets 5V 600mA through a regulated DC-DC booster, it should be ideal in theory...How do I understand if it's right for me?
Ditch the ESP01 in favor of the NRF24L01 (I already have a couple of these, but any other suggestion is appreciated)...but that would require a new setup, new coding (never used those modules), a "receiver" that then sends to wifi, and btw I don't know if the signal can make it from the balcony (where I plan to put the WeatherStation) to the inside of the house (I think it will, as the WiFi does - at least I think it does)

I don't really know how to actually measure the consumption of my circuit...I've read something around but, as I said, my electronics knowledge is limited, I don't have much spare time to dedicate on this, and therefore I cannot figure out without a clear guidance, sorry...
I'm not attaching my code because I don't think it's necessary - the sleep mode I'm using is SLEEP_MODE_PWR_DOWN from the avr/sleep.h library, other than that it works fine as it is.
Can someone give me suggestions or pointers on how to analyze my problem? Am I on the right track or my reasonings are off?
Thanks for any help you could provide, if you need any more info I'll do my best (in due time though, as I said I've not that much time to work on this...if I could muster 1 or 2 hours a week it would be a dream!)

You are wasting a lot of power in your system. You need to be far more efficient when running off battery.

Don't boost your battery voltage to 5V. Instead use a system that runs entirely at 3.3V.
Never use a linear voltage regulator like the AMS1117 since it just wastes power as heat. Instead use a switching "buck" regulator.
Turning off modules when not being used is a very good idea. Sleeping the Arduino only saves some of the power - the modules will all still consume power.

I would suggest the ideal way forward would be:

Remove the Arduino from the schematic completely
Replace the ESP-01 with an ESP8266 module with more pins, or better still an ESP32 module.
Connect all the sensors (optionally with P-channel MOSFETs to control the 3.3V supply to them) direct to the ESP32
Remove the 5V boost from the power supply
Connect the power supply through a 3.3V switching regulator to power the whole circuit.

I knew I was doing something wrong with power management; you know, if you look at many popular "maker" websites you often find such solutions which are good for many projects but when start biting back they do it strong. I like your suggestion of using an ESP module, I think I'll consider the ESP8266 for this (It seems the ESP32 is too much for my project). About the 3), can you point to some resources for examples or some component name? (so I can buy the right parts. Same for the 5, so I won't buy the wrong regulator). Thanks a lot, great answer

Any P-channel MOSFET that has a threshold voltage between 0V and -2V would do the job. You don't need much current handling capacity. I usually work with surface mount SOT-23 devices, so any part number I would have to hand would probably not be suitable for you.

As for a regulator, there's LM2596 based adjustable modules readily available on eBay (be sure to adjust the voltage properly ;) ) - but again, any part numbers that I use would probably not be suitable for you since they would be small surface mount ones.

I think I'll follow your advices and look into ESP8266 modules. NodeMCU, Weimos D1, any favorite? Anyway, thanks a lot for the answer!

If you replace the Arduino with an ESP32 don't use an ESP32 development board, use the module! All development boards still use a lot of power even in deep sleep. Check YouTube Andreas Spiess - https://www.youtube.com/watch?v=3O_vrKAmshA  (I deleted my previous comment with the wrong name)


text:
HC-12 modules stopped receiving, cannot understand why
I've created a simple transmitter with an HC-12 and an Arduino Nano (clone), where I send the values of DHT11 and LM35 sensors to a receiver unit made only of a Wemos D1 and another HC-12.
Setup is really simple and worked fine for a couple of days (transmitter in the cellar 2 floors down, receiver in my living room, it was POSTing data to my own server correctly), then I unplugged the receiver and modified the transmitter to add a JSON library; when I plugged them back again the receiver is not getting anything anymore.
Transmitter seems to be working fine, at least it prints the number of bytes written in the Serial Monitor.
I tried:

reverting back to the working version (no JSON), but still the same
tested each of the HC12 modules with a simple test code and AT commands, they all responds and are all set to factory configuration, like it was before actually (AT+DEFAULT)
made another receiver with an Arduino Uno and a lcd screen - a setup that I was successfully using before changing to the Wemos. Strangely, now this setup doesn't work too...
Switched the modules and what I got? The transmitter still transmits, the receiver doesn't receive, nothing changed.

Tried sending a simple string "Test", still no results.

Relevant code:
Transmitter:
#include <ArduinoJson.h>
#include <DHT_U.h>            // just Adafruit Library
#include <DHT.h>
#include <SoftwareSerial.h>
#define DHTTYPE DHT11   // DHT 11
SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin
int DHTPIN = 4;
int LMPIN = 5;
DHT dht(DHTPIN, DHTTYPE);
StaticJsonDocument<80> doc;

void setup() {
  analogReference(INTERNAL);
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  dht.begin();
}

void loop() {
  delay(5000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  int reading = analogRead(LMPIN);
  float lmt = reading/9.31;
  doc["dht_h"] = h;
  doc["dht_t"] = t;
  doc["ds_t"] = lmt;
  char result[50];
  serializeJson(doc, result);
  Serial.println(result);
  int written = HC12.print(result);
  Serial.println(written);    // it's 39 chars
}

Receiver (all wifi sections are removed):
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#define STASSID "....."
#define STAPSK  "....."
SoftwareSerial HC12(D13, D15); // HC-12 TX Pin, HC-12 RX Pin

const char* ssid     = STASSID;
const char* password = STAPSK;
const char* host = "...........";
const uint16_t port = 3000;

void setup() {
  Serial.begin(9600);
  HC12.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
}

void loop() {

  String content = HC12.readString();
  Serial.println(content);
  if(content.length()) {
    // This will send a string to the server
    Serial.println("sending data to server");
    if (client.connected()) {
      //....
    }
  }
  delay(1000);
}

I'm pretty stumped by the fact that it stopped working, and that both the HC-12 modules seem to be working fine (at least they respond to all the AT commands).
I even tried purging arduino from the system and reinstalling (I now have the very latest IDE release) but nothing....
Am I missing something obvious? (I've a weak electronic background, I'm a web developer by trade).
Is there a way to check if data is actually sent?
How can I debug these modules?

why not just run the DHT11 and LM35 from the ESP and save the debug effort? You should also use the server.on handlers instead of the painfully low-level client.connected stuff.

@dandavis Because there's no wifi connection where I put the sensors (it's floor -1th, I live at 2nd), and also I plan to add other devices to the receiver. But please don't focus on the ESP, the issue seems to be another

Did you check that your receiver connects to the WiFi?

@gbg Forget the WIFI (anyway, yes, it does), I cannot receive anymore with the HC-12 (it worked before)

For what it's worth, I manage to make them working again by playing a bit with the settings of both modules.
Using a simple test sketch I issued some AT commands to both modules; I had already tried setting them to the DEFAULT setup with AT+DEFAULT, but that was fruitless. I decided to left the mode as is (FU3), same for the serial rate (B9600), but I tried switching channel so I set both modules with AT+C002.
That did the trick, maybe was some sort of external interference, or a lack of precision in the channel settings - I just know that's a week now they've been communicating just fine and that's what matters.
So, if they fail to communicate, first try to adjust their settings, don't assume the DEFAULT ones are surely working.

For long range, better using FU4 , even if it's sloooooow.


text:
Can I force Arduino not to be powered by USB?
I'm building a 3D printer and I'm using an ATmega2560 + RAMPS board.
The whole thing is powered by an ATX PSU (12v for motors and stuff, 5v for the Arduino), but when I plug in my USB cable, I can't shut the printer down, as it switches over to USB power.
Is there a way to make the Arduino never use the USB power, only the external power source?
Thanks!

Or create a USB adapter that does not connect the power line.

The best way of doing this, if you want your USB connection to still work, is to remove the P-channel MOSFET T1 from the board.

You can't just disconnect the power from the USB port since that power connection goes directly to UVCC on the ATMega16U2 chip. That is used to power the internal USB peripheral (it goes to a 3.3V regulator inside the chip) and without it the USB interface won't have power.
The USB power is connected to the main 5V rail through that transistor, so if you remove that transistor the 5V from the USB remains connected to the ATMega16U2, but is no longer connected to the rest of the circuit.

Or the big fuse next to it :)

No. That would be the same as cutting the power from the USB.  The USB socket goes first to the fuse, then to both the transistor and the ATMega16U2.

you could do this if you cut the trace for the 5V line from the USB connector to the rest of the board. if you place the mega underside up on a bench in front of you, with the USB facing towards you, i believe it should be the top left pin of the 4 USB pins, but you should double check that first.

you probably can't see it but your answer has 1 down and 1 up vote.  I didn't down vote you - but suspect the person who did may not have liked that your answer requires "double checking".  Perhaps if you verify your answer is correct and re-word it, the person who down voted it may remove the down vote.

Personally I don't like the idea of a permanent modification such as cutting a trace. Once it's done you are pretty much out of options and alternatives. I'm not the down voter either, just throwing my two cents into this post.

Well, it's what I looked for, if I want a non permanent thing I'd put in a switch but this is what I want. Thanks!

This method may be counter-productive. You need the power from the USB port to run the ATMega16U2's USB hardware. Without that you won't get a USB connection...

@Valmond the answer posted by Majenko is what you want, mine is incorrect.

Just modify your UBS cable to not provide power.

read the accepted answer. the USB chip would not be powered