text:
Making Serial act as an interrupt
I am trying to make a program to control a stepper motor with serial inputs, and in writing a function to jog it, I am having trouble figuring out how to make a serial input stop the loop that steps the motor without making the time per step inconsistent.  Is there a way where I can have a new serial input act like an interrupt and break any loop that's in progress.
void jog() {
  if(input[1] == 0) sd.setDirection(0);
  else sd.setDirection(1);
  while(true){
    if(Serial.available() > 0) break;
    sd.step();
    delayMicroseconds(10);
  }
  sd.setDirection(0);
}

Right now I have this (I'm using a Pololu library that defines the steps), but for some reason this does nothing or at least moves so slow it's imperceptible (a single step only moves the motor 0.007 degrees).  It moves the motor very smoothly if I delete if(Serial.available() > 0) break; but then I can't stop it.
void loop() {
  getData();
  switch(input[0]){
    case 'r':
      Serial.write('r');
      ramp();
      break;
    case 'c':
      Serial.write('c');
      cycle();
      break;
    case 'j':
      //Serial.write('j');
      jog();
      break;
    default:
      break;
  }
}
void getData(){
if(Serial.available() > 0){
  for(int i = 0; i < 200; i ++){
    input[i] = 0;
  }
  for(int i = 0; i < Serial.available(); i++){
    input[i] = Serial.read();
    Serial.print(input[i]);
  }
}
Serial.flush();
//Serial.print(input[0]);
}

This is the relevant code that calls jog()

Please show us a complete working example, that shows your problem, not only one function. Can it be, that there is still data on the Serial buffer, when you enter the jog() function? In that case it would exit directly

It does not have anything in the buffer when it starts.  Post updated with full code.

How do you know, that there is nothing in the Serial buffer, when you enter the jog() function? You don't check for this.
I think your problem is actually in your getData() function. The for loop
for(int i = 0; i < Serial.available(); i++){

might not work as you think, because i increases in every loop iteration while Serial.available() decreases in every iteration. So you actually read less data, than is available on the buffer. For example let's assume, that you have 2 Bytes on the buffer. Serial.available() returns 2. In the first for loop iteration i is 0, while Serial.available() is 2. When you read from the Serial buffer in the iteration, Serial.available() decreases to 1 (since you removed one byte from the buffer by reading it). At the end of the iteration, the for loop will increase i by 1 (due to the i++). Now in the condition of your for loop, you have 1 < 1 (because both i and Serial.available() are 1), thus the for loop will exit without any further iterations. But you still have 1 Byte left in the buffer, that you didn't read.
As I read from the documentation of Serial.flush() (though the documentation is notoriously bad) and from this question, I see, that it will only wait until the output buffer is emptied by the interrupt routines. It does nothing with the input buffer. So you still have data in your RX buffer after this line.
That means, that you really have data in your RX buffer, when you get into the jog() function. Thus it will directly exit without doing any step.

To solve the issue, you should first correct your getData() function to read all the available data from the RX buffer. You can change your for loop like this:
for(int i = 0; Serial.available() > 0 && i < INPUT_BUFFER_SIZE; i++){

This will loop until the RX buffer is empty (when Serial.available() returns 0) or until your input[] array is full (Please add a constant or a define for the input buffer size. Maybe you already have it. You didn't include the full code. But I guess it is 200).
After the for loop, you can empty the buffer by reading from it, until there is nothing left (Please see the linked question for that). You can even do this at the start of your jog() function. This ensures, mostly, that no data is in the buffer at the start of the jog() function (mostly, because the timing of data reception could be, that you receive a byte between the emptying of the RX buffer and the loop. Little probability, but not impossible).
Though - as Nick Gammon states in the linked answer - it is not the best way to empty the RX buffer and use every serial input as interrupt (sometimes you don't have exact control, when exactly the data is received). A better solution is to implement a message protocol, where the end of a full message is marked with a special character. Then you read from serial, until a full message is received (you can even do this non-blocking, so that you can do other things until the message is complete), and only then act upon the message. This would need bigger changes in your code. You would have to rewrite your getData() function and then remove all blocking code from the sketch (for example all delays) and work with non-blocking code instead (for example using the micros() function. The principle is explained in the BlinkWithoutDelay example, that comes with the Arduino IDE (though it uses millis() instead of micros() it is the same principle). You would call the jog() function repeatedly, which would only do a step, if it is time to do one. In the meantime the rest of the code can receive new messages. This makes you more flexible and independent of the exact timing of data reception. Since this would be a big rewrite of your code, you have to decide yourself, if you want to go this way, or stay with the simpler and more imperfect solution.


text:
RFID RC522 card reader project(servo, buzzer, two led) with FreeRTOS
So I wrote simple code which turns on led, buzzes and rotates servo motor when card readed. It works normally. But I want buzz, rotate and on off functions to work asynchorous. I will paste the code which I tried to apply freertos. Any help is appreciated!
void loop() {
 if (!mfrc522.PICC_IsNewCardPresent()) {
 return;
}

if (!mfrc522.PICC_ReadCardSerial()) {
    return;
}

for (byte i = 0; i < mfrc522.uid.size; i++) {
  card_ID += mfrc522.uid.uidByte[i];
}

if (card_ID == rfid) {

  //
  // I want to create async tasks here...
  //
  buzz(750, 1000); // task 1

  green_on();      //
  delay(1500);     // task 2
  off();           //

  rotate();        // task 3

}
//Serial.print(card_ID);
else {
  red_on();
  delay(700);
  off();
  red_on();
  delay(700);
  off();

  buzz();
}

card_ID = "";
}`

my freertos applied code is this. i will just paste the rotate function of all task functions for showing purposes:
void setup() {
// some code here  - inits and other things
  xTaskCreate(Main,(const portCHAR *) "Main", 128, NULL, 1, NULL );
  vTaskStartScheduler();
}

void Main(void *pvParameters) {
(void) pvParameters;

for(;;) {
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
    }

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

    //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

    for (byte i = 0; i < mfrc522.uid.size; i++) {
     card_ID += mfrc522.uid.uidByte[i];
   }

   if(card_ID==rfid){
    xTaskCreate(Buzz,(const portCHAR *) "Buzz", 128, NULL, 2, NULL );
    xTaskCreate(GreenLed,(const portCHAR *) "GreenLed", 128, NULL, 3, NULL );
    xTaskCreate(Rotate,(const portCHAR *) "Rotate", 128, NULL, 4, NULL );

   }
   //Serial.print(card_ID);

   else {
     xTaskCreate(RedLed,(const portCHAR *) "RedLed", 128, NULL, 2, NULL );
     xTaskCreate(Buzz,(const portCHAR *) "Buzz", 128, NULL, 3, NULL );
   }

   card_ID="";
 }
}

void Rotate(void *pvParameters) {
(void) pvParameters;

 for(;;) {
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                      // waits 15ms for the servo to reach the position
}
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      vTaskDelay(15 / portTICK_PERIOD_MS);                       // waits 15ms for the servo to reach the position
    }
  vTaskDelay(1);
}

}

what do you mean by work asynchorous? ... please provide a clear description of the desired behavior

sorry if I'm mistaken, I am trying to say that I want three tasks to work at the same time, I also have written it in first code, line 12

source: Stack Exchange

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

sort: votes


text:
STM32 as keyboard
I would like to use a STM32F105xx to build my own computer keyboard.
That MCU has support to USB OTG (FS).
So, I have 2 questions:

Can I flash microcontroller with usb or I need a external
programer?
How to do the computer recognize stm32 as a keyboard?

https://arduino.stackexchange.com/tour

The STM32F105xx series is not yet supported by either Arduino core (STM32 core or maple core) and neither mbed-os.
The chip is still usable with the STM32 provided framework, the STM32HAL, (e.g. through STM32CubeMX). There you can select your chip and generate a template project. The program lets you easily configure the chip for "USB Device" role and HID (Human-Interface-Device) class.

Note that from a hardware side, you must provide the chip with an external crystal oscilator (usually 8MHz) so that the HSE+PLL can generate the 48MHz USB clock. This will not work on the internal HSI clock due to low precision. Activate the HSE Crystal in the RCC section of CubeMX and see the clock configuration tab.
From there on you'll have to read the STM32F1 HAL documentation to figure out how to send keystrokes. There are also external resources here and here.
Programming the board via USB is possible. Just set the BOOT0 and BOOT1 pins accordingly and reset the board to get into bootloader mode. It will then appear as a USB device which is flashable by given tools. See e.g. here. The more direct way is to buy a cheap STLinkv2 and program it via the SWD pins (SWDIO + SWCLK), which also enables debugging, which USB flashing does not.

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


text:
light leds from an array
I have the project to build a robot for my school. It will record button pushes then move according to this record.
Before usig motors, i'm trying to do this using leds.
Thanks from posts from this community, I've succeed in recording button pushes in an array.
Now I'm trying to light the leds according to this array.
I have 4 buttons with 4 leds and one button tu run the recording when it's ready.
I'm stuck in lighting the leds when I push the play_button.
I hope someone can help me...
Here's my script :
int arr[10];
boolean previous = LOW;
unsigned long time1 = 0;
int debounce = 200;
unsigned long time2 = 0;
int index_state = 0;

int play_button = 13; //define pin # for play button

int button[4] = {2,4,6,8}; //store button pins in an array
int leds[4] = {3,5,7,9}; //store led pins in an array

void setup()
{
  for(int n=0;n<10;n++) arr[n] = 0;//initialisition
 Serial.begin(9600);
}

void loop(){
 boolean mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);
 while(mode == LOW) mode = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead (8);//wait here till one of the pushbutton goes high;
 //Serial.println("value");
 if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {
 //find out which one is high and store that value in array;
 if(digitalRead(2)) arr[index_state] = 2;
 else if(digitalRead(4)) arr[index_state] = 4;
 else if(digitalRead(6)) arr[index_state] = 6;
 else if(digitalRead(8)) arr[index_state] = 8;
 else ;

 //print the value and the index;
 Serial.print(arr[index_state]);
 Serial.print(" Stored in index: ");
 Serial.println(index_state);
 index_state = (index_state + 1) % 10;
 //update value of time1 for button debouncing
 time1 =  millis();
}

  //update the value of previous button state
  previous = digitalRead(2) || digitalRead(4) || digitalRead(6) || digitalRead(8);

  }

Thank you

You have problems in including the further functionality (the playback), since your loop() function is solely written for providing the first part of functionality (the recording). You need an overall structure, that will execute the correct functionality at the correct time/logic order.
For this, an Finite State Machine (FSM) is the best way. It will help you to structure your code and the logic. It is an important principle to learn.
First you would have to divide your program logic into different states and transitions between them (don't look too close at the actual code at this point, but with a higher abstraction). Currently I see 2 states in your project: A state, where you are recording the button presses in an array, just like you already did. And a state, where the array is used for playback. The transition from the first to the second state happens, when the playback button is pressed. The transition back happens, when the playback is finished. It helps to draw a graph for this, to visualize the the states and their transitions. In my answer to this question I explained this further including an example of such a graph.
When you are finished creating the states and transitions, you can create the necessary code structure. The easiest way for a beginner is to use a simple state variable (simply an integer, or - if you want to use names for the states - an enum) in a switch()-case statement. You can also see this in the linked answer. Your code then goes into the case statements. The switch statement will only execute the code for the current state. To do a transition to another state, you simply change the state variable. So in the case statement of the first state, you put the code that you already have for reading the buttons, and an if statement, that checks the playback button. If the playback button was pressed, change the state variable to the second state.
You could also solve this problem without an FSM, but the structure won't be that good and easy to expand. Also you might get some extra points for implementing an FSM :D

Currently your code is blocking. That means, that it will block any further operation, until something happened, in this case, that one of the 4 buttons gets pressed. Often this is only a hindrance, when adding functionalities. It is better to use do-maybe code, means code, that will only do something, if some condition is met (like time). You are already doing this in the if statement
if( mode == HIGH && previous == LOW && millis() - time1 > debounce) {

(it only triggers the recording of a new button, if a button was pressed and the debounce time has passed) so why are you blocking before this with the while loop? You could just write to mode without the while loop.


text:
Scope of RtcDateTime object when declared outside of a function
I'm trying to merge 2 Arduino samples, in order to be able to use DS3231 RTC module with ESP8266 WiFi simple web server.
My RTC library is this:
https://github.com/Makuna/Rtc/wiki
Generally, to code runs ok (I have the Web server responses to my browser calls, and I think the DS3231 RTC code also works). But when I'm trying to use a variable from within the RTC object into the Web server function - I get nothing.
I thought declaring the 'now' object outside any function (Setup() nor Loop()) will make it global, and when I'll update it in the Loop() function using
now = Rtc.GetDateTime();

It will be available to other functions as well, but all I get is "0" when I try to print it.
My code is here:
Definitions part:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* This block is for I2C protocol for DS3231 module (for normal hardware wire use below) */
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
RtcDS3231<TwoWire> Rtc(Wire);
/* The above block is for I2C protocol and DS3231 module  (for normal hardware wire use above) */

ESP8266WebServer server(80);
RtcDateTime now;

My Loop():
void loop(void) {
  now = Rtc.GetDateTime();
  Serial.println(now.Minute());
  server.handleClient();
  delay(500);

}

And all I get is "0" printed.
Any help would be appreciated!

And your code outputs the correct minutes, if you move the declaration of now into the loop() function?

What do you get if you remove the WiFi Web server code?

Update: Thank you so much for everyone looked into it. I've just now tried to debug it, and found that for a strange reason - my DS3231 module stopped working (forgot the time, and also didn't advance, even after program resets). What worked was to disconnect it from power and take out the battery. Now it works ok, and the scope of the variable is good also. Should I delete my question now? or just leave it like this? Many thanks again! I appreciate it so much!

As was suggested by more 'native' friends here - I'm 'Answering my question' to make things clear.
After a check and debug - I've found a mysterious behavior that happened to my DS3231 module. Probably a mistaken initializing set of calls - made it stop working - not getting time updates and not counting the time at all. (Freeze at 1/1/2000, 00:00:00).
Disconnecting it from power source, and taking out the battery - returned it to normal behavior, able to get time updates, and answering the calls from the library.
When that part solved - everything else went as easy as it should.
The code sample I posted in my question (declaring the 'now' object outside of setup() and loop() functions) made that object global, so another function (WebServer) can read its current value and use it internally.
Thanks everyone who looked at my problem and helped,
It was a great lesson about how not to take anything as 'known' without double-checking.


text:
Text got scrambled on Tinyscreen+
Yesterday when I was trying to reset my Tinyscreen+ by using a needle to flick its power switch (because the case made it hard to do it with my fingers). It was a bit clumsy and I may had shorted some connections in the process. After that, the text on the bottom part of the screen become scrambled as shown in the attached image.
Does anyone have an idea on what caused that and if it's fixable?
Thanks for any help

you already said what caused it ... yes, it is probably fixable ... you have to determine where the failure is located ... you also have to decide if you want to spend time and money to repair it ... it is cheaper to replace it

If it still happens after you completely power off and back on you've probably destroyed the hardware. Time for a new screen and a $40 lesson learned the hard way.

You may be able to replace the OLED module itself if you're handy with a soldering iron. The controller is SSD1331, one likely part number for the display module is CFAL9664B-F-B2. Or, it looks like you're using monochrome images; you could replace with a much cheaper SSD1306-based display.

The schematic says it's a UG-9664HDDAG01 (not sure if it's just the controller or the whole thing). Although I think I'll just use the top 3/4 of the screen for now.


text:
ATMEGA32u4 Arduino Bootloader Issues
I've been struggling with this issue for a few days on and off now.  I made a custom PCB (schematic) for a smaller Arduino Pro Micro and it works - mostly.  The only issue I had was that the pins on the USB connector were backward, but when I soldered on a USB cable everything worked as expected.
I then made a new board (schematic) with the following changes:
 - Fix the USB connector
 - Changed two of the GPIOs that were brought out to pins (from D4 and D17 to D6 and D9)
 - Added an onboard LED connected to D8
 - Removed the jumper on HWB pin
I have been able to burn the bootloader using both an Arduino Uno and with an AVRISP mkII.  When I plug the micro into the computer the first time it is recognized as an "Arduino Micro (COM6)".  Then I try to upload the Arduino example Blink.ino sketch - and that works too.  In the process the IDE forces the reset and in device manager I can see the "Arduino Micro bootloader (COM7)" replace the micro on COM6.  The LED does begin to blink but in device manager it remains as "Arduino Micro bootloader (COM7)".  When I try to upload another sketch to this port it fails (as I would expect) because it cannot force the reset; presumably because the bootloader is already active.  So I unplug it and try again.  It shows up as "Arduino Micro (COM6); all looks good but when I try to upload it cannot force the reset, tries to upload to "Arduino Micro (COM6)" and fails (I assume because it is not entering into the bootloader).
When I double tap the reset pin or connect to the arduino using a baud rate of 1200 the micro does reset (as expected) and the light stops flashing so I suspect the bootloader is being executed - but on device manager it remains as "Arduino Micro (COM6)".
If anyone has any ideas I'm all ears.  Normally I do not have to fight with Atmel hardware like I have on this issue.

The bootloader on the chip only waits a few seconds for an upload request. If you start the upload within this time the things will happen as you expect them. If the time is over the bootloader stops listening on the serial port and frees it for the program.  You can reenter the "boot time interval" by resetting the chip. But as you have no button ( ;-) ) this would be difficult. A UNO for example has an extra USB to Serial converter chip that can perform this reset before the programming starts. Can you add an external reset button and try pressing it and start the programming immediately?

If you ask why the first upload was possible: As long as there is no program on the chip, the bootloader has no reason to give up control to a program. Then it waits forever for an upload.

That second comment makes sense (kinda what I figured).  When I reset (wire soldered to the resistor-next board will have a pin for RST) the chip the LED I connected for the blink turns off for 8 seconds.  (This is the boot time interval for the Arduino Micro bootloader I believe.  To the computer it is still seen as "Arduino Micro (COM6)" - not bootloader.  When Arduino IDE attempts to connect to the programmer (LED still off) it errors out.

8 Seconds sounds reasonable. It depends from where you got the bootloader, but the device name  "Arduino Micro" is the correct string for the caterina version that is chosen automatically by the IDE.  I found another thread that could be the solution but I don't understand why. Please see  https://arduino.stackexchange.com/questions/57651/arduino-pro-micro-bricked.

Perhaps this is also interesting: https://www.eevblog.com/forum/microcontrollers/reinstall-bootloader-for-an-arduino-pro-micro/ That's also a good read, if you use a linux box as workstation (like me).

It seems like the bootloader is not connecting via USB for some reason.  I can cause the chip to reset by open/closing a COM connection at 1200 baud.  It appears to be entering the bootloader section of flash because the LED stops flashing.  Same thing happens when I double tap the reset button.

The issue I am having a problem wrapping my head around is that I have two versions of this board; one works, one doesn't. Using Atmel Studio I can verify that the flash, fuse and lock bits are all identical. I updated the question with both schematics.


text:
FreeRTOS single thread vs Function call
Good day to everyone,
I am currently working on project using ATmega2560. I want to use threading, that is why I decided to use FreeRTOS. However, I cannot make one thread to work fine, so that I start writing second one. So, I have following code:
#include <stdlib.h>
#include <avr/wdt.h>
#include <Arduino_FreeRTOS.h>
#include <semphr.h>

void setup()
{
    pinMode(car_state_pin, INPUT);
    pinMode(battery_pin, INPUT);

    Serial.begin(9600);
    Serial2.begin(9600);
    Serial3.begin(9600);

    watchdogSetup(); //setup WD for 8 secs

    Serial.println("Create Tasks");

    Serial.flush();
    Serial2.flush();
    Serial3.flush();

    xTaskCreate(collect_data, (const portCHAR *) "GPS_Collect_Data", 128, NULL, 1, NULL);

    //collect_data(NULL);
}

And I have function collect_data which should run as thread:
void collect_data(void *pvParameters)
{

    (void)pvParameters;
    uint8_t len;
    char *tmp;

    for (;;)
    {
        millis_delay(2000);

        if (digitalRead(car_state_pin) == HIGH)
        {

            Serial.println("Collecting Data");
            tmp = (char *) calloc(50, sizeof(char));

            do
            {
                wdt_reset();
                len = gps_get_data(tmp);
                Serial.println("Len < 15!");
                millis_delay(100);
            } while (strlen(tmp) < 15);

            /* Add imei and state of the car into the data string */
            len += sprintf(tmp + len, "%s,%d,%d", imei, digitalRead(car_state_pin), digitalRead(battery_pin));
            tmp[len] = 0;

#ifdef DEBUG
            Serial.print("TMP IS: ");
            Serial.println(tmp);

            Serial.print("Len is: ");
            Serial.println(len);
#endif

            free(tmp);
        }
    }
}

The problem is, this current code does not work properly, it resets automatically after printing "Collecting Data" and it just repeats forever (So output is:
Creating Tasks
Collecting Data
Creating Tasks
Collecting Data

and so on).
However, when I comment xTaskCreate and do normal function call (uncomment the last line of setup), it works perfect. Can there be any reason, why thread wouldn't work as normal function call? I guessed maybe because of stacksize, but I've increased it and still no result.

What is wdt_reset() supposed to do?

@SimSon The watchdog handling is activated for RTOS and you have to ensure that it is triggered in between the watchdog time interval (here 8 sec ?). If these triggers do not occur, the MCU assumes a hanging interrupt and resets the MCU. I'm more concerned about the cmalloc without a free.

You use cmalloc without freeing the memory. The task needs memory. The greater the stack is, the more memory is used by the task, the less memory you can allocate. If you use more stack memory there is not enough memory for the second malloc. Why do you allocate the buffer in the loop? If you need it, be sure to free the tmp variable after usage. Use a smaller stack size. You only need space for the task frame and the local variables.

@PeterPaulKiefer ahh, I remember. Thanks for reminding!

@PeterPaulKiefer thanks for your answer. However, decreasing stack size and free-ing tmp did not change anything. Again, function call works fine, however, thread fails. I already made changes to the code snippet


text:
How to get text to flash on ssd1306 i2c screen
I am trying to alternate a string back and forth on the SSD1306 oled screen.
So I want the display to show "test1" for 0.5 seconds, then "test2" for 0.5 seconds, repeating. the code below is just showing "test1" for 0.5 seconds then going blank...
I am using a ssd1306 128_32 i2c screen, and using the adafruit library.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);

  display.setTextSize(4);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);

}

void loop() {
 testdrawstyles1();
 testdrawstyles2();
}

void testdrawstyles1(void) {
 display.clearDisplay();
 display.print(F("test1"));
 display.display();
 delay(500);
}

void testdrawstyles2(void) {
 display.clearDisplay();
 display.print(F("test2"));
 display.display();
 delay(500);
}

Perhaps you have to reset the cursor. I don't know if clearDisplay handles that for you.  Could you please try: display.setCursor(0,0); above each print statement. Perhaps, actually you print the text to "nirvana".

That did it! Thanks! Convert your comment to an answer please :)

As approved by the OP, the error was caused by not having reset the cursor to a visible position on the display. The text was written outside of the OLED.
It seems as the clearDisplay() method does not reset the cursor.
The solution is to change the following methods
void testdrawstyles1(void)
{
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(F("test1"));
  display.display();
  delay(500);
}

void testdrawstyles2(void)
{
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(F("test2"));
  display.display();
  delay(500);
}


text:
Arduino and DAC
this might be more general electronics question, forgive me if this is not the correct place to ask.
I am atempting to use the arduino and MCP4725 breakout board to inject 4 different voltages into an existing line that comes from V1.
V1 is the analog signal from an existing unit and varies between 2v, 3v and 4v. VM1 responds to those voltages and switches to a different working modes. 2v == Mode A, 3v == Mode B, 4v == Mode C.
My plan is to have MCP4725(represented as V2 below)hooked up to Arduino to simulate Modes A, B, C when needed.
MBR0540 D2 is there to prevent sending the voltage back to the sending unit, MBR0540 D1 is to do the same for DAC.
I am worried that if the D2 fails for whatever reason, I might loose the sending unit functionality.. is there a better way to do it?

simulate this circuit – Schematic created using CircuitLab
Thanks for any help/comments you might have.

VM1 will receive the higher voltage of the two sources. If V1 is set to 4V then V2 will not be able to do anything - it will be ignored. Is that really what you want?

yes, thats what I would like, to occasionally send higher voltage and change the Mode on the receiving end ignoring 2v in this case

Here is a video about reverse voltage protection. It's my favorite one. High current is not your problem. But Afrotechmods shows more ;-).  https://www.youtube.com/watch?v=IrB-FPcv1Dc . With the MOSFet solution you have nearly 0 voltage drop. Then you can make the protector more safe by using more stages.

You can also use two OpAmp Buffers https://en.wikipedia.org/wiki/Buffer_amplifier to separate the two outputs from each other. That has also the avantage of being able to drive more load, if you would need it.

There is also a solution I would like the most. As you ask for security, a complete separation of the two lines would be the best way. I would measure the output voltage of V1 with the arduino and if the arduino should overwrite it with a higher voltage it generates it with the MCP4725. Both outputs the V1 and V2 are connected to a 2 channel analog multiplexer. The arduino is able to toggle it for its needs. It depends on the security level you needs, whether you should use such a complicated solution. But I would do it, just for the fun ;-).

thanks @Peter Paul Kiefer I will investigate the MOSFET solution, is there a safe(fallback) solution using analog multiplexer so that if it fails it fails back to V1 voltage all the time?

There is always a risk that the multiplexer fails. You could use two of them to lower the risk. you have also the risk of a failing MCU. If you use two multiplexer in parallel, you could lower the risk that the multiplexing will be disturbed. But it's more complex to handle MCU failures. You could build a watchdog circuit with a capacitor that is loaded over a time interval and that is discharged from an permanently triggered impulse by the MCU. If the MCU fails the cap. is charged to the maximum voltage. You can use the voltage to switch the muxer to the V1 channel. (Just an idea!)

Unless you are really stressing it, it is highly unlikely that D2 would fail.
You could, though, replace both diodes with a simple SPDT switch to select between the two voltage sources.
Whatever you do, though, it probably has about the same chance (or more so) of failing (and the same end result) as having the diodes.
You could always add an "emergency override" switch that both bypasses D2 and isolates V2 in case of failure.

thanks for this, what would stress it? would giving it permanent 4v be considered stressing it?

The MBR0540 supports up to 40V, so you're not even close to stressing it.


text:
Arduino problem
I'am making a temperature monitor using an IC2 Interface and a dht11 sensor connected to an arduino uno, it works great when it´s plugged to the computer but whenever i plug it to a 9v battery the humidity goes to "0" and the temperature to "2", it only works when i resend the code through the ide to the arduino.
What could be the problem?
Code :
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
DHT dht;

void setup()
{
  lcd.begin(16,2);
  lcd.clear();
  dht.setup(7); // Pino 7

}

void loop(){

  float humidade = dht.getHumidity();
  float temperatura = dht.getTemperature();

  lcd.setCursor(0,0);
  lcd.print("Humidade: ");
  lcd.print(humidade);
  lcd.print("%");

  lcd.setCursor(0,1);
  lcd.print("Temp: ");
  lcd.print(temperatura);
  lcd.print("C");

  delay(1000);

}

why are you posting the code? ... you said that it works correctly

Just so you can see it´s output

think about what you did to make it fail

Fixed it by clicking the red button on the arduino uno.

The 9v sort of "cube shaped" batteries have a notoriously limited current output, resulting in falling voltage as the current demand rises. The Arduino's voltage regulator is not very effecient either, plus the battery gives only 2v of "headroom" over the minimum Vin voltage of 7v. Your system is probably starving. Try a different source.

Im new to arduino i got it fixed by clicking the red button in the arduino board, it started giving me the right numbers connected to the 9v battery.


text:
Adafruit ImageReader Library 2.3.5 added several library dependencies
Why has Adafruit ImageReader Library v2.3.5 recently added six dependencies on other libraries for hardware I'm not using?
I used the v2.3.2 of the Adafruit ImageReader Library successfully two months ago. An example sketch worked fine with my ILI9341 3.2" display and its SD card.
Now there is an updated v2.3.5 available but the library manager wants to add six more "dependency" libraries:
- Adafruit ST7735 and ST7789 Library
- Adafruit seeswaw Library
- Adafruit HX8357 Library
- Adafruit SSD1351 library
- Adafruit SSD1331 OLED Driver Library for Arduino
- Adafruit EPD
As far as I know, the ILI9341 uses none of the hardware that corresponds to the six libraries it's trying to drag in. I don't want unneeded dependencies and don't want the code bloat.
If I don't accept the additional libraries, my sketch fails to compile. The error message is "C:\Users\barry\Documents\Arduino\libraries\Adafruit_ImageReader_Library\Adafruit_ImageReader_EPD.h:18:10: fatal error: Adafruit_EPD.h: No such file or directory"
However, EPD code is for "e-paper displays" which does not apply to my ILI9341 which is a TFT display. I don't think EPD code should be a real dependency.
Kindly redirect me if there's a better place to ask.

If you don't use the functions of the ImageReader library, which use the additional libraries, your compiled code will not contain code from the additional libraries.
The Adafruit ImageReader library may have functions which use other libraries and the libraries are required for compilation. But at linking the compiled units which are not used by your code and even parts of the compiled units which are not used by your code are not put in the resulting hex or bin file.

I sincerely hope that the linker is smart enough to leave out compiled units that are not used. However, linkers can only operate upon external references between components and is not able to detect run-time usage.

So in my case, if the ImageReader library has a "new EPD()" statement anywhere (I don't know if it does or not), such that the instantiation occurs at run-time, the linker must include the EPD library code, regardless of if it's ever actually called or not, right?
Bottom line, I think I need to get a clean compile, find the .elf file, and generate a memory map to see what components are included. Thanks!

yes there are things where the compiler can't evaluate the dependencies (like virtual methods of classes), but the new EPD() is not one of them. here it is clear at compile time that the class EPD will be used.

I hope to get an answer to the original question "Why has Adafruit ImageReader Library v2.3.5 recently added six dependencies on other libraries for hardware I'm not using?"
On GitHub, the library description only says "Requires Adafruit_GFX library and one of the SPI color graphic display libraries, e.g. Adafruit_ILI9341." However the current version depends on six additional libraries for other hardware.
link

@Barry, the reason is CI tests of examples https://groups.google.com/a/arduino.cc/forum/#!topic/developers/kMS80BNOLW8

Juraj, with your link I've learned about "Travis CI", an automated continuous integration system and followed it for tips about build-checking my Arduino projects for various processors. Good stuff. This will be useful for my Feather M4 (SAMD51) projects.
I'll pursue the issue of code bloat separately. I need to write sample programs and examine the resulting memory map. Then I can tell how many unused libraries for unused hardware finally end up in the compiled object code. Anyway, that's a separate issue and this question is well answered.

@Barry, if the additional libraries are used only in examples then there is no way to your code for them.


text:
How to detect button presses with a 74HC595 shift register?
Is there a way I can have my arduino uno differentiate between pushbuttons that are wired through a shift register and detect when each are pressed or not? I found this tutorial for the 74HC165 but I'm not sure it's applicable to the 74HC595.

The 74HC595 is a deserializer while the 74HC165 is a serializer. This means the former consumes a serial datastream and provides all data bits in parallel on dedicated data lines. While the latter consumes parallel data and converts it to a serial datastream.
To scan buttons you want to have parallel input data, where each switch is attached to a single data line. Then you serialize the data to reduce the amount of required Arduino inputs. This method is well explained in the mentioned tutorial.
As the 74HC595 is a deserializer it is not really applicable here. Instead you could use it to drive multiple outputs through a serial interface (see https://www.arduino.cc/en/tutorial/ShiftOut as an example).

Well, it's not completely true about it's not applicable. It can be used as outputs for scanning buttons. However it has some pitfalls


text:
What is the best way to assign pins to an LED Cube?
I have made an LED cube that is a 3x3x3 design and was wondering if there is way to make a function in the Arduino IDE where each the layers of LEDs can be represented by a list with 1 being on and 0 being off:
{1, 0, 1, 0, 1, 0, 0, 1, 0} with the first number of the list being the first column, then the second column, etc. and the same for the rows which would be something like {0, 1, 0}. Does this make sense? If so, is there an idea for a function that could take these inputs and transform them into digitalWrite outputs? I am using an Arduino Nano for this, with pins 2, 3, 4, 5, 6, 7, 8, 9, and 11 used for the columns with A0, A1, and A2 being the rows of the cube.

Well, learning bit manipulations and using three uint16_t (as 9 bits won't fit into uint8_t) to store state for a whole cube is much better. Then you hust have to setup timer ISR and each time it fires just display one "floor". The multiplexing can be done even in loop, but it's usualy flickering as you can't do almost perfect timing as in the ISR.
And for example, I was using two 2x4x4 segments to build up 4x4x4 cube and single MAX7219 to drive it, so I don't have to handle whole multiplexing and so.
My another aproach was using individually addressable LEDs like WS2812B, so I needed only one pin to drive it all. Or by using ARM and DMA transfers, I could drive 8 or 16 lines simultaneously.


text:
Using two input methods to control one motor shield (bluetooth and pushbuttons)
since an Arduino cannot run two programs simultaneously, I have been struggling a lot to get my project working - basically it is a motorized desk which is supposed to take input either from a BLE controller app or a pushbutton in order to move the linear actuators. However these inputs should work SIMULTANEOUSLY, I have failed to make both of them work together, after countless hours of prototyping, code provided below, please help me out.
    #include <AFMotor.h>

    AF_DCMotor motor1(1, MOTOR12_64KHZ);

    AF_DCMotor motor2(2, MOTOR12_64KHZ);

    int command;

    int forwardButton = A3;

    int backwardButton = A4;

    void setup() {

      Serial.begin(9600);

      pinMode(forwardButton, INPUT_PULLUP);

      pinMode(backwardButton,INPUT_PULLUP);

      motor1.setSpeed(255);

      motor2.setSpeed(255);

    }

    void forward(){

       motor1.run(FORWARD);

       motor2.run(FORWARD);
    }

    void backward(){

       motor1.run(BACKWARD);

       motor2.run(BACKWARD);
    }

    void stopMotor(){

       motor1.run(RELEASE);

       motor2.run(RELEASE);
    }

    void loop() {

      if (Serial.available() > 0) {

        command = Serial.read();

        stopMotor();

        switch (command) {

          case 'a':
            forward();
            break;
          case 'c':
            backward();
            break;
          case 'e':
            forward();
            break;
          case 'g':
            backward();
            break;
          case 'b':
            forward();
            break;
          case 'd':
            backward();
            break;
          case 'f':
            forward();
            break;
          case 'h':
            backward();
            break;
        }

      }
        else {

          stopMotor();

      }

    while(digitalRead(forwardButton) == LOW)

    {

      forward();

    }

    while(digitalRead(backwardButton) == LOW)

    {

      backward();

    }

    if(digitalRead(backwardButton)== HIGH)

    {

      stopMotor();

    }

    if(digitalRead(forwardButton) == HIGH)

    {

      stopMotor();

    }

    }

you did not describe the problem ... all you said is that you failed, which does not really mean anyhing specific ... you also did not say how the system should work

read through your code in loop() one line at a time and make note of what it does ... keep in mind that loop() repeats several thousand times per second


text:
stray \342 in program
When I try to compile my code it says "stray '\342' in program
My code:
#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

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

  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop() {
  if (remote.decode(&result)) {
    val = result.value;
    if (val == 0xFFFFFFFF) {
      val = prev;
    }
    prev = val;
    detekceKlaves();

    remote.resume();
  }
}

void detekceKlaves() {

  switch (val, HEX) {

    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");

  }
}

Error code:
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

irTEST:43:20: error: stray '\342' in program

     case 0x807FB24D:

                    ^

irTEST:43:21: error: stray '\200' in program

     case 0x807FB24D:

                     ^

irTEST:43:22: error: stray '\254' in program

     case 0x807FB24D:

                      ^

irTEST:47:10: error: stray '\342' in program

     case 0x807FB04F:

          ^

irTEST:47:11: error: stray '\200' in program

     case 0x807FB04F:

           ^

irTEST:47:12: error: stray '\255' in program

     case 0x807FB04F:

            ^

irTEST:47:23: error: stray '\342' in program

     case 0x807FB04F:

                       ^

irTEST:47:24: error: stray '\200' in program

     case 0x807FB04F:

                        ^

irTEST:47:25: error: stray '\254' in program

     case 0x807FB04F:

                         ^

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino: In function 'void detekceKlaves()':

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:43:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB24D:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:47:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB04F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:51:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F18E7:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:55:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F906F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:59:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F9867:

     ^~~~

Multiple libraries were found for "IRremote2.h"
 Used: C:\Users\maxim\Documents\Arduino\libraries\IRremote2
exit status 1
stray '\342' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Please help

possible unprintable characters ... copy the code from your question above and try to compile it

As @jsotola said, copy the code.  First try cutting and pasting into a new file.  If that does not work, copy it by retyping it into a new file.   How did you get unprintable characters?  Probably the best way (also difficult for a new developer) would be to find and use an octal editor to find and remove the problematic characters.

use something like notepad++ for editing

If I copy your provided code in a vim-editor you can see some strange characters. <202c>
switch (val, HEX) {
  4
  5     case 0x807FB24D<202c>:
  6       Serial.println("Stisknuto PLAY");
  7       tone(2, fre);
  8       break;
  9     case <202d>0x807FB04F<202c>:

I've removed them for you:
#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

void setup()
{
  Serial.begin(9600);
  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop()
{
  if (remote.decode(&result))
  {
    val = result.value;
    if (val == 0xFFFFFFFF)
    {
      val = prev;
    }
    prev = val;
    detekceKlaves();
    remote.resume();
  }
}

void detekceKlaves()
{
  switch (val, HEX)
  {
    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");
  }
}

@ MaximMaximS, you copied the code from someplace with right-to-left text orientation like an arabic website ... the hex 202d is a unicode character that controls the direction of the text ... https://www.codetable.net/hex/202d

Thanks, but I didn't copy it. I wrote it.


text:
Problem with printing keypad input to the LCD in a while loop
this is my first post here, though I have been following this forum for a while (pun intended). I am trying to write a program for a machine that will drill holes in a metal rail, and cut the rail to the desired length. This is a home project, but I am starting to think that it is a bit much for the arduino. I hope I'm wrong.
Case 1 is used to enter the length of the rail. Case 2 is used to enter the number of big holes that need to be drilled in a rail, after that it goes to Case 3 where it should, for each hole, ask the user to enter the distance, that means that this part will be in a loop, with a condition that the counter is less or equal to the number of holes. When this is done it should go to Case 4. But the problem appears with Case 3. It seems that the loop (while loop) is creating some troubles. I've tried the program without the while loop ( so basically it only asks once to enter the distance) and it works. I think that maybe the part where I need to print the message "enter the value" and then print the keypad values creates some trouble with the while loop, maybe it slows it down.
I forgot to add, when I upload the program, and I start entering the values with a keypad, as soon as it goes to Case 3, the display prints a bunch of ones (the display fills up with 1s)
Could it be that this is too much for Arduino? Should i try to program it like a regular microcontroller, using arduino IDE but not using arduino commands? What do you think? Please ask if you need some clarification about the code. And thank you in advance.
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include<Encoder.h>
#include<Keypad.h>

//definisanje tastera za tastaturu
LiquidCrystal_I2C lcd1(0x27, 16, 2);
LiquidCrystal_I2C lcd2(0x23, 16, 2);
const byte ROWS=4;
const byte COLS=4;
char hexaKeys [ROWS][COLS]={
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {4, 5, 6, 7};
byte colPins[COLS] = {8, 9, 10, 11};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
Encoder myEnc(2,3);

unsigned long currentTime;
unsigned long previousTime2=0;
unsigned long previousTime3=0;
unsigned long previousTime4=0;
unsigned long previousTime5=0;
unsigned long oldTime=0;
int loopTime=5;
String niz1="";
String niz2="";
String niz3="";
String niz4="";
String niz5="";
int duzina;
int br_Vrupa, br_Mrupa;
int state=1;
int debounce=400;
int i=1;
int m=1;
int j,k,n;
int zad_vrV [30], zad_vrM [30];
int start_taster, previous_state; //button that signals the start
int encoder_reading;
int prev_vr;
int zbir;
int error=5;
bool testRange1=true;
bool testRange2=true;
bool testRange3=true;
int machine_start=14; //relay that moves the rail
int relay1=15;  //relay for big holes
int relay2=16;  //relay for small holes
int relay3=17;  //relay for cutting the rail
int dt=2000;

void setup(){
  lcd1.init();  //printing values from the encoder
  lcd2.init();  //printing values from the keypad
  lcd1.backlight();
  lcd2.backlight();
  pinMode(12,INPUT_PULLUP);
  pinMode(machine_start,OUTPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
}

void loop(){
  char keyin=customKeypad.getKey();
  lcd1.setCursor(0,0);
  lcd2.setCursor(0,0);
  currentTime=millis();
  switch (state) {
    case 1:
    lcd2.print("Uneti duzinu:");
    if(keyin){
      if(isDigit(keyin)){   //proverava da li je uneta vrednost neka cifra
      niz1 += (char)keyin;    //od unetih cifara kreira niz
      lcd2.clear();
      lcd2.setCursor(0,1);
      delay(10);
      lcd2.print(niz1);
      duzina=niz1.toInt();     //konvertuje dobijeni niz u broj (int)
      }
      else if (keyin=='#'){
      niz1.remove(0);
      duzina=niz1.toInt();
      lcd2.clear();
      delay(10);
      lcd2.print(duzina);
      }

      if(keyin=='A'){
        state=2;
        lcd2.clear();
        delay(10);
    }
  }
    break;

    case 2:

    lcd2.print("Uneti br V");  //enter the number of big holes
    if(keyin){
      if(isDigit(keyin)){
        niz2+=(char)keyin;
        lcd2.clear();
        delay(10);
        lcd2.setCursor(0,1);
        lcd2.print(niz2);
        br_Vrupa=niz2.toInt();
        }
      else if (keyin=='#'){
        niz2.remove(0);
        br_Vrupa=niz2.toInt();
        lcd2.clear();
        delay(10);
        lcd2.print(br_Vrupa);
    }

    if(keyin=='A'){
        state=3;
        lcd2.clear();
        delay(10);
      }
    }
    break;

    case 3: //this case is used to enter the length to the each big hole

    while(i<=br_Vrupa);{
      j=i-1;
      if(keyin){
        if(isDigit(keyin)){
         niz3+=(char)keyin;
         lcd2.print("enter length ");
         lcd2.print(i);
         delay(10);
         lcd2.print(niz3);
         zad_vrV[j]=niz3.toInt();
        }
        else if (keyin=='#'){
          niz3.remove(0);
          zad_vrV[j]=niz3.toInt();
          lcd2.clear();
          delay(10);
          lcd2.print(zad_vrV[j]);
        }
      }
       if(keyin=='A'){
         i++;
         }
      if(i==br_Vrupa){  //when counter i reaches the br_Vrupa value, switch to the next case
        state=4;
      }
    }

      break;

      case 4:
      lcd2.clear();
      delay(10);
      lcd2.print("Uneti br M"); //enter the number of small holes
      if(keyin){
        if(isDigit(keyin)){
        niz4+=(char)keyin;
        lcd2.clear();
        lcd2.setCursor(0,1);
        delay(10);
        lcd2.print(niz4);
        br_Mrupa=niz4.toInt();
        }
        else if (keyin=='#'){
        niz4.remove(0);
        br_Mrupa=niz4.toInt();
        lcd2.clear();
        delay(10);
        lcd2.print(br_Mrupa);
        }
       if(keyin=='A'){
        state=5;
        lcd2.clear();
        delay(10);
        }
       }
      break;

      case 5: //this case is used to enter the length to the each small hole
      lcd2.clear();
      delay(10);
      while(m <= br_Mrupa){
        lcd2.print("enter length ");
        lcd2.print(m);
        n=m-1;
        if(keyin){
          if(isDigit(keyin)){
          niz5+=(char)keyin;
          lcd2.clear();
          lcd2.setCursor(0,1);
          delay(10);
          lcd2.print(niz5);
          zad_vrM[n]=niz5.toInt();
        }
        else if (keyin=='#'){
          niz5.remove(0);
          zad_vrM[n]=niz5.toInt();
          lcd2.clear();
          delay(10);
          lcd2.print(zad_vrM[n]);
        }

       if(keyin=='A'){
         m++;
        lcd2.clear();
        ;
         }
        }
      break;
  }

}
  start_taster=digitalRead(12);
  if(start_taster==LOW && previous_state==HIGH && currentTime-previousTime2 > debounce){
    previousTime2=currentTime;
    digitalWrite(machine_start,HIGH);
  }
  previous_state=start_taster;
  encoder_reading=(myEnc.read())*446/400;
  if(encoder_reading!=prev_vr){
    lcd1.clear();
    delay(10);
    prev_vr=encoder_reading;
  }
  lcd1.print(encoder_reading);

  zbir=br_Vrupa+br_Mrupa;
  for(k=0;k<zbir;k++){
    if(encoder_reading>=zad_vrV[k] && encoder_reading<zad_vrM[k]-tolerance && encoder_reading>zad_vrM[k]+tolerance && testRange1){
      digitalWrite(machine_start,LOW);
      digitalWrite(relay1,HIGH);
      previousTime3=currentTime;
      testRange1=false;
      if(currentTime-previousTime3 >= dt){
        previousTime3=currentTime;
        digitalWrite(relay1,LOW);
        digitalWrite(machine_start,HIGH);
      }
      if(encoder_reading<(zad_vrV[k]-error) || encoder_reading>=(zad_vrV[k]+error)){
        testRange1=true;
      }
    }
    else if(encoder_reading>=zad_vrM[k] && encoder_reading<zad_vrV[k]-tolerance && encoder_reading>zad_vrV[k]+tolerance && testRange2){
      digitalWrite(machine_start,LOW);
      digitalWrite(relay2,HIGH);
      previousTime4=currentTime;
      testRange2=false;
      if(currentTime-previousTime4 >= dt){
        previousTime4=currentTime;
        digitalWrite(relay2,LOW);
        digitalWrite(machine_start,HIGH);
      }
      if(encoder_reading<(zad_vrM[k]-error) || encoder_reading>=(zad_vrM[k]+error)){
        testRange2=true;
      }
    }
  }
  if(encoder_reading>=duzina && testRange3){
    digitalWrite(relay3,HIGH);
    previousTime5=currentTime;
    testRange3=false;
    if(currentTime-previousTime5>=dt){
      previousTime5=currentTime;
      digitalWrite(relay3,LOW);
    }
    if(encoder_reading<(duzina-error)){
      testRange3=true;
    }
  }
}

you don't read the keyboard in the while loop in case 3. no it is not too much for Arduino. (it is nothing compared to what it can)

I'm not sure what you meant. I thought that this part reads the keypad:
if(keyin){
if(isDigit(keyin)){
niz3+=(char)keyin;

while(i<=br_Vrupa);{ probably there is a misplaced semicolon (;) If i<=br_Vrupa the while loop is never exited an the block below is newer executed.

You are right, I've corrected that, but it still doesn't work. Now, when it enters Case3 it just keeps displaying "enter the length enter the length enter the length " over and over

customKeypad.getKey() reads the key


text:
Getting maxretry error when trying to ping using python requests or urllib3
I have written this code working on SimpleHost example from ESP8266Ping library,
the code works,
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>

#define HTTP_REST_PORT 80

const char* ssid     = "usernaem";
const char* password = "password";

const char* remote_host = "10.10.10.12";

ESP8266WebServer http_rest_server(HTTP_REST_PORT);

void get_online_status() {
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& jsonObj = jsonBuffer.createObject();
  char JSONmessageBuffer[200];

  Serial.print("Pinging host ");
  Serial.println(remote_host);

  if(Ping.ping(remote_host)) {
    Serial.println("Success!!");
    jsonObj["roku_express"] = 1;
  } else {
    Serial.println("Error :-(");
    jsonObj["roku_express"] = 0;
  }
  jsonObj.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  http_rest_server.send(200, "application/json", JSONmessageBuffer);
}

void config_rest_server_routing() {
    http_rest_server.on("/", HTTP_GET, []() {
        http_rest_server.send(200, "text/html",
            "Welcome to the ESP8266 REST Web Server");
    });
    http_rest_server.on("/ping", HTTP_GET, get_online_status);
}

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

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println("Connecting to WiFi");

  WiFi.begin(ssid, password);

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

  Serial.println();
  Serial.print("WiFi connected with ip ");
  Serial.println(WiFi.localIP());
  config_rest_server_routing();
  http_rest_server.begin();
  get_online_status();
}

void loop(void) {
  http_rest_server.handleClient();
  }

if I try to access my wemos D1 Mini from web browser I get correct message :
if offline
{
  "roku_express": 0
}

if online
{
  "roku_express": 1
}

but if I try to get the REST URL from python code either using requests or urllub3
import urllib3
http = urllib3.PoolManager()
url = "http://10.10.10.4/ping"
response = http.request('GET', url)

I get below error

MaxRetryError: HTTPConnectionPool(host='10.10.10.4', port=80): Max
  retries exceeded with url: /ping (Caused by
  NewConnectionError(': Failed to establish a new connection: [Errno -536870212]
  Unknown error: -536870212'))

Is the computer running the Python code on the same network as the ESP8266? What happens if you try to access the ESP8266 URL from a web browser?

like I said in the opening post, from web browser it worked.


text:
Dragino Lora shield for Arduino sensor use
I am new to arduino and lora technology and i have dragino lorashield for arduino Uno and dragino gateway. I have also MQ-3 gas sensor and I want to detect the alcohol value and to send it to the gateway using the lorashield after that the gateway should send the data to ThingSpeak platform.
Currently the code for my MQ-3 sensor is as below. I would like to ask you for some help as I dont know how to write the code for the dragino and to send it to the gateway. Thanks in advance!

void setup() {
 Serial.begin(9600);
}
void loop() {
 float sensor_volt;
 float RS_gas; // Get value of RS in a GAS
 float ratio; // Get ratio RS_GAS/RS_air
 int sensorValue = analogRead(A0);
 sensor_volt=(float)sensorValue/1024*5.0;
 RS_gas = (5.0-sensor_volt)/sensor_volt; // omit *RL
 /*-Replace the name "R0" with the value of R0 in the demo of First
Test -*/
 ratio = RS_gas/0.01; // ratio = RS/R0
 /*-------------------------------------------------------------------
----*/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 delay(1000);
}

The code is working fine when I am using only the arduino. How do I modify it to use lora and to send the data to the gateway?

start with any example sketches that you can find

please format your code ... put ``` (three backticks) on a blank line before the code and same after the code


text:
Arduino stops sending/receiving data over Serialport after random time
I got a C# WPF application wich communcates with my arduino uno over serial port. Everything works fine for 3 to 20 seconds then i can not send or receive anything from/to the arduino.
What im trying to archieve:
 Connected a arduino uno to an optical sensor of a mouse to read from its registers, now i want to process the data on my pc.
I tried using another arduino uno and also some other mouse optical sensor, wich did not change anything.
Opening and closing the serialport after each communication did not work for me.
I have seen a few questions here on stack exchange, i looked through everyone but they could not help me.
 Serial.flush() seems to be not working, or its some kind of overflow i cant figure out.
I would really appreciate it if someone could explain me what the root of this problem is.
For completeness, here is my C# code:
 public class SerialCommunication
    {
        public SerialPort serialPort = new SerialPort();

        public SerialCommunication()
        {
            string[] ports = SerialPort.GetPortNames();
            if (ports.Count() == 1)
            {
                MessageBox.Show("No serialport is available");
                return;
            }
            serialPort.PortName = ports[1];
            serialPort.BaudRate = 115200;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.Handshake = Handshake.None;
            serialPort.StopBits = StopBits.One;
            serialPort.NewLine = "\r\n";
            serialPort.WriteTimeout = 2000;
            serialPort.ReadTimeout = -1;

            serialPort.Open();
        }
    }

public partial class MainWindow : Window
    {
        public static readonly object _lock = new object();

        private SerialCommunication serialCommunication = new SerialCommunication();

        public MainWindow()
        {
            InitializeComponent();
            GetWindow(this).KeyDown += HandelKeyDown;

            serialCommunication.serialPort.DataReceived += (sender, args) =>
            {
                string bufferstring = ((SerialPort)sender).ReadLine();
                OnMessageReceived(bufferstring);
                //serialCommunication.serialPort.DiscardOutBuffer();
                //serialCommunication.serialPort.DiscardInBuffer();
                //Thread.Sleep(3);
                //byte[] buffer = new byte[15];
                //((SerialPort)sender).Read(buffer, 0, buffer.Length);
                //string bufferstring = Encoding.UTF8.GetString(buffer);
            };
            serialCommunication.serialPort.WriteLine("OK");
        }

        private void OnMessageReceived(string message)
        {
            if (message.Length != 15 || message.Contains('O') || message.Contains('K') || message.Contains('\n') || message.Contains('\r'))
            {
                serialCommunication.serialPort.DiscardInBuffer();
                serialCommunication.serialPort.DiscardOutBuffer();
                serialCommunication.serialPort.WriteLine("OK");
                return;
            }

            //Format: "y: 0x%02X,x: 0x%02X"
            string x = message.Substring(3, 4);
            string y = message.Substring(11, 4);

            int offsetX = (Convert.ToInt32(x, 16) - 128);
            int offsetY = (Convert.ToInt32(y, 16) - 128);

            // the next three lines only visualize the received data but do not change it
            MoveX(offsetX / 50);
            MoveY(offsetY / 50);
            ShowMessage(message);
            Thread.Sleep(2);
            serialCommunication.serialPort.WriteLine("OK");
        }
}

Foto of how the application and data it receives look like:

Here is my arduino code:
#include <Arduino.h>

// 5v
#define POWER 13
// Serial I/O
#define SDIO 11
// Serial clock
#define SCK 12

// Registers
#define DELTAY 0x02
#define DELTAX 0x03

#define serialInputBufferSize 16
char dataBuffer[serialInputBufferSize];
unsigned short inputBufferLength = 0;

bool sendPosition = true;

char tmp[16];

void InitMouse()
{
  digitalWrite(SCK, HIGH);
  delayMicroseconds(5);
  digitalWrite(SCK, LOW);
  delayMicroseconds(1);
  digitalWrite(SCK, HIGH);

  // Wait for the serial transaction timer to time out:
  delay(1000);
}

byte readRegister(byte addr)
{
  byte r = 0;

  // Set the dataline to output
  pinMode(SDIO, OUTPUT);
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(SCK, LOW);
    digitalWrite(SDIO, addr & (1 << i));
    digitalWrite(SCK, HIGH);
  }

  // Switch the dataline from output to input
  pinMode(SDIO, INPUT);
  // The datasheet mentions to wait at least 100 µsec
  // when switching from write to read operations.
  // This is needed for the chip to prepare the data
  delayMicroseconds(110);

  // Clock trough the register and read its data
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(SCK, LOW);
    digitalWrite(SCK, HIGH);
    r |= (digitalRead(SDIO) << i);
  }

  // Delay at the end guarantees >100 µsec before next transaction
  delayMicroseconds(110);

  return r;
}

byte y = 0;
byte x = 0;

void WaitForMovementThenSendPositionOffset()
{
  x = 0;
  y = 0;

  while (((y == 0 && x == 0) || x == NULL || y == NULL) && sendPosition)
  {
    delay(1); // kann eigentlich weg
    y = readRegister(DELTAY);
    x = readRegister(DELTAX);
  }

  if (sprintf(tmp, "y: 0x%02X,x: 0x%02X", y, x) > 0)
  {
    tmp[16] = 0;
    if (!Serial.println(tmp))
    {
      // Serial.end();
      // Serial.begin(9600);
      // Serial.begin(115200);
      Serial.flush();
    }

    sendPosition = false;
  }
}

void serialEvent()
{
  sendPosition = false;

  // Read serial data into the buffer
  while (Serial.available())
  {
    dataBuffer[inputBufferLength++] = Serial.read();
  }

  Serial.flush();

  if (strstr(dataBuffer, "OK"))
  {
    sendPosition = true;
    WaitForMovementThenSendPositionOffset();
  }
}

void setup()
{
  pinMode(SCK, OUTPUT);
  pinMode(SDIO, INPUT);
  pinMode(POWER, OUTPUT);

  digitalWrite(POWER, HIGH);

  Serial.setTimeout(1000);
  // Serial.begin(9600);
  Serial.begin(115200);

  InitMouse();
}

void loop()
{
}

what troubleshooting have you done?

@jsotola as mentioned above: I tried using another arduino uno and also some other mouse optical sensor, wich did not change anything. Opening and closing the serialport after each communication did not work for me. I have seen a few questions here on stack exchange, i looked through everyone but they could not help me.
I also tried around with delay() and other useless stuff for 2 days now

start with basics ... lower the baud rate ... use a simple Arduino sketch that sends repeatedly "ABC123" one character at a time with a short pause in between characters ... observe the result on the C# side of the connection

@jsotola i tried baudrate 9600 wich did not help, on the c# side i get the results i want. I will add a foto of how my wpf application looks like and the data it receives, but thank you

you need to modify the arduino sketch to the minium code that still exhibits the undesired behavior ... that is why i said to start by sending ABC123 and see if it still happens

@jsotola ok i try it with "ABC123"

The problem was in the serialEvent() method. I did not rest the bufferindex where i red the received message so it allways stayed there until the arduino ran out of memory and also i did not gave the arduino enough time to receive the message so i added delay(1) there.
Here is my updated code:
void serialEvent()
{
  inputBufferLength = 0;
  sendPosition = false;
  delay(1);
  // Read serial data into the buffer
  while (Serial.available())
  {
    if (inputBufferLength < serialInputBufferSize)
    {
      dataBuffer[inputBufferLength++] = Serial.read();
    }
    else
    {
      Serial.read();
    }
  }

  Serial.flush();

  if (strstr(dataBuffer, "OK"))
  {
    sendPosition = true;
    WaitForMovementThenSendPositionOffset();
  }
}

Every time you receives data, it tries to read a full line (SerialPort.ReadLine()).
If there's not a full line available, it will block the current thread until there is or until it times out.
These calls will stack up and eventually cause the application to fail.

If i restart the c# application, it still does not work. I have to restart the arduino, then it works again. I think problem is on the arduino side, but i give it a try and use a buffer with SerialPort.Read() instead.


text:
DC Motor Car Steering
I am working on a project with a 3-Wheel Car: 1 Custer Wheel, and 2 DC Motors. I need to steer the car playing with the speeds of these two dc motors. If I would supply a constant voltage and current to the DC motors, is there an equation or maybe a source to know the exact degree of turning by assigning PWM to a certain value? Let's say I want to turn the car 30 Degrees to the left from the straight direction. Can I do calculations to find all of the PWM values or it can only be got through experiments?
Thanks in Advance!

you cannot turn a motor a known amount without some kind of feedback

As my experience in RC robots as yours, you Can't, simply because the speed of the car rotating varies from a surface to another, on ceramic flat surface the robot will turn so fast,but on a carpet for example the robot will rotate slowly even the signals and the voltages were Similar.

As @jsotola said, you would need a feedback, that means a sensor which tells you the angle of your car in order to reach the angle you want, for example use a magnetometer like the HMC5883L

Basically you can't. PWM value required to turn to a specific degree will depend on motors, on voltage, on hardware, in the current velocity of the car and probably on the surface under the wheel. Also keep in mind that real cars don't turn like that (at a fixed angle). Instead, driver constantly adjusts the position of the steering wheel, while looking at the road (i.e.a feedback system). Same is for RC cars, operator smoothly deflects the joystick looking at the vehicle.


text:
RF24 library commands, channel, and address
I'm trying to use the RF24 library for wireless communication.
However, it appeared that this library does not have "help" option.
There was a keywords file but it did not explain what it does.
I found couple of examples online, and in the library, but id did not explain things quite in detail.
Could you explain to me how those command works, and weather there's any help file for the library?
Especially, I have a question about the channel and address used in the library.
A. Does address take character or number as input?
The official example in the library used
byte addresses[][6] = {"1Node","2Node"};

But I also say some example use
byte addresses[][6] = {"00001","00002"};

The byte command was suppose to be a 8-bit unsigned number, from 0 to 255, but why they used string " " as input?
I found a sentence in RF24.h file: Addresses are assigned via a byte array, default is 5 byte address lengths. But why they wrote byte addresses[][6] instead of byte addresses[][5]?
B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.
setChannel  KEYWORD2

The pin was explained in RF24.h. However,

Can one open multiple channel at once?
If one use the same addresses in multiple channel at once, can the address being distinguished, or were they treated as the same address?
Is channel-pin/port(while writing)-address a tree structure?

C.
Can one open up more pin/port in transmitting and writing?
  openWritingPipe   KEYWORD2
  openReadingPipe   KEYWORD2

there is a link on the page you linked. http://tmrh20.github.io/RF24

I'd suggest reading the datasheet. It's quite well written. Don't worry if you don't understand everything; just keep reading. That should give you a good idea of what this module does, and how it sort of works.

A. Does address take character or number as input?

The address is 5 bytes. In this library it is provided as an array. In C a string is merely an array of bytes. So it is possible to represent an array of bytes as a simple string. Internally the two representations:
byte address[] = "123ab";

and
byte address[] = { '1', '2', '3', 'a', 'b' };

and even:
byte address[] = { 0x49, 0x50, 0x51, 0x97, 0x98 };

are all identical, except that the first one adds an extra 0x00 to the end of it to mark the end of the string (which the library completely ignores).

B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

It's helpful here that you have some understanding of basic radio communication terminology.
When you say that a device works at X frequency you are generally only referring to the "frequency band" that the device operates within (2.4GHz in this case). The device doesn't work at 2.4GHz - only "in the 2.4GHz band". That frequency band is then divided up into channels. Each channel is a specific frequency. Just like your television has channels you select one specific channel (and thus frequency) to tune into and communicate on.
Channel numbers are just used because it's far far easier to remember "channel 21" instead of 471.25MHz, for example.
For two devices to be able to communicate they both need to be tuned to the same frequency, and hence the same channel.
The "address" is more like the address your computer has on the network. Within the channel frequency you can have multiple devices communicating. The address identifies exactly which of the devices you want to send data to or are receiving data from.

C. Can one open up more pin/port in transmitting and writing?

The nRF24L01 internally uses pipes as a method of separating data from different devices into distinct feeds that you can read from. It is merely for convenience. You can open up to 6 pipes at once, each one receiving from a different address. All pipes are in the same channel though since you can only tune to one channel at a time.
By the way - the keywords.txt file exists solely for the IDE to do highlighting of certain words. It's not meant for a human to read when working out how to use a library.


text:
Is there some hardware that can be used to upload sketch source code via USB flash disk (Automatically By plugging it in)
Well am asking this basically to know if it is possible to create a bootable flash drive that automatically uploads any source code onto the arduino just like creating a bootable flash drive when installing windows operating system on a computer. I will be happy to get some cool responses that would be helpful thanks.

There is a solution with SD card and SD bootloader. You put a bin file on SD card, insert it into the SD adapter and power up the Arduino. The bootloader loads the bin file to flash memory.
I use 'avr_boot' SD bootloader by Zevero. It reads a file named firmware.bin from SD card if present and loads it into flash.
To generate a bin file for Arduino AVR boards add to platform.txt
recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" -O binary {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"

I use this with the ArduinoOTA library which uploads the bin file from IDE to the SD card over network and then resets the MCU for the bootloader to apply the bin.
btw: the ArduinoOTA library can use the upper half of the flash memory too to store the uploaded bin and then activate a modified Optiboot to copy the bin to run location and reset the MCU.
UPDATE 2022: new advanced example for my ArduinoOTA library: load hex from SD card

Could you please provide a link were i could get more information about how it can be done with ease or if possible please

@Sigma, sorry, I forgot to link the Zevero bootloader. fixed. the link is in answer.

There is no specific piece of hardware that does what you ask.
There are various options though:

Write a new bootloader that uses the USB Host Shield to load data from a USB MSD device then flash it to the internal flash of the MCU (hard to do if you don't know low-level programming)
Use an embedded Linux computer (Raspberry Pi, etc) to run avrdude and flash your Arduino like it's a connected to a computer
Use an Arduino that has a Linux portion to it (such as the venerable Arduino Yun) or a shield that provides a similar function (Dragino Yun Shield) to flash the AVR chip from Linux
Don't use an Arduino at all, but use an embedded Linux computer for everything.

Thanks for the comment though it really seems tough to me its like I have a lot of reading and practice that I have to do. Isn't there any easier way that can by pass Linux some how?

Not without writing lots of software and learning how the USB host shield works, how flashing the chip works, and other such low-level functionality.


text:
How can I upload a sketch remotely from a distant location onto an arduino that is power by a battery
Of course after developing a success full embedded product the next step would be making upgrades to compete favorably with new products in the market. Well making upgrades would require making adjustments in the sketch and Uploading it onto already made prototypes to cub the costs involved in by the hardware of a remotely located prototype. How can one upload a sketch from his location on to the prototype without going there psychically to upload through the port?

Battery powered devices need a system where the device checks over Internet connection (WiFi, mobile) if a new firmware bin file is available on a specific location on a server. If the bin file is available the device can download it and apply.
One option how to apply the new bin is to use SD card and SD bootloader (Zevero avr_boot) The sketch saves the downloaded file on SD card and resets the MCU. The SD bootloader then loads the binary from the SD card to flash.
Other option if enough free flash memory is available is to use the InternalStorage object from ArduinoOTA library. It uses the upper half of the flash memory to store the uploaded bin and then activates a modified Optiboot to copy the bin to run location and reset the MCU.

I  have options i think all i have to do is do some reading and seek out examples then i could do what ever i want to do. Thanks once again Im grateful for the information let me look out for the examples then I am sure I will be good to go then

First you have to establish communication between Arduino and your computer. This communication could be wire (ex. LAN) or wireless.
Like Juraj said, you could use ArduinoOTA with an additional WiFi or Ethernet module on your Arduino, as long as arduino is connected to the network and you know its address. I haven't tried it yet, so I don't know its reliability. Even so, it helps your problem

so why do you write an answer if you didn't test it?

I do not really know but its as if a few people or none have tried it. I really cannot afford wasting my money on unneccessary hardware if its not really worth a try. I wish i could get a clear highlight or possibility on how it would be done

@Sigma, the library has 38 stars  on GitHub in 1 year of existence even it is downloadable from Library Manager so most users don't have to go to GitHub. there are a few arduino forum threads where people ask for assistance to make it work and all were successful. right now here https://forum.arduino.cc/index.php?topic=629780.msg4421977#msg4421977

@Juraj This is helpful I am going to give it a shot


text:
Press On Hold Off Power Switch
Hi everyone I am hoping someone here can help me.
I am trying to make an arduino turn my project on and off.Using a relay.
I am looking for it to act like a computer power button.
A short press to turn on and them stay on and a long press (say 5 sec) to turn off and then stay off till button is pressed again.
I would like it so that the project can not be accidentally turned off
Can anyone please help.
Thanks

What have you tried so far, and what part is giving you difficulty? If you need a hint to get started, you code will need to store the relay state (on/off), measure the time of  each button-press, and compare the time to the length of a short-press or long-press, depending on the current state.

Hi JRobert after spending the best part of 2 days looking around the web. Reading posts looking at you tube videos. I cant find an example to do this. The Arduino IDE as a button on, off, example in it. But I need a long press to turn off. To prevent accidental power off. Basically I want a pin to go high on a short press. and only go low if it sees a long press of say 5 secs. So if the button is pressed accidentally it will do nothing unless the press is long.

Here is a test sketch that I wrote for a different question. The other question's requirement was for a short press (minimum 100ms) to turn on an LED, and a long press (1 second) would turn it off. With a slight modification of this sketch, it may work for you. You will need to install the Bounce2 library.

// Press and hold button for 100 ms to turn LED ON.
// Press and hold button for 1000 ms to turn LED OFF.
#include <Bounce2.h>

byte buttonState = 0;
const byte ledPin = 3;
const byte buttonPin = 2;
const unsigned long debouncerInterval = 50;
unsigned long buttonPressedTime = 0;
unsigned long currentMillis = 0;

Bounce debouncer = Bounce();

void setup(){
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  debouncer.attach(buttonPin, INPUT_PULLUP);
  debouncer.interval(debouncerInterval);
}

void loop(){

  // Get the current time.
  currentMillis = millis();

  // Check if button was pressed or released.
  if(debouncer.update()){

    // Pressed.
    if(debouncer.read() == 0){
      if(buttonState == 0){
        buttonState = 1;
        buttonPressedTime = currentMillis;
      }
    }

    // Released.
    else{
      buttonState = 0;
    }
  }

  // Turn the LED ON or OFF.
  if(buttonState == 1){
    if(currentMillis - buttonPressedTime >= 1000){
      digitalWrite(ledPin, LOW);
      buttonState = 0;
    }
    else if(currentMillis - buttonPressedTime >= 100){
      digitalWrite(ledPin, HIGH);
    }
  }
}

Thank you so much for your help it works great. I just changed the buttonPreeedTime from 1000 to 5000 and it dose everything I wanted... Thank you so much

To clarify the problem, do you want to control ON OFF using Arduino? It is very simple. Please read this simple tutorial, and modify it according to your needs.

This is not what @David Boswell is trying to do. A short button press turns on the relay, and the user must press and hold the button down for 5 seconds to turn the relay off. The button in the link of the tutorial turns the relay on, then automatically turns the relay off after 5 seconds has elapsed.

@VE7JRO yes of course with small modification. jees.

You hit the nail on the head..VE7JRO. that is what i need to do. Press and hold to turn off


text:
Dim 4k LCD panel in response to ambient light
Warning: I'm completely new to Arduino, and not even sure if it's the right solution here.
I'm trying to make a better digital picture frame. Got almost all the way there by just buying a nice flat-bezel 4k display, connecting a chromecast, and putting a picture frame on it. Voila!
But I want it to adjust its brightness in response to ambient light -- and turn itself off when the room is dark. So now I need something to check a light sensor and control screen brightness.
Is it possible (and does it make sense) to disassemble the monitor, wire up the LCD panel to a controller with arduino, add in a light sensor, and try to tackle it that way? Is there a better way?
Would greatly appreciate any recommendations / suggestions / ideas.
Thanks!

maybe the display already has an auto-brightness function

check if the display allows lan remote control

Does the display have any button or such for controlling the brightness?

Well,you might need to provide an image or specs of this LCD, but assuming the worst case that it's just a basic LCD screen you will need to disassemble it and you will make a lot of things and It may be hard for you, as you said that you are completely new to Arduino.


text:
How to create an array from serial.read?
I'm working on a audio-reactive lightinstallation with 16 LED lights.
In Max MSP I analyse my audio and split the frequencies in 16 'parts'.
I store these parts in a message of 16 ints, either 1 or 0 (on of off).
Every time a new frequency is detected the message updates and puts out a new int from 16 numbers (for exampe 1000100100110101).
I receive this number in my serial monitor of my Arduino Uno.
I want to put this 'incomingValues' in an array so I can check if a number/frequency is 0 or 1. When it's 1 I can turn on my relay/ light.
The 'incomingValues' is changing quite quickly but that shouldn't be a problem right?
I tried multiple things to create an array and update this every time a new serial message is coming in but I'm not used to work with Arduino so I could need some help.
Thanks! :)
Here is my code:
int counter;
int incomingValues = 0;
int lights[16];

void setup() {
  Serial.begin(9600);
  counter = 0;
  pinMode(13, OUTPUT);
}

void loop() {

  boolean newValue = false;

  while (Serial.available() > 0) {

    incomingValues = Serial.read();
    Serial.print(incomingValues);
    counter = counter + 1;

    newValue = true;
  }

  if (newValue) {
//    delay(50);
//    lights[counter] = incomingValues;
//
//
//    Serial.print(lights[0]);
//
//    for (int i = 0 ; i < 16 ; i ++) {
//      Serial.print(lights[i]);
//    }
//    Serial.println("");
//    newValue = false;
  }

  if (counter > 15) {
    counter = 0;
    Serial.print("\n");
  }

  if (incomingValues == 1) {
    digitalWrite(13, HIGH);
  } else if (incomingValues == 0) {
    digitalWrite(13, LOW);
  }
}

so, what is the problem?

You already save the data in the lights array (if you uncomment the newvalue if statement). Where exactly do you need help? What doesn't work as how you indended and what does it actally does?

If you are able to send the message as 16 chars, followed by a newline, then here is a test sketch that might work for you. Use the Serial Monitor to send the 1000100100110101 data. Please ensure you have the Serial Monitor set to send a Newline Only.

// Valid input data from serial is 16 chars followed by a newline.
// 1000100100110101
const byte bufferSize = 17;
char inputBuffer[bufferSize + 1];

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

void loop(){

  if(Serial.available() > 0){
    byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    if(bytesRead == 16){
      for(byte i = 0; i < 16; i++){
        if(inputBuffer[i] == '1'){
          Serial.print("on ");
        }
        else{
          Serial.print("off ");
        }
      }
      Serial.println();
    }
    else{
      Serial.println("Invalid data length.");
    }
  }
}

Thanks @VE7JRO, it does the job :)
const byte bufferSize = 16;
char inputBuffer[bufferSize + 1];
int myDelay = 20;

void setup(){
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);

}

void loop(){

  if(Serial.available() > 0){
    byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    if(bytesRead == 16){
      for(byte i = 0; i < 16; i++){
        if(inputBuffer[0] == 1){
          digitalWrite(13, HIGH);
          delay(myDelay);
        }
        else{
          digitalWrite(13, LOW);
        }
        if(inputBuffer[1] == 1){
          digitalWrite(12, HIGH);
          delay(myDelay);
        }
        else{
          digitalWrite(12, LOW);
        }
      }
      Serial.println();
    }
    else{
      Serial.println("Invalid data length.");
    }
  }
}


text:
L298N Motor Driver - Code issuing "expected primary-expression before '=' token"
Programming Questions / L298N Driver - Code Issuing - " expected primary-expression before '=' token"
Today at 07:20 pm
Hello Arduino Community,
Code is shown at bottom - please read below
I've been working on a little project that uses the L298N Dual Motor Driver to run a single motor.
Using this link I set up my project (disregard Using the L298N with PIC Section) :
https://www.teachmemicro.com/use-l298n-motor-driver/.

I connected my wires and checked them and their connections for any problems.
I am using 1 motor instead of two
I am using two 'C' Duracell Alkaline Batteries, connected them together in a series circuit. I've tested the batteries and they run my Small Round Electric Motor with 12000 RPM + 3 to 6V DC perfectly when I don't connect the battery and motor to the L298N Driver.
The two, 'C' batteries are 1.5 volts each (connecting them together in series give me 3 volts)
I am connecting my arduino uno to a newly purchase laptop - I've compiled codes from this computer that have worked fine.

I copied and pasted the code from the website at the link at the top. I checked device manager and chose the correct port with the correct board, so I am starting to believe there is something wrong with the code on the website.
Once I compile the program, errors pop up stating, "expected primary-expression before '=' token" for every line of code that has a #defined variable (mentioned on the top lines of the program).
It would be helpful to please comment your thoughts and solutions for this issue.
Please see link at the top for code.
Thank you.

when a sketch fails to compile, it has nothing to do with the hardware itself ... you only need to select the correct board before compiling, but it does not need to be connected for the sketch to compile ... connection to the board is only necessary during the upload phase after compilation is successful ...  that means that all of the information that you included about batteries and motors is irrelevant to your question

Definitions via #define don't use equal signs. The following is wrong
#define EN = 1

Instead it should be
#define EN 1


text:
Attiny85 simple analog and digital output problem
I'm just lighting up an LED through a TIP31C, pin 0 goes through a 560kohm resistor to the tip's input pin
pin 1 goes through a 750 ohm resistor to the tip's input pin
^i'm not sure this information is really relevant
The reason I am doing this is so i can sleep the attiny85 while having pin 0 set to HIGH to have the led at a very low brightness, kind of like a standby function
void setup() {

}

void loop() {
  digitalWrite(0, HIGH);//works ONLY the first time
  delay(500);
  digitalWrite(0, LOW);
  delay(500);

  analogWrite(1, 15);//always works
  delay(500);
  analogWrite(1, 0);
  delay(500);
  /*it's like as soon as i've used an analogWrite, i can no
    longer output with digitalWrite
  */

  //pinMode(0, OUTPUT);//didn't help
  digitalWrite(0, HIGH);//never works
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

is there a problem of some kind?

@jsotola yes, I've put comments in the code explaining it

Try doing the pinMode in setup method. This is where it's supposed to be.

@FilipFranik I've tried that, it still doesn't work

There are a number of issues here:

You state you have a 560kohm resistor, this is too high a value. With 5V it will restrict the current to 8.9uA.

This is too low to drive the LED, which probably requires up to 20mA (5V / 0.02A = 250Ohm at least)
This is also too low for for the base of the transistor (I'm not completely sure if my understanding of transistor gain is correct, but I think if you feed 1mA into the base of the TIP31C, it's gain of 25 will allow upto 25mA between the collector and emitter.) Based on this, 5V / 0.001A = 5kOhm.

You do need pinMode(0, OUTPUT); and pinMode(A1, OUTPUT); in setup. It will work, except you won't notice the effect with your 560kOhm resistor.
You also need to check the pins of the atTiny85.

As you can see, the only analog outputs are on physical pins 2, 3 and 7. You need to refer to these (for connection to pin 7) as:
pinMode(A1, OUTPUT);
analogWrite(A1, 15);

Below is a rough idea of what the schematic should look like

simulate this circuit – Schematic created using CircuitLab
And below is an (untested) example of the code:
void setup() {
  pinMode(A1, OUTPUT);
}

void loop() {
  analogWrite(A1, 15);
  delay(500);
  analogWrite(A1, 0);
  delay(500);
}

I think you confused the "analog output" (actually the Attiny85 does not have a real analog output, meaning DAC, Digital to Analog Converter. It can only output PWM voltages to mimick analog signals) with the pins of the ADC (Analog Digital Converter), which is basically an analog input.


text:
MPU6050 - Why is my gyro integration incorrect?
My situation:

I am able to communicate over i2c with my MPU6050 IMU
I can get accelerometer and gyro data
I can compute the sensor's orientation using my accelerometer

Issue:

when trying to compute the sensor's orientation using my gyroscope my values seem to be totally incorrect. I am computing the orientation using a complementary filter.

This is the code I use https://paste.ubuntu.com/p/vZmbnc23gj/
This is the computed orientation, when the sensor is lying on a table: https:https://paste.ubuntu.com/p/W7DzVKR9c7/
Those measurements are totally incorrect, because when moving the senor randomly around its axis it never goes above 1.8. (even when I do an 180 degree turn)
Could somebody give me some hints or explanation on why my results are incorrect and drifting so much?

Could you post a schematic of your connections? I understand you can communicate with it, but am interested in what you have.

@Wendall connection, are just typical "i2c connection" without pull ups

You need to perform offset calibration, otherwise you'll get large drift errors. The MPU6050 has a dedicated Digital Motion Processor (DMP) where data from the gyro and accelerometer are fused for you. I recommend grabbing the results of that fusion from the DMP. As far as I know the only libraries that do this are ones based on Jeff Rowberg's work. For a detailed guide please see:
https://youtu.be/k5i-vE5rZR0