text:
Cisco Switch not receiving serial communication from Arduino
So I have an issue that I can't really think of a reason why it would be happening. I have an Arduino Mega connected on Serial3 to a RS232 breakout board with a male DB9 connector on it. I then have two female breakout boards connected. One is connected to the RS232 breakout board and the other to a Cisco DB9 to roll over cable, which is connected to my Cisco Switch, or if it is, it is being ignored.
For some reason no data sent from the Arduino is making it to the Cisco switch that I can tell. I did confirm that it is sending data using a USB to DB9 adapter and PUTTY. I can send and receive data from both the Arduino and PUTTY correctly to the other.
I can receive data from the switch perfectly. Cisco's default settings are the same as the Arduino's, 9600, 8bits, no parity, 1 stop bit etc...
I can also connect the switch to the USB to DB9 adapter directly and send and receive fine through it / PUTTY as well.
Does anyone have any suggestions why I'd be able to send data to and from Putty, but only receive data from the switch, or why the data going to the switch is failing?

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  Serial3.begin(9600, SERIAL_8N1);
  Serial.println("Ready....");
  Serial.println();
}

void loop() {
  // read from Serial3, write to Serial
  if (Serial3.available()) {
    int inByte = Serial3.read();
    Serial.write(inByte);
  }
  // read from Serial, write to Serial3
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial3.write(inByte);
  }
  Serial3.println(); // Added just to test if a cr could be passed
  Serial3.write(98); // Added just to test if a character could be directory passed
  Serial3.write(10); // Added just to test if a cr could be passed
}

Consider in band verses out of band flow control.

Is there such a thing as inb vs oob for a serial console connection? This isn't on the internal network of the switch in any way but the console port.

Ug, I can't answer in the comments as I'm running out of characters...  See my Answer.  We'll just have to change the Answer to match the actual problem once you solve it later...

It seems you have demonstrated that the Arduino is transmitting, so this is more likely a fit for a networking equipment site than the Arduino one.  Looking at line ending cases was a good idea, you might look there a little more, or make sure you are using the same putty or Arduino serial monitor settings in both the PC-switch test and the PC-Arduino-switch experiment, ie, don't use putty for one and the serial monitor for the other.

Of course your "Added just to test" would break any meaningful traffic by inserting these extra characters between those of the intended message, and if the source data is keeping the PC-Arduino link full potentially make the Arduino-switch one fall behind.  Presumably you also tried without those llines.

Hey thanks for the replies. Yes I tried without, and the only thing that I have noticed is that adding those lines does not seem to make any different to the switch, HOWEVER they do seem to cause some sort of interference with the received traffic from the switch causing text artifacts.
The reason I put them there was to see if any characters valid or not made it to the switch. I would transmit with the arduino, and then change the serial connection back to the PC and press the enter key to see if any characters were received. If there was, I'd get an error since they'd be a bad command.

I'm not sure how to use the Arduino Serial mon to monitor my USB to DB9 adapter, or are you saying there is a way to use Putty as my Arduino Serial monitor instead of the IDE, or either / both?. Here is the setups that I have tested.
Switch TO DB9 Adapter (Putty) - Works
Switch TO Arduino (Arduino IDE Serial Monitor) - Receives only.
DB9 adapter (Putty) TO Arduino (Arduino IDE Serial Monitor) - Works

I have not used stack all that much, is there an easy way to copy a question to the network group, or link back to this one? Seems like the comments here would be relevant to them too.

Networking Comm considers this off topic for their community.

They are probably wrong - this is far more a Cisco question than it is an Arduino one.  But questions that lack information to make them answerable tend to be unpopular everywhere.

You can use putty with an Arduino just by choosing the appropriate serial device and line settings, in your case you want the line settings to be the same as those you were able to talk to the switch with, unless you have misreported what they are.

So I used putty to connect to the arduino but I couldn't enter commands via putty at all. I was able to power cycle the switch though and it did correctly read from Serial3 and Write it back out to Serial which putty was connected to. Fairly similar to the arduino IDE. I should point out though, that this should not really matter since I have matched the settings putty uses on the arduino to talk to the switch, and I couldn't even manually send a character to it. If anything I think I'm probably dealing with some missing element the cisco switch requires. Any more Ideas I will gladly try.

So you get valid behaviour with Putty but not the Arduino serial monitor?

Assuming this is a flow control problem:

Is there such a thing as inb vs oob for a serial console connection?
  This isn't on the internal network of the switch in any way but the
  console port

It assumed this is a managed switch and the traffic on the console port has nothing to do with the traffic going through the switch. Rather this is likely a port to the computer inside the switch.  Such a port might be able to use RTS/CTS/DSR or X-on / and X-off.
If this is a flow control problem, consider first looking for thumb switches on the back of the switch to see if the method used for flow control over the console port can be selected. If that is not possible, consider simply hardwiring the out of band flow control pins to always allow for data to flow.  At 9600 baud, a dedicated Aruidno should be able to keep up.
Refer to the 9 pin connector in this chart to find the out of band flow control pins.

This is unlikely to be the answer.  Flow control usually means the receiver allowing, or impeding the transmitter.  An Arduino ignorant of it would transmit blindly, and there's little reason why a switch not heavily burdened by previous traffic from the Arduino would be trying to suspend incoming data.  In the other direction, if the switch where looking for flow control inputs it wouldn't send, but it apparently is is sending.

Good point.  So what do you think?  Cross over cable confusion?  Like switching Rx & Tx or DTE & DTC?  Maybe a difference in the EOL (End Of Line) character?  Could be that Putty is tolerant of different EOL characters and works with both while they don't work with each other?

Swapped wiring seems unlikely given that something is allegedly received from the switch.  In terms of line endings, it would not be the terminal program's "tolerance" but rather what it transmits.  If the same terminal program is used for both tests that should not be the issue either, but we don't know that the same program was used for both the direct and arduino-in-the-middle tests.

Yeah I don't think this is what I need but thank you for the reply. Also these switches don't have anything like that on the back, you change all the serial connection settings on the switch itself when you are connected to it, but this needs to work with stock switch settings to be useful for what I need. Very few people every change these settings on Cisco routers and switches since they usually just use console to configure network settings, and then all times after that connect with telnet or ssh.

Could be a voltage problem. You're using an TTL->RS232 Adapter as far as I can tell from the picture, which is absolutely necessary. Arduino only gives out TTL Signal Level, which would not be "understood" by the Cisco Switch, which works on RS232 / Serial Voltage Level (which is a lot higher). However, maybe the RS232 Converter Module is faulty. You could check the output voltage level with a Multimeter and see if it actually is in the required range (http://www.radio-electronics.com/info/telecommunications_networks/rs232/signals-voltages-levels.php).
Also connecting ground correctly is important, but that should be ok on your setup :).


text:
Problem with modbus communication between two arduinos when writing more than 27 registers
I have the following problem:
I want send 200 registers from a modbus master to a slave. Both are arduinos.
I can't send more than 27 registers. When I send more i get the Errorcode 255 which means timeout. I know that the modbus message is limited to 253 bytes (256 bytes - server address (1 byte) - CRC  (2 bytes)). Listed here: MODBUS APPLICATION PROTOCOL SPECIFICATION page.5
My setup:

I use two Arduino Mega 2560. One as a master and the other as the slave. If that works I want to use more than one slave. They are connected via Serial1 master TX1 (pin18) to slave RX1 (pin19) and master RX1 (pin19) to slave TX1 (pin18).
The modbus library I'm using is ModbusRtu.h from smarmengol.
Because i want to ultimately communicate with more than one slave device I use RS-485. To send the message as a broadcasat but thats not relevant now because first I want to send to one slave to test it out.

I know that the array is much bigger as the registers I want to send. Thats because I wanted to know when the the timeout happens. Sending 27 registers works fine and the slave recieves all of the 27. But when sending more than 27 registers I get the timeout and nothing will be send.
Master code
#define SERIAL_BUFFER_SIZE 256
#include "ModbusRtu.h"

#define Timeout 150
#define QUERYINTERVALL 50

/* Defined the buffersize as stated in
 * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
*/

modbus_t telegram;

// Test sending large array
uint16_t sendLargeArray[200] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                                18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
                                33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
                                48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
                                63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
                                78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
                                93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
                                106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
                                118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
                                130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
                                142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
                                154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
                                166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
                                178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
                                190, 191, 192, 193, 194, 195, 196, 197, 198, 199};

Modbus master;

void dataSend();

void setup()
{

 /**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
    master = Modbus(0, 1, 8); // this is master with RS-485 config
    master.begin(9600, SERIAL_8N2);
    master.setTimeOut(Timeout);
    Serial.begin(9600); // setup Serial for USB debugging
}

void loop()
{
    uint8_t error = master.getLastError(); //get errorcode
    uint8_t state = master.getState();     // get state from master 0 = idle 1 = waiting

    dataSend(); // function for sending array

    // Error Code
    Serial.print("Error code: ");
    Serial.print(error);
    Serial.println();

    // Print master state
    Serial.print("Master State: ");
    Serial.print(state);
    Serial.println();
}

void dataSend()
{
    uint8_t slaveId;
    uint8_t u8state;
    unsigned long u32wait;
    slaveId = 1;
    u32wait = millis() + QUERYINTERVALL;
    bool staywhile = true;

    // telegram for sending sendLargeArray
    telegram.u8id = 1;
    telegram.u8fct = 16;
    telegram.u16RegAdd = 0;
    telegram.u16CoilsNo = 28; // 27 or less works fine
    telegram.au16reg = sendLargeArray;
    u8state = 0;

    // Master broadcasts data
    while (staywhile)
    {
        switch (u8state)
        {
        case 0:
            if (millis() > u32wait)
                u8state++; // wait state
            break;
        case 1:
            master.query(telegram); // send query (only once)
            u8state++;
        case 2:
            master.poll(); // check incoming messages
            if (master.getState() == COM_IDLE)
            {
                u8state = 0;
                u32wait = millis() + QUERYINTERVALL;
                staywhile = false;
            }
            break;
        }
    }
}

Slave code
#define SERIAL_BUFFER_SIZE 256
#include "ModbusRtu.h"

/* Defined the buffersize as stated in
     * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
    */

// data array for modbus network sharing

uint16_t recieveLargeArray[200] = {};

 /**
  *  Modbus object declaration
  *  u8id : node id = 0 for master, = 1..247 for slave
  *  u8serno : serial port (use 0 for Serial)
  *  u8txenpin : 0 for RS-232 and USB-FTDI
  *               or any pin number > 1 for RS-485
 */
Modbus slave(1, 1, 8); // this is slave @1 and RS-485

void setup()
{
  Serial.begin(9600);
  slave.begin(9600, SERIAL_8N2); // baud-rate at 9600
}

void loop()
{
  uint8_t error = slave.getLastError();
  slave.poll(recieveLargeArray, 28); // receiving 27 or less registers works fine

  // print every 5th element of the recieved array
  // no spamming console that way
  Serial.print("Recieve: ");
  for (int i = 0; i < 200; i += 5)
  {
    Serial.print(recieveLargeArray[i]);
    Serial.print(",");
  }
  // Error Code
  Serial.println();
  Serial.print("Error code: ");
  Serial.print(error);
  Serial.println();

  memset(recieveLargeArray, 0, 200 * sizeof(uint16_t)); // recieveLargeArray = {}

}

Questions

Does anyone know why I cant send more than 27 registers?
Did anyone made a simillar project and can share the code?
Has anyone a fix for that?

Help is very appreciated.
Cheers ueberBrot
Link issuepage on ModbusRTU.h GitHub
Edit

Forgot to mention that I increased the buffer size inside the ModbusRTU.h library aswell. I did it like that #define MAX_BUFFER 256 as mentioned in this comment from Juraj
Changed the define location of #define SERIAL_BUFFER_SIZE 256 in both sketches to the top.

I did change the MAX_BUFFER inside ModbusRTU.h from 64 to 256. As you stated before in there its only the size for the used array. What I also did was move the #define SERIAL_BUFFER_SIZE 256 inside both my sketches to the top. That did nothing, After that I found a way to increase the RX and TX buffer size with the help of this post. I changed it from 64 to 256. maybe I could have changed those with a #define in my sketches aswell?.
Now I can send a max of 59 registers at once. Im not sure why I cant send more because the max should be 123 registers at once and the buffer is 256 bytes so  123 registers x 2 bytes = 246 is enough space in the buffer.

In ModbusRtu.h:
#define MAX_BUFFER 64 //!< maximum size for the communication buffer in bytes
27*2=54 bytes for registers and 10 for header and crc.
Change the MAX_BUFFER define. On Mega you have enough RAM.
btw: RS485 doesn't imply mandatory use of Modbus. You could use your own protocol.

Thank you for the answer @Juraj.
Oh sorry forget to mention that in the original post. After I increased the Arduino buffer size to 256 byte I did the same inside the ModbusRTU.h library #define MAX_BUFFER 256  . So thats not the problem.
Using my own protocol what do you mean by that? I dont have a clue how to do that so Im guessing its either not in my skillrange or I simply dont know where to begin. Can you explain or point me to an example? That I could use for my ultimate goal a master with many slaves?
Cheers ueberBrot

if it allows only 27 registers, then it didn't apply. what "Arduino buffer"?

In the file ***\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h the SERIAL BUFFER SIZE (Arduino buffer) is defined from line 77 to 86. If the buffer is not defined like I did in my sketches #define SERIAL_BUFFER_SIZE 256 it has two default values 16 or 64 byte dependening of the Arduino RAM. Or is this wrong?

not wrong, but not needed. The Serial buffer is really a 'buffer'. If full, write() waits a little until there is space (bytes are send out continuously). The buffer in ModbusRtu.h is not a real buffer, it is an array to build the complete message.

Ah ok thought it may be connected to my problem thats why I increased it. If the change I did inside the library did not apply how is that? Do you have a clue?

did you change the define inside ModbusRtu.h? in your sketch it is too late.

source: Stack Exchange

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

sort: votes


text:
STM32 and NRF send & receive
This is my send and receive code in STM32 (blue board).
But i can't send and receive data . why?
I did use Enrf24.h .
Enrf24 link: https://github.com/spirilis/Enrf24
send code is:
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}

void loop() {
  Serial.print("Sending packet: ");
  radio.print("OONN");
  radio.flush();  // Force transmit (don't wait for any more data)
  delay(1000);
  Serial.print("Sending packet: ");
  radio.print("OOFF");
  radio.flush();
  delay(1000);
}

receive code is:
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
}

void loop() {
  char inbuf[33];
  while (!radio.available(true));
  if (radio.read(inbuf)) {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

this image can help :

And the question is?

Thanks, i can't send and receive data . why? please see my image

You did not say which library you are using, but based on the #includes, I am assuming http://maniacbug.github.io/RF24
This line in your receiver code:
  while (!radio.available(true));

does not make sense. You are passing true to the radio.available() function, but the function does not care about a parameter.
You probably mean something like:
while (!radio.available());

When you pass in a variable, you are calling a variant of the function that expects a pipe number to be given, and true is defined as 1. Your transmitter, however, is not sending on pipe number 1.

I use this library   link  . in exmaple folder you can see some example  i did use Enrf24

First of all, remove
while (!radio.available(true));

after that use
PA_5 ----> SCK
PA_6 ----> MISO
PA_7 ----> MOSI

it will work correctly.

It is better answer for some reseans
in Enrf library you can not send data with write untill txbuf_len==0

size_t Enrf24::write(uint8_t c) {
  if (txbuf_len == 32) {
  flush();  // Blocking OTA TX   }
  txbuf[txbuf_len] = c;   txbuf_len++;
  return 1; }

dont use purge then

txbuf_len = 0

this is for read dat
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
 // radio.autoAck(false);
}

void loop() {
  char inbuf[35];
  if (radio.read(inbuf))
  {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

this is write for write data:
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}
int i=0;
void loop() {
  i++;
  Serial.print("Sending packet: ");
  Serial.println(i);
  radio.print("1234567890123456789012--------->");
  //radio.purge();
  delay(100);
}

what is in principle the difference between the code in question an code in answer? only the removed while (available)?

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


text:
Program hangs at am2315.begin() - ideas?
In working with the AM2315 temperature/humidity sensor, my program hangs at the am2315.begin(); line.
The only output I get is "Serial on"
Here is the code:
#include "cactus_io_AM2315.h"
AM2315 am2315;

void setup() {
     Wire.begin(0X20);
     Serial.begin(9600);
     Serial.println("Serial on");
     Serial.println(am2315.begin());
     Serial.println("- - - - Weather station - - - - - - - -");
     Serial.println(" ");
     Serial.print("RH\t\tTemp (C)\tTemp(F)");
     Serial.println(" ");
}  // end setup

I have tried it both with and without the 10K pull-up resisters and get the same result.  I'm not comfortable including them in any case because I will eventually use I2C&Power to link the I2C bus to many other devices and am not sure what that might do..
Right now none of that is hooked up.  It is just the sensor and the Arduino and the laptop.
Voltages have been measured so I know the device is getting 5V power.
My connections and software are based on this article:  http://cactus.io/hookups/sensors/temperature-humidity/am2315/hookup-arduino-to-am2315-temp-humidity-sensor

UPDATE:  New information:  When I am using I2C&Power, I provide power from only one of the dual-port units.  But I discovered that leaving the SDA and SCL unterminated there it breaks the I2C that is trying to pass through it.  By putting in 4.7K pull-up resistors there it restored the connection.

I added a DS3231 RTC module to the breadboard I2C bus and removed the 10K resisters, and now they both work.
Apparently this sensor does not play well alone.  But with the both of them it is fine.
No need at all for the 10K resisters.  (I am using a Nano)
If I disconnect the RTC and reset, it again hangs at the am2315.begin statement, resistors or not.
So this problem is solved now.

10K might have been to high a value. Test it with a lower value resistor (e.g. 1K).

The Adafruit page mentions ~10k, but 4.7k is more typical for I2C pull-up resistors. Your RTC looks like it has 10k resistors built in, so that would have helped. Are you sure your resistors are 10k? Perhaps check with a multimeter.

All good ideas.  I will try them out.  Thank you.

New information:  When I am using I2C&Power, I provide power from only one of the dual-port units.  But I discovered that leaving the SDA and SCL unterminated there it breaks the I2C that is trying to pass through it.  By putting in 4.7K pull-up resistors there it restored the connection.

I've seen some devices saying that they need just a 1.5K resistor, but like you the best solution I have found is to always have a DS3231 on the I2C bus, seems to make everything work.

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


text:
How can I use my Arduino sketches on my Raspberry Pi IDE?
I have installed the Arduino IDE 2:1.0.5 on my Raspberry Pi3 under Raspbian and am using a cobbler breakout which provides a nice breadboard.  On that breadboard I have installed an Arduino Nano to do analog voltage readings, which it then communicates back to the Rpi3 via the USB serial port which shows up as /dev/ttyUSB0 on the Rpi3.
This port opens as a regular file in Python for further processing such as adding a date & time stamp (obtained by an NTP server) and saving the results to a data file that is displayed in gnuplot 4.6.

You'll notice I am using 3.3 Volts for the fan to keep it quiet, and the two wires heading up to the top go to the voltage source I am monitoring.  If you look closely you can see the voltage divider circuit.
Here is today's solar plant voltages which this thing tracks.  The block at the bottom means the inverter was on.  Green means the battery bank is full.

Anyway, it turns out that the same serial connection is supported by the Rpi Arduino IDE for programming.
Rather than programming the Nano on a laptop and constantly having to unplug/replug it on the breadboard my goal is to use Rpi Arduino IDE for programming.
So I moved all my sketches over from the Arduino IDE on the laptop to the Rpi.
But
.... then every time I start the Rpi IDE it throws error messages for all the sketches that have underscores in their names.  Turns out the Rpi version will only allow alphanumeric directory names.  I have a couple dozen sketches and this is not productive.  It requires clicking OK for every directory it skips - which turns out to be all of them.
So my question is:  What can I do about this?

Perhaps you could spell out which op sys you installed on your Raspberry Pi, and which IDE version is installed.

Just a little comment: arduino IDE version 1.0.5 is quite old.. Maybe it's worth updating to 1.8.1 (you can't use apt, though; just go on the Arduino download page and download the ARM version (I think)

Ah, I see 1.8.1 there. And yes, I had used apt-get install to do this in the first place.  Not sure I have the know-it-all to do it another way.  Meanwhile, it is working great. I love being able to reprogram my units that are outside and far away without having to bring them back in to the laptop and risk bending pins, etc. I can do updates with almost no downtime.

Obligatory XKCD: https://xkcd.com/1205/

To fix this problem I came up with the following procedure which takes out all the underscores from the directories & filenames and capitalizes each word instead.
First, I copied all my sketches and libraries (from my documents/arduino directory) to a USB flash drive.
The Rpi Arduino IDE creates a sketchbook directory upon install, so I
Copied the libraries folder to ~/sketchbook/libraries
Copied the sketches folder to ~/sketchbook/AMSsketches
Then I wrote a custom script that is copied to my home directory on the Rpi, which can be obtained here as a text file (use Chromium or wget to copy it to the file ~/AMS2Rpi)  - Here is the link:  http://calttc.net/AMS2Rpi
which contains this code:
#! /bin/bash
#
#  AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
#
#                  SDsolar      2017-01-29
#
#  Reason:    Arduino IDE on MS inserts underscore characters in file & directory names
#             Arduino IDE on Rpi rejects all but alphanumeric characters
#
#  Solution:  Remove all but alphanumeric characters
#             and capitalize each word in the names
#
#  Usage:
#    Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
#    Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
#      On the Rpi, copy the libraries directory to ~/sketchbook/libraries
#      On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
#    Copy this script to your home directory as AMS2Rpi using Chromium
#    cd
#    chmod +x AMS2Rpi
#    ./AMS2Rpi    (This will take some time)
#    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
#    chmod +x ~/AMS2RpiQ
#    ~/AMS2RpiQ
#    Open the Rpi Arduino IDE
#
#  Alternatively, if you have a lot of sketches you might want to
#    change the "mv -i" below to "mv"
#    and cat it into AM2SRpiX above
#    so you don't need to answer "y" for every rename.
#
#  Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
# ---------------------------------------------------------------------
rm -f /tmp/AMS2R*
cd $1
find .  | awk '{ print length(), $0 | "sort -n -r" }' | \
        grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
touch /tmp/AMS2Rpi_2
while read line
  do
  BASE=`basename "$line"`
  NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
  if [ "$BASE" != "$NEWBASE" ]
  then
  OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
  fi
done </tmp/AMS2Rpi_1
rm -f /tmp/AMS2Rpi_1
mv /tmp/AMS2Rpi_2 /tmp/AMS2Rpi
exit

Then set it to executable and run it:
cd
chmod +x AMS2Rpi
./AMS2Rpi

When it is finished, I filter out just the directory I want (VERY IMPORTANT):
cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMS2RpiQ

(You can look at that file to verify it before running it)
chmod +x ~/AMS2RpiQ
~/AMS2RpiQ

Cleanup if you wish:
rm /tmp/AMS2R*
rm ~/AMS2RpiQ

Now the Arduino IDE on the Rpi opens cleanly and all my sketches are there.
Problem solved.   It works great.

This reminds me of a programmers' joke I read some time ago, which said "a programmer is someone who takes one month to develop a program which automates a one hour task" ;)

That's pretty good.  I would only add that the retired ones are the worst.  ;-)

Turns out there are two easier answers if you are willing to do it manually.
You can use the Windows-based IDE to load each sketch then save them with an allowable name, before transferring them.
So, instead of going through the program, just do it by hand - this is best if you don't have too many, or if you are very patient.
Or jump in with both feet:  use your USB flash drive to just move your libraries and sketches to the appropriate directories under sketchbook.
libraries go to ~/sketchbook/libraries
sketches go to ~/sketchbook/sketches
Go into the IDE preferences and tell it to look into ~/sketchbook/sketches

Manually rename any directories in both directories so they only have alphanumeric characters in the subdirectory names
The Rpi version of the Arduino IDE has no problem with filenames with underscores.  It is just the directories it rejects if they are not strictly alphanumeric.  But it really prefers that the files have the same names as the directories.
Each library must be added to the IDE using the
IDE menu Sketch..Import Library..Add Library

It stores them somewhere else in the IDE's guts.

I might add that this works fine unless you have 40 sketches and libraries that are being ignored due to this error.

here's an expression that strips every character that is not ( alpha numeric or space character, or period character) that is also Followed by an alpha numeric or space or period and replaces it by capitalising the following character.

find  ./ -depth | perl -wan -F'/' -e ' chomp; chomp($F[-1]);$x=$_; if ($F[-1]=~m/[^\p{Alnum}\d \.]/ and substr($F[-1],0,1) ne ".") {  $F[-1]=~s/[^\p{Alnum}\d \.]+([\p{Alnum}\d \.]{1})/uc($1)/eg; $y = join "\\",@F; system("mv",$x,$y);print "mv \"$x\" \"$y\"\n";}'

it ignores unix hidden file starting with "." And it also renames directories.
This will fail on edge cases where the last character in the name is a non alpha character.

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


text:
SerialUSB on Arduino Due
I'm starting fiddling with a Due but I can't seem to be able to communicate over USB with it. Here is my code:
int bauds = 9600;

void setup() {
    SerialUSB.begin(bauds);
}

void loop() {
    if (SerialUSB.available())
        serialUSBEvent();
}

void serialUSBEvent() {
    String str = SerialUSB.readString();
    SerialUSB.write(str.c_str());
}

As you can see, I try with the bare minimum but my output consoles (2 COM port for the 2 usb connections, just in case I messed up which is which) stay blanks, whatever I send them...

Have you tried resetting the board after sending the program? Or after having opened the terminal?
A few days ago I didn't have any results using SerialUSB, and today I have. The program has been sent trough the programming port, and SerialUSB is with native port. Uploading my program trough native port, it didn't worked until I reset!

authors: Сергей Аликин


text:
Arduino Uno + 12 relays
I'm using a basic relay and I want to use 12 like this. Each one needs 50 milliamps, but the Arduino can supply only 300 milliamps. What can I do?

Use transistors.

You should never drive relays direct from an Arduino.  You always need a driver circuit since each OP pin can only reliably provide up to 25mA.
Every relay needs (at least) an NPN transistor and a flyback diode.  Follow the myriad of examples for controlling one relay on an Arduino and multiply it by 12.
You might like to make things smaller and more manageable by using a paur of ULN2303 chips with 6 darlington drivers in each instead of using 12 discrete transistors.

Im using a transistor for each one. But it still take 50 milli amper. Can you show me a circuit?

@MyNick If you are managing to draw 50mA into the base of a transistor then they must be massive transistors driving house sized relays.   If you are talking about the power supply current draw not the IO pin current draw, then just get a bigger power supply.

Regular transistors that comes from the kit.

@MyNick Then I have to assume (rightly or wrongly, I can't tell since you won't tell me) that you're referring to the power supply current not the IO pin current, in which case - what is your problem? Just use a more powerful power supply for the relays. If you are actually referring to the IO current then god help your Arduino.

This is the circuit for each relay, it takes 50 milli amper from the io pin: https://mail.google.com/mail/u/0/?ui=2&ik=7c60d62fee&view=fimg&th=150943794c75955d&attid=0.1&disp=inline&realattid=1515816904198979584-local0&safe=1&attbid=ANGjdJ9eRNUCnxNPSMue9eI_2SEzxRP7jg00s0ty_jgJJyrD0-eI94xWwlpXSn3q5KYgrIP9QpdxBgSG9mscZxEcG1LzmsNXXF_pkVixDsEDKtTO0iYZkN9fHF6MzoE&ats=1445596069379&rm=150943794c75955d&zw&sz=w1256-h819

@MyNick You know, much as I would love to be able to read your email, I just can't afford the time trying to hack it.

tried to give the link to the image. nvm here you go: http://puu.sh/kUxyk/4a53ce59e5.jpg

I see only 4.3mA, not 50mA.

I just a circuit that a friend drew for me. He told me that the current is not real and i should try to build it and check it. (he just put random values or something). I built it and it took 50 ma (i checked it using multi meter)

WHERE did it take 50mA? At what point in the circuit?

between the io and the resistor into the base of the transistor.

In that case there is something very wrong with your circuit. Given a typical Hfe of 100 you would then expect the transistor to be passing around 5A.  It would literally be on fire.

i found that circuit example : https://www.flickr.com/photos/anachrocomputer/3242387876/in/pool-make
how does the resistor makes a different? if i use 300 ohm what will happen?

@MyNick Yes, that is the normal basic relay driving circuit.

and if i use 300ohm resistor and not 1k?

Then you raise the current allowed through the base, and thus the maximum through the colletcor.  300Ω should be fine, but 1K is better since it limits the maximum that can be drawn from the IO pin.

Ok now i get it, Thank you so much for all of your time


text:
Arduino graphic interface
I succeeded in programming a system of thermoregulation using Arduino.  This system holds the temperature of a plate at 37°C. I used a PID corrector to realize this.
What I want to do now is make a graphic interface that can communicate with the Arduino, allowing me to see a graph of the temperature.
I would like an explanation of how to send temperature data to a graphic interface using Arduino Uno.

There are two main possibilities.
The first one is to make a GUI on the Arduino itself. Add a TFT screen, touchscreen if you want the user to interact, or a non-touchscreen (cheaper) if you just want to display. Then, within your Arduino code, you can display the temperature data, and if you go the touchscreen route, interact with the user.
I own a couple of Arduino Esplora devices, and they would be near perfect for this, as they have a non-touch TFT screen, a joystick, buttons and a pot. All the equipment you need to display the temperature. Oh, and it has temperature and light sensors onboard.

The second way would be to make a GUI on your desktop/laptop machine. In your Arduino code, you could send your temperature data through USB (Serial), Bluetooth (SoftwareSerial), WiFi, Ethernet, nRF, etc etc etc. If you don't mind having the Arduino tethered to your computer by a cable, USB<-->Serial is the easiest solution. The software on the computer listens on a serial socket and when it receives temperature data, it displays it within its GUI.
HTH

It all depends on what graphical interface.  There's many ways of doing it.  You have TFT screens that the Arduino controls directly (take a look at UTFT for example), or serially connected displays (such as the ones offered by 4D Systems).
First you need to decide what kind of display device you want to use - and that is deciding:

What your budget is
How many Arduino resources you can dedicate to the interface
What IO you have available on your Arduino

And more.

@zakaria That's even more vague than before. Is this a program you already have (if so WHAT program?!), or do you want to write your own PC program? (We don't know how, ask on a PC programming website).

no I don't have the program before and i want to write my own PC program. but anyway I want to understand how can arduino send the data to another program, by using sockets?

@zakaria Now you throw sockets into the mix as well...!  What you ask is not trivial. I think you need to go back to basics and work out exactly what you want and how to articulate that into words and then google the different aspects of it.

Does your Arduino mount an Ethernet shield? If not, the only chance is to send data to your PC via the "serial" interface trough the USB port. Hence, the PC need to be kept close/connected to Arduino, and turned on. Then, on the PC, there are plenty of option to fetch such data and do whatever you want with them (graphing including).


text:
Making AC current with pin 11
I'm trying to make AC current (50Hz) with an Arduino Uno. It seems to be not working (or wrong code).
int up;
int down;
int out = 11;
void setup() {
  pinMode(out, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (up = 0; up <= 255; up++) {
    analogWrite(out, up);
    delay(1);
  }
  for (down = 255; down >= 0; down--) {
    analogWrite(out, down);
    delay(1);
  }
}

Update:

Now the code above is giving output voltage of 0-5V (getting increased from 0 to 5 and then decreased) not giving a negative cycle (-5V).
After setting the minimum delay of 1, the output wave is still half wave rectifier with frequency 2Hz.
Without delay LED is blinking so fast I don't know what's its frequency.

How do I make make 50Hz AC current a with negative cycle?

The UNO doesn't have a DAC. So you need to filter the PWM output to get an analog AC voltage.

What you have there (apart from your lack of brackets on the for which breaks it all) is code for a saw-tooth wave (if you filter it) at 1.95Hz.

Your code shows a real lack of understanding of the basics of C programming.

ohhh, i thought arudino analogWrite output is sin wave. After watching this https://www.arduino.cc/en/Tutorial/PWM it's seems like arduino gives output only in digital wave.

It's digital (as in Pulse Width Modulation) but when filtered (low pass filter) it forms an analog voltage. By setting the duty cycle (analogWrite) in the right way you can form one discrete part of an AC waveform. If you want a sine wave then you have to form a sine wave out of discrete values.

Normally that is done using a look-up table (LUT) since calculating values of sin is far too slow on a little 8-bit MCU.

@Majenko updated the for loop and also code. Checked with multimeter on AC it's showing around 5V and on DC it's showing around 2.5V. seems like half AC current at 50Hz is created. now working on low pass filter.

Your code is still far from correct. There's bits there that aren't wanted, and the bits that are wanted are in the wrong place (and the wrong value, and just plain wrong).

If you are not critical on the waveform you can use a transformer where the secondary has a center tap. The primary should have one as well. Tie the input center tap to +12 or whatever is available but DO NOT use the arduino 5 volt pin. Then using two avalanche protected N channel MOSFETs you them to drive the remaining two input leads.  The output will be a pseudo sine wave, far from perfect but it will have the negative excursion you want.This type of circuirity can be found in Switch Mode Power Supplies (SMPS). Note the transformer winding ratio will determine your output voltage. You will need a little dead time between turning one MOSFET off and the Other on.  A single mosfet would work but there would only be two connections to the transformer primary not 3 and the wave form will be a lousy.

You do realize you're answering a more than 4 year old question, I hope. Your answer would benefit greatly from a schematic.


text:
What is the proper way to implement PID?
I'm having some trouble conceptualizing how to go about implementing PID into my drone. There are a few ways I'm thinking about implementing the pipeline:

Having one PID Object for each of the six motors.
Having one PID Object for each axis.

How I would implement PIDs on a per-motor basis?

How I would implement PIDs on a per-axis basis?

I'm guessing that the second one will be the best course of action, as it can all be put into its own loop, where the PID data will be available on-demand, as opposed to calculating it on the spot. It is object-oriented, and runs in the background.
The first one has its appeals, too. It eliminates some of the calculations needed in order to find the actual value. It is procedural, and very straightforward and performs on the spot.
What do you guys think?

Each unique variable you want control over should have a single pid loop, and each loop should only ever stretch across one "order" of time.
For example, to control the craft's roll rate, you should have one PID loop that takes the target roll rate and outputs the controlled roll torque value, which gets transformed somehow into motor accelerations. The trig weights for that part can be precalculated so it doesn't have to happen at runtime.
To control the craft's roll rotational position, you would need one PID loop that takes the target roll position and outputs the target roll velocity, that target roll velocity then becomes the setpoint for the roll-velocity pid loop.
I don't see why each motor would need its own PID loop unless you are measuring the actual thrust each motor produces. If you did measure each motor's thrust their pid loops would still come after the target torque value were calculated. The target torque PID calculations don't need to know about what motors exist or where they are located.
I may not be understanding the intention of your diagrams or what "order" the PID loops are in, so feel free to comment with clarifications. This is complicated stuff.
Its also worth noting that the actual implementation pid often has some features that don't appear in theoretical pid loops like integral windup prevention. You also need a way to either call them at exactly the same interval each time, or accurately keep track of the time delta since the last update. You may want to take the derivative of the process variable only, not the error, so you don't observe setpoint changes in the D term; you could also "outsource" the derivative term if you IMU has a better calculation of it (like the raw gyroscope values).

I will give a generic C-answer to it:
1) figure out what parameters / variables involved in a PID control loop;
2) structure those parameters / variables into a struct;
3) pass that struct to a common set of PID algorithm.
4) done.
with this approach, the algorithm is only implemented once and the can be used / reused as many times as you want.


text:
Time signal. Determine the presence of pulses and their duration
I want to detect the exact time signal from an FM radio station. The signal is transmitted in the form of 5 short pulses and one long one. My task is to determine the presence of a pulse in the audio data stream and its duration.
It is understood that the signal is received by the radio receiver and then the audio signal is fed to the atmega microcontroller.
The pulse duration varies in the range of 100 ... 560 ms
How can you control the appearance of these pulses using a microcontroller, and also determine their duration? Below is an example of computer processing. The same is required to be implemented on a microcontroller.

I have a reference recorded signal in WAV format.
This recorded signal from the output of the radio receiver contains both the speaker's speech, music, and the exact time signal:

I know the time signal is centered at 1 kHz, so
apply filtering to this signal. The filter has the following frequency response:

The signal after the filter looks like:

It remains to apply the threshold device and duration selection.
However, I do all this in an audio editor to understand the ongoing processes. In fact, I need to implement this on an arduino, so I really hope for your tips, because I don't know how to implement a filter on an arduino for one frequency, and I also don't know how to make a pulse detector and a meter for its parameters.

Below is the result of homodyne, the method suggested in the comments. On the test signal, the algorithm was able to identify the required pulses! It remains to write a sketch where there is a detection threshold and definition of the duration!
I was able to write a condition, when the threshold is exceeded, the LED turns on, and turns off otherwise. But I don't know how to make the definition of duration yet ...
Added after a few days:
I was able to assemble the entire structure, the sketch below does the following:

Listens to the audio signal coming to the analog input of the arduino from the radio receiver on the RDA5807M microcircuit, through an amplifier on one transistor, which provides signal amplification and offset to the positive range.

Performs homodyne processing: selects only the signal with a frequency of 1 kHz, all other frequencies are suppressed

Selects the optimal detection threshold for finding the exact time signal of 1 kHz frequency at the background level.

Calculates the duration of each pulse

Finds the exact time by the last impulse using the recalculation formula.

Thus, at the moment I get the exact time digit in the serial port monitor.
But the end result I want to get is setting the resulting digit on a seven-segment display. Having looked at the sketches of his work, I found that the values in the loop are constantly processed there, which again slows down the microcontroller, but for me this is unacceptable. As I understand it, you need to write a separate function into which you pass the value of the hour and set this value on the indicator only once an hour. But I don’t know how to implement it. I ask for help!
/ * Last edited on January 25, 2021.
   1 kHz homodyne signal detection

  This program continuously samples analog input A0 and uses a homodyne
  detection circuitry for signal identification at 1 kHz (+/- 24 Hz at -3 dB).

  The A / D converter is set to "free running mode" and takes one sample every 104 µs.
  The samples are multiplied by two generated 1 kHz signals ("local oscillator") in quadrature to each other.
  The products are then low-pass filtered with a time constant of 64 sampling periods (6.656 ms),
  which gives (I, Q) signals with a bandwidth of 24 Hz.
  Finally, the signal strength is calculated as I ^ 2 + Q ^ 2.

  The program is designed for Arduino Uno and will probably work on any AVR based Arduino,
  having an ADC and operating at a frequency of 16 MHz.

  For a detailed explanation, see
  http://arduino.stackexchange.com/a/21175

  Posted by: 2016 Edgar Bonet Orozco.
* /

// Here is everything related to the parameters of the RDA5807M receiver:
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
#define RDA5807M_REG_RSSI 0x0B
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word (0x0001)
#define RDA5807M_FLG_TUNE word (0x0010)
// masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word (0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

uint8_t volume = 7; // 0..15
uint16_t freq = 938; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;
// Receiver end

unsigned long startTime; // Turn on two timers, this
unsigned long elapsedTime; // and this one
int threshold = 300; // Set the maximum noise level
boolean timing = false; // I do not know...

#include <util / atomic.h>

// The analog input used must be between A0 and A5.
const uint8_t analog_in = 0;

// The frequency we want to define, in Hz.
const float SIGNAL_FREQ = 1000.0;

// Time bits.
const float SAMPLING_FREQ = F_CPU / (128 * 13.0); // 9.615 kHz
const long PHASE_INC = round (SIGNAL_FREQ / SAMPLING_FREQ * (1L << 16));
const int LOG_TAU = 6; // tau = 64 / SAMPLING_FREQ = 6.656 ms

// Set the ADC to constant conversion mode "free running mode"
static void configure_adc ()
{
  ADMUX = _BV (REFS0) // ref = AVCC
           | _BV (ADLAR) // left adjust result
           | analog_in; // input channel
  ADCSRB = 0; // free running mode
  ADCSRA = _BV (ADEN) // enable
           | _BV (ADSC) // start conversion
           | _BV (ADATE) // auto trigger enable
           | _BV (ADIF) // clear interrupt flag
           | _BV (ADIE) // interrupt enable
           | 7; // prescaler = 128
}

// Demodulated (I, Q) amplitudes.
volatile int16_t signal_I, signal_Q;

// Interrupt handler is called every time the ADC is ready to read.
ISR (ADC_vect)
{
  // Read the ADC and convert to a signed number.
  int8_t sample = ADCH - 128;

  // Update the phase of the local oscillator.
  static uint16_t phase;
  phase + = PHASE_INC;

  // Multiply samples by square waves in quadrature.
  int8_t x = sample;
  if (((phase >> 8) + 0x00) & 0x80) x = -1 - x;
  int8_t y = sample;
  if (((phase >> 8) + 0x40) & 0x80) y = -1 - y;

  // First order low pass filter.
  signal_I + = x - (signal_I >> LOG_TAU);
  signal_Q + = y - (signal_Q >> LOG_TAU);
}

/ * Return the power reading. * /
static uint16_t get_power_reading ()
{
  int16_t I, Q;
  ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
    I = signal_I;
    Q = signal_Q;
  }
  return sq ((int8_t) (I >> LOG_TAU)) + sq ((int8_t) (Q >> LOG_TAU));
}

// *********************************************** ***********************
void setup ()
{
  configure_adc ();
  Serial.begin (9600);

  // Receiver start:
  Serial.begin (9600);
  Wire.begin ();
  // Register 02h - enable, settings
  reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  setRegister (RDA5807M_REG_CONFIG, reg02h);

  // And then we decided to further strengthen the bass: (I don't need this, I need to somehow remove it)
  reg02h | = RDA5807M_FLG_BASS;
  setRegister (RDA5807M_REG_CONFIG, reg02h);

  // Register 03h - select radio station
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister (RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);
// Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister (RDA5807M_REG_VOLUME); // Read the current value
  reg05h & = ~ RDA5807M_VOLUME_MASK; // Reset the VOLUME bits
  reg05h | = volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
  setRegister (RDA5807M_REG_VOLUME, reg05h);
  // Receiver end:
}

void loop ()
{
  // Print power readings every 8ms.
  static const uint16_t print_period = 8;
  static uint16_t last_print;
  uint16_t now = millis ();
  if (now - last_print> = print_period) {
    //Serial.println (get_power_reading ()); // Build a graph by which you can determine the optimal threshold
    // If the signal has exceeded the threshold, start timing:
    if (get_power_reading ()> threshold &&! timing)
    {
      startTime = millis ();
      timing = true;
    }
    // If the signal is below the threshold, stop the countdown and display the amount of time passed - the pulse duration:
    if (get_power_reading () <= threshold && timing)
    {
      elapsedTime = millis () - startTime;
      timing = false;
      //Serial.println(elapsedTime);
      if (elapsedTime> = 80 && elapsedTime <= 580)
      {
        int h = floor ((elapsedTime - 100) / 20); // Get the time in hours, but there are 6 pulses, but only the last one is needed.
        //Serial.println(h);
        // "valround" --- Round to the nearest integer,
        // "floor (x)" --- Round down to integer
        if (h> = 1 && h <= 24) // If the time is defined as abnormal, beyond reasonable limits, then simply forget it:
        {
          Serial.println ("Exact time:");
          Serial.print (h);
          Serial.println (": 00");
        }
      }
    }
    last_print + = print_period;
  }
}

// Receiver start:
void setRegister (uint8_t reg, const uint16_t value) {
  Wire.beginTransmission (0x11);
  Wire.write (reg);
  Wire.write (highByte (value));
  Wire.write (lowByte (value));
  Wire.endTransmission (true);
}

uint16_t getRegister (uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission (RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write (reg);
  Wire.endTransmission (false);
  Wire.requestFrom (0x11, 2, true);
  result = (uint16_t) Wire.read () << 8;
  result | = Wire.read ();
  return result;
}
// receiver end

Start by conditioning the signal to a voltage within 0 – 1.5 V (no pulse) or 3 – 5 V (during the pulse). Capture that on a scope and post the trace here. It should be way easier to help you if we can see what the conditioned signal really looks like.

can you actually hear the time signal on the radio? ... how often is it transmitted? ... if you can hear it, then what does it sound like?

Are you referring to the WWV/WWVH time broadcast signal?

or to the 1 kHz beeps

I am receiving a signal from a broadcasting station, and the time pulses sound at an audio frequency of 1 kHz. There are 6 of them, sometimes 5, when there are overlays on the presenter's broadcasting. The signal is transmitted at the end of every hour. Is not WWV/WWVH

Your last plot shows a signal intensity around 40 which, for a sine wave, implies an amplitude of π√(40÷8)≈7 on the ADC in 8-bit mode. This is using less than 6% of the range of the ADC. Also, the strong residual oscillations hint that the average voltage may be far from 2.5 V. You may want to fine tune your signal conditioning in order to fix these issues. You can also add a layer of smoothing on the decimated intensity.

If the voice and music are superimposed on top of the signal you are
looking for, that will make matters quite difficult. The first thing you
have to do is filter out all the unwanted sound. The limit on how
aggressively you can filter is given by the width of the pulses. If you
want to detect 100 ms pulses, your filter width should probably be more
than 10 Hz. The filter you used in your test is way larger than that.
Given the limited processing power of your typical Arduino, it may be
preferable to do all the signal conditioning in the analog domain, prior
to digitizing it on the Arduino. If you really have to do everything in
the Arduino, you will still have to adjust the amplitude and the offset
of the signal in the analog domain so that it fits the range of the ADC.
For implementing a narrow-band filter on the Arduino itself, I generally
recommend to use an homodyne detection scheme. This can give
you very narrow filters at a minimal processing cost. See this other
answer where I discuss the working of the scheme, and provide a
link to an implementation.
If you have something similar to an Uno, you should be able to load that
sketch directly, although you may want to tweak the time constant in
order to make the filter narrower. You can then send it your test
signal, collect back the power readings sent by the sketch through the
serial port, and plot those. This should give you a new test signal for
prototyping the next stages of your processing pipeline. If all goes
well, you would just have to set a threshold for detecting the pulses,
and then have some condition on the length of the detected pulses to
sort out spurious pulses from legit ones.
Edit: I suggested using a threshold on the detected power for
deciding when there is a pulse and when there is not. However, if the
power signal is noisy, this simple scheme may not be good enough.
One possible way to reduce the noise is to increase the time constant of
the filter by increasing LOG_TAU. Do not set it above 8,
otherwise it may overflow some variables. Also note that, the larger the
time constant, the lower the bandwidth, which can be an issue if the
frequencies are not very accurate.
Another option is to low-pass filter the power readings. This can be
done on a sub-sampled signal in order to lower the processing cost.
Finally, for deciding whether there is a pulse or not, it can be useful
to add some hysteresis to the detection, basically simulating a Schmitt
trigger. This is simply accomplished by replacing the detection
threshold with two distinct thresholds: a high one for the “no pulse” →
“pulse” transition, and a lower one for the reverse transition:
const uint16_t LOW_THRESHOLD  = ...;
const uint16_t HIGH_THRESHOLD = ...;

// within loop:
static enum { NO_PULSE, PULSE } state = NO_PULSE;
uint16_t power = get_power_reading();
if (state == NO_PULSE && power >= HIGH_THRESHOLD) {
    state = PULSE;
    register_pulse_start();
}
if (state == PULSE && power < LOW_THRESHOLD) {
    state = NO_PULSE;
    register_pulse_end();
}

Thank you! I used your code unchanged and it works! Only I used the signal from the generator, since I do not yet have an amplified signal after the receiver. Now output the result to the serial port. I only see huge numbers when I apply 1 kHz!
Tell me what can I do next? After all, the survey is carried out quite rarely.

@Антон: Next step would be to define a threshold for pulse detection, but you cannot do that without a realistic test signal (with realistic amplitude): send the test signal to the Arduino, plot the numbers that come out, and select a threshold in between the lowest pulse level and the highest non-pulse level.

I ran a test, this time using a signal from the phone generator. I changed the frequency of the signal and watched the result. I think the optimal threshold is 25.
I cannot give a test signal because Arduino rarely plots points and my short impulses simply does not fix.
I attached the graph in the post above

I increased the sampling rate to 115200 baud, but it is not always possible to detect a 200ms signal ... Is it possible to increase the sampling rate further?

@Антон: A sampling rate of “115200 baud” does not make sense. A sampling rate of 155200 samples per second is more than what the Arduino can handle: processing the samples would require 127% of the available CPU power. You can increase the sampling rate, but that will not help detecting short pulses. You instead have to increase the rate at which samples are printed to the serial port, i.e. decrease print_period. Increasing the baud rate will be needed only if you set print_period to less than 8 ms, which is unlikely to be useful.

How can the values be smoothed without getting a signal lag? I noticed that the signal is very jagged and the time is not always accurate.

@Антон: Every low-pass filter I know about introduces some lag. But the lag is the same for the rising and falling edges of a pulse, so it does not interfere with the pulse length measurement. Re “the signal is very jagged”: see amended answer.

Hello! Your code helped me a lot.
But now my task is to detect rectangular pulses with a duration of 460 μs. Can this be done with the help of your code? What needs to change in it?
I have created a new question on this site, and I would very much like to hear your instructions, as I really liked your solution to the previous problem. Thank you!


text:
Form a signal from an array of bits
I need to reproduce with a digital pin of an Arduino such a key in the form of a sequence of 1's and 0's, where a one takes 2 ms high and 2 ms low, and a zero takes 1 ms high and 1 ms low.

  int key = 0b101100001111;

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  for (int n = 0; n < 12; n++)
  {
    if (bitRead(key, n) == 1) //execute if bit value == 1
    {
      sendSignal(2000);
    }

    else //execute if bit value == 0
    {
      sendSignal(1000);
    }
  }
}

void sendSignal(int duration)
{
  digitalWrite(13, HIGH);
  delayMicroseconds(duration);
  digitalWrite(13, LOW);
  delayMicroseconds(duration);
}

This sketch really works! I figured out what my problem is: I actually need a longer key (64 bits). I am using long type: long key = 0b1000011110001101111100011111001010110001101101111011011100110100; but long only allows 32 bits. What do you recommend to do? Maybe you need to arrange it as an array? I think you can make it easier somehow. thank you

you did not ask a question

0b101100001111 can never fit into a byte.

That new version of the code you posted works for me, no warnings. Which Arduino are you compiling for?

Arduino Uno. Did you manage to blink the LED?

Not visually, because the delayMicroseconds() is too short for the human eye. My oscilloscope shows the right signal. If you want to check visually, replace delayMicroseconds() with delay().

Thanks you! This sketch really works!
I realized what my problem is: in fact, I need a longer key (64 bits). I am using long type:
long key = 0b1000011110001101111100011111001010110001101101111011011100110100;
But long only allows 32 bits. What do you recommend to do? Maybe you need to arrange it as an array? I think you can make it somehow easier. Thank you

There's always an uint64_t to try, on many machines aka long long int.

You should make
byte key = 0b101100001111;

global, i.e. put it BEFORE the setup function and not within it.
Also, a byte only can contain 8 bits, you need 12, so make it an int (thanks to ocrdu, see comment below):
int key = 0b101100001111;

If you need more bits, you can use uint32_t or uint64_t, and count further than the current 12.
Now key is a local variable which is removed after exiting the setup function.
I'm not sure where 'key' comes from in:
switch (bitRead(key, n)) {

Do you get a compiler error, or did you ALSO define a global variable named key ?
Anyway, if you make key global it will fix either way.
A few other remarks:

Try to align your parenthesis, like the 3 }'s at the end, indent them properly, this makes your code much more readable
Instead of the switch/case, you could use an if statement in this case, as the re are only (and always) two possible values (0 and 1):

Thus:
 if(bitRead(key, n) == 0)
 {
     ...
 }
 else // 1
 {
     ...
 }

Try also comments to write in English instead of Greek, you never know when your comments will be read by non Greek readers (like now).

You can make the following fragment shorter and less duplicated:

Original:
digitalWrite(13, HIGH);
delayMicroseconds(1000);
digitalWrite(13, LOW);
delayMicroseconds(1000);

If you wrap this in a function:
void sendSignal(int duration)
{
    digitalWrite(13, HIGH);
    delayMicroseconds(duration);
    digitalWrite(13, LOW);
    delayMicroseconds(duration);
}

Then you can write a 1 by calling:
sendSignal(2000);

and a 0 by calling:
sendSignal(1000);

It's Russian, not Greek. Just saying 8-).

@orcdu thanks :-)

Thank you very much! Really good advice! Did this, it seems like the sketch is without errors and it is loaded into the board. But I cannot track these impulses on an oscilloscope. I tried to change the duration of the impulses by a few seconds, but I don't see the banal blinking of the LED on the 13th pin with my eye, it is always on.
I don't understand what's wrong, everything seems to be logical in the sketch

int key, not byte key. 12 bits won't fit.

@ocrdu good point, I will update my answer

@Антон See the comment of ocrdu; that is an additional bug fix.

You might consider next time remove the Arduino specific lines and use a PC debugger to step through it.

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

If you modify the code slightly, you can use an array of characters of any length, so need to worry about digital word length.
Here's a modified version of your program that does this.
Note that I also took the liberty of replacing the 'magic number' 13 with LED_PIN, and the 'magic number' 12 with KEY_LEN.  I would suggest you do the same with your pulsewidth values - maybe something like PULSE_WIDTH_ONE_USEC and PULSE_WIDTH_ZERO_USEC?  That way someone else (or you 3 months later) looking at your code can easily see what the values are intended to do
const int KEY_LEN = 62;
const char key[KEY_LEN] = { "10110110110101111001011010110100101011011100110110101101101100" };
const int LED_PIN = 13;

//int key = 0b101100001111;
void setup()
{
  Serial.begin(115200);
  pinMode(13, OUTPUT);
}

void loop()
{
  for (int n = 0; n < KEY_LEN; n++)
  {
    if (key[n]== '1') //execute if bit value == 1
    {
      Serial.print("1");
      sendSignal(200);
    }

    else if (key[n] == '0')//execute if bit value == 0
    {
      Serial.print("0");
      sendSignal(100);
    }
    else
    {
      Serial.print("x");
    }
  }
  Serial.println();
}

void sendSignal(int duration)
{
  digitalWrite(LED_PIN, HIGH);
  //delayMicroseconds(duration);
  delay(duration);
  digitalWrite(LED_PIN, LOW);
  //delayMicroseconds(duration);
  delay(duration);
}


text:
Receiver sleep mode RDA5807M
Good afternoon guys!
I have a radio receiver connected to an arduino and I want it not to work all the time, but to turn on by the arduino timer for a certain time, and the rest of the time the receiver must be turned off by software.
I have a working sketch that allows you to tune this receiver, and it also allows you to re-tune the receiver (set the volume and frequency) by calling a function.
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word(0x0001)
#define RDA5807M_FLG_TUNE word(0x0010)
//masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word(0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

//uint8_t volume; // 0..15
//uint16_t freq = 1077; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;

void setup() {
  Serial.begin(9600);
  Nastroika(1, 4, 1077); // Receiver setting: incl. or off (on, off), volume (0 ... 15), frequency MHz * 10 (107.7 = 1077)
}

void loop() {
  Nastroika(1, 4, 1077);
  delay(5000);
  Nastroika(0, 4, 1077); // Nastroika(0)
  delay(5000);
}

void setRegister(uint8_t reg, const uint16_t value) {
  Wire.beginTransmission(0x11);
  Wire.write(reg);
  Wire.write(highByte(value));
  Wire.write(lowByte(value));
  Wire.endTransmission(true);
}

uint16_t getRegister(uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission(RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(0x11, 2, true);
  result = (uint16_t)Wire.read() << 8;
  result |= Wire.read();
  return result;
}

void Nastroika(byte Key, uint8_t volume, uint16_t freq) // Receiver configuration after power failure
{
  Wire.begin();
  // Регистр 02h - inclusion, settings
  if (Key == 1)
  {
    reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  }
  else if (Key == 0)
  {
    reg02h = reg02h & ~RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;

  }
  setRegister(RDA5807M_REG_CONFIG, reg02h);
  // Регистр 03h - radio station selection
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

  //Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister(RDA5807M_REG_VOLUME); // Reading the current value
  reg05h &= ~RDA5807M_VOLUME_MASK; // Resetting the bits VOLUME
  reg05h |= volume << RDA5807M_VOLUME_SHIFT; // Setting a new volume
  setRegister(RDA5807M_REG_VOLUME, reg05h);
}

I need to modify this sketch and add the ability to wake up the receiver and put it into sleep mode. There is "RDA5807M_FLG_ENABLE" here. As I understand it, you need to change it?
Added later:
The method of turning off the receiver for a while, suggested in the comments, works.
However, for everything to be correct, when calling the function when the receiver is disconnected, we will send Nastroika(0, 4, 1077); that is, when turning off, we still specify the volume and frequency, although these parameters are superfluous here. It would be correct to write simply Nastroika(0); , But this cannot be done just like that, because there should be exactly three input arguments for the function, and not one.

Switch off:
reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
setRegister(RDA5807M_REG_CONFIG, reg02h);

Switch on:
reg02h = reg02h | RDA5807M_FLG_ENABLE;
setRegister(RDA5807M_REG_CONFIG, reg02h);

EDIT: (to answer a comment of Антон)
Nastroika (настройка) means "tuning". Is that right? Then I would use this method only for tuning. Create two methods one for switching off and one for switching on.
void switchOff()
{
   reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
}

void switchOn()
{
   reg02h = reg02h | RDA5807M_FLG_ENABLE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
}

In the Nastroika Method you should only perform the tuning and let the module of. If you insist to switch on at the same time you could use your old version.
Example:
void Nastroika(uint8_t volume, uint16_t freq)
{
   // !!!!! This is the wrong place for Wire begin
   // move it to the setup method.
   // Wire.begin();
   reg02h = reg02h | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
   // or if you insist / you want to keep the module be started here
   // reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
   reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT;
   setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

   reg05h = getRegister(RDA5807M_REG_VOLUME);
   reg05h &= ~RDA5807M_VOLUME_MASK;
   reg05h |= volume << RDA5807M_VOLUME_SHIFT;
   setRegister(RDA5807M_REG_VOLUME, reg05h);
}

Usage:
void setup()
{
   Serial.begin(9600);
   Wire.begin();
   Nastroika(4, 1077);
}

void loop()
{
  switchOff();
  delay(5000);
  switchOn();
  delay(5000);
}

Thanks, I corrected the code according to your suggestion. If you can help me get rid of two unnecessary arguments, I will be even more grateful to you

Thank you, I did everything as you said, everything works, I'm happy. We've also fixed some bugs, thank you!


text:
Drivers for CH9102X serial port chip
Some ESP-family cheap boards manufacturers had recently moved to CH9102X serial port chip (from CP2102), and it seems the drivers for CH9102X are hard to find.
Where can I download them?

It can be found on manufacturer's website: http://www.wch.cn/search?q=CH9102&t=downloads
Please note, that some drivers' downloading pages are only available in Chinese, so make sure you open Chinese (not English) site version.
Windows CDC driver: http://www.wch.cn/downloads/CH343CDC_ZIP.html
Windows SER driver: http://www.wch.cn/downloads/CH343SER_ZIP.html
MacOS driver: http://www.wch.cn/downloads/CH34XSER_MAC_ZIP.html
P.S. For Windows 7 x64 I recommend using the first one (CDC). SER driver didn't work for me because of signing issues.

Did you ask this question just so that you could answer it?

Exactly. See also: https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/


text:
Modbus IP with Simply Modbus TCP
include SPI.h
include Ethernet.h
include Modbus.h
include ModbusIP.h

//Modbus Registers Offsets (0-9999)
const int SENSOR_IREG = 100;
//Used Pins
const int sensorPin = A0;

//ModbusIP object
ModbusIP mb;

long ts;

// Set Port to 502
EthernetServer server = EthernetServer(502);

void setup() {
  //Assign the modbus device ID.
  regBank.setId(1);

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    byte ip[] = { 192, 168, 1, 177 };

    mb.config(mac, ip);

    // Add SENSOR_IREG register - Use addIreg() for analog Inputs
    mb.addIreg(SENSOR_IREG);

    ts = millis();

}

void loop() {

   //Call once inside loop() - all magic here
   mb.task();

   if (millis() > ts + 2000) {
       ts = millis();

       mb.Ireg(SENSOR_IREG, analogRead(sensorPin));
   }
}

I am trying to read data from the first analog pin through ModbusTCP using SimplyModbusTCP but I keep getting errors when I poll my Arduino. I am using an Arduino UNO with a Ethernet Shield W5100 and Modbus Library. I am request data from Ip address 192.168.1.177 Port:502 Slave:1 and Function Code:03. The error I get is "Error 66 occurred at TCP Read in SMT8.0.vi. LabVIEW: The network connection was closed by the peer."

did you test the Ethernet shield with some basic Ethernet library example?

Yes I did and it worked fine. I can even ping the unit through cmd.

did you set the register address 100? try 101 in client too

Tried both, with same results

Removed that and I am still getting the same result

still error 66?

input registers is function 04

II get the same thing

Looks like SimplyModbus was the problem, used Modbus poll and was able to read data.

You should not create the Ethernet server. The library creates the server and your server takes the port first.
Modbus function code to read Input registers is 04.

I removed that line and still get the same results

Tried function code 4 and got the same result

try again register 101


text:
Trying to light an LED with one Button and have no idea what is wrong
New to Arduino. I am trying to use a single button to light and turn off a single LED. I followed an online tutorial (youtube video) and changed the code just a bit. I know it is for two LEDs but I tried it for one. I have no idea why it is not working. I don't see why it doesn't make sense but it just does not work.
Here is the code:

float LengthPush = 0; // LengthPush is the amount of time the button has been pressed.

int ShortPush = 100; // 100 ms push. Supposed to turn on the LED.
int LPush = 1000; // 1000 ms push. Supposed to turn it off.

int ButtonPin = 2;
int RLED = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(ButtonPin, INPUT_PULLUP);
  pinMode(RLED, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (digitalRead(ButtonPin) == LOW) {
    delay(100);
    LengthPush = LengthPush + 100;

    Serial.print("ms = ");
    Serial.println(LengthPush);
  }

  if (LengthPush >= LPush) {
    digitalWrite(RLED, LOW);
  } else if (ShortPush <= LengthPush < LPush) {
    digitalWrite(RLED, HIGH);
  }
  LengthPush = 0;
}

Are you getting compiler errors? If yes, you have to include them into your question. "Doesn't work" is not a good description. I would think, that the else if statement throws an error, because you try to compare 3 values in 1.

I just got it right!  My mistake was comparing 3 values. I thought i had to specify that the press length had to be more than 100ms, but less than 1000 if I wanted it to turn on. Turns out the compiler already does that. Thank you for answering.

Also you can remove the semicolons directly after each opening bracket {. Also try to align your code so that each nested { is indented one level according to its nested level.

I formatted your source code in Question. How do you like it?

@chrisl I suggest you to write your comment as an answer, so the OP can close the question

I think your problem lies in the else-if-statement, where you try to compare 3 different values. While this doesn't thrown a compiling error in my Arduino IDE, it will probably not do, what you are trying to achieve.
Instead you need to compare LengthPush with one value and then with the other. You can even do this inside the same if statement:
if(ShortPush <= LengthPush && LengthPush < LPush)

The && is the boolean AND operator, which means, that the if statement will be executed, if both statements around it will evaluate as true.

I'm not sure, what actually happens with your original code, since it doesn't throw a compilation error. It might be (and that's my theory here), that the program will first evaluate ShortPush <= LengthPush and then compare the result to LPush. Since boolean values evaluate as 0 or 1 in integer calculations, that messes up the whole intent of this. Take the case, that LengthPush is really in the required interval. Then the first part will evaluate as true, which means 1 as integer. Then this 1 get's compared to LPush, which is always higher, so the overall result is true. But the same result comes, when LengthPush is smaller than ShortPush.


text:
How do you make a stepper motor move at decimal (such as 0.5) steps?
if I were to use a code with the following format,
//some loop
digitalWrite(STEP_PIN,HIGH);
digitalWrite(STEP_PIN,LOW);
//

each loop would make the motor move at one step. With this loop I can also make the motor move at 200 or other integer steps. However, is it possible to make the motor move at decimal steps such as 0.4?

It is called microstepping. There are modules with current control that can do microstepping. The easiest solution for you can be a geared stepper motor.

Depends on you stepper driver. It needs to support microsteps. Which driver do you use?


text:
Can't add board for RFDuino in Arduino IDE
I tried to upload sketch to my RFDuino. I can select the RFDuino port. But I can't upload cos I can't select the RFDuino board.
I followed the installation steps listed here
but I don't see RFduino package in Board Manager after I finished the steps above.
I am using Mac Mojave and Arduino IDE v1.8.9. I have tried it with v1.6.6 but results the same.

I get Error downloading http://rfduino.com/package_rfduino166_index.json

the company RFDigital is gone. no support. try a manual install

I had this problem with STM32 package. Go to Arduino15 folder(%appdata%) and delete download cache

@SilvioCro, did you try it?

@Juraj When I did those steps(in my case it was STM32 package - this link, it worked. Go AppData\Local\Arduino15 and delete package_index.json.sig and package_index.json files

@Juraj No. Sorry, I was on the phone(when I wrote 1st comment) so it was messy. My bad.

Turns out that rfduino.com's domain is gone, so the link will always return with an error downloading. After reading this thread arduino.cc, @pert posted a link for the .json file that used to be at the website you have. I used this link on MacOS Mojave and Arduino v1.8.9 and it worked perfectly!