/r/arduino

Photograph via snooOG

An unofficial place for all things Arduino!

We all learned this stuff from some kind stranger on the internet. Bring us your Arduino questions or help answer something you might know! 😉

/r/arduino

690,432 Subscribers

1

Advice - Part 2

Here is the original post with the project details: https://www.reddit.com/r/arduino/comments/1iaxhep/advice/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button

I was advised to power the 10 RFID modules separately, so I designed an external power circuit for the Arduino Mega and the 10 RFID sensors.

https://preview.redd.it/8gpwf5vog0he1.png?width=1453&format=png&auto=webp&s=3c0eb587d07277ce4b06bb410a51df1a268ff7e9

I am a mechanical engineer, so my circuitry knowledge is very basic. Here is my reasoning:
- The sensors I purchased ( https://www.aliexpress.com/item/1005008180012512.html?spm=a2g0o.order_list.order_list_main.5.21ef1802Sw6ZFy ) are rated to run at 3.3V at 20mA so I calculated their equivalent resistances to be R = V/I = 3.3V/0.02mA = 165 Ohms. I elected to set them up in parallel.

- For the Arduino Mega I considered the top answer from this forum ( https://arduino.stackexchange.com/questions/35619/how-much-current-does-an-arduino-mega-draw-from-a-lipo-battery-5-000-mah ) to calculate its equivalent resistance as R = 7V/0.07mA = 100 Ohms.

I then selected R1 and R2 to be 15 and 22 Ohms respectively so that the Arduino receives 7.794V at 77.94mA, and each of the RFID sensors receives 3.34V at 20.24mA.

The power supply then is found to require 12V at 280mA**.**

So my question now is:

1. Is this circuit correct?

2. Are the selected R1 and R2 appropriate? Would they burn under that load in a real-world case?

3. The Arduino Mega is said to draw more power if peripherals are connected from that same link I shared earlier. I only really intend to connect simple 4 LEDs, so I decided to ignore the peripheral loading. Can I consider this extra load negligible?

4. The required power supply is 12V and 280mA. Does this mean I have to supply exactly this amount, or should I be within that ballpark +- some mA? I don't expect to find an exact transformer for this. What I am wondering is if I should give it a current buffer of ~+-... idk.. 20mA? to account for... idk, something?

I fear I may have to delve into opamps to protect the electronics. please PLEASE PLEASE tell me I can avoid revisiting that bullshit.........

0 Comments
2025/02/04
00:11 UTC

1

LCD 1602(no L2C "extension") for micro-bit!!

I know this is arduino reddit but nobody could help me in microbit reddit so I came here.

I am trying to connect a LCD 1602 to my microbit. I found a scheme for it but it is for arduino, I have followed that scheme and connected it like that to my microbit but the LCD display seems to not properly work because it turns on, connects to my microbit but doesn't show any output when I code it to. Also its connected to 5V, I don't think that should be a problem.

Could anyone help me fix this somehow or tell me what problems could be causing this.
Here is a link to a youtube video I watched and the scheme: https://cdn.shopify.com/s/files/1/1509/1638/files/HD44780_1602_Blaues_LCD_Display_Datenblatt_AZ-Delivery_Vertriebs_GmbH_6b261ba0-ce77-4bbd-82a7-a9c3c417c348.pdf?v=1606233091 ; https://www.youtube.com/watch?v=_2nQCynm28s

0 Comments
2025/02/04
00:04 UTC

0

About to go insane with TSOP38238 IR receiver. Random infinite outputs or no outputs at all

https://preview.redd.it/platv8l0f0he1.jpg?width=1434&format=pjpg&auto=webp&s=faabe5d20f51029ab6c6e143bc6999a6ad012e22

I have never touched an arduino in the past, and I don't discard the possibility being braindead, but everything online suggests this should be pretty simple.

I have looked at code from here, here, and ChatGPT. Other than the image, I have tried other ways (more or less direct) to connect OUT, GND and Vs from the TSOP38238 always paying attention to not put anything in the wrong pins. Before trying to get code working I tested the IR receiver OUT with an LED, based on this guide and it worked as intended.

https://reddit.com/link/1ih44lr/video/gr29fzing0he1/player

When I use the ReceiveDump.ino example, from IRreceiver I get inifinite prints in this format, always repreating only alternating between sum 8200 and 8250:

Protocol=UNKNOWN Hash=0x0 1 bits (incl. gap and start) received

rawData[2]:

-11750

+8250

Sum: 8250

Protocol=UNKNOWN Hash=0x0 1 bits (incl. gap and start) received

rawData[2]:

-11750

+8200

Sum: 8200

Protocol=UNKNOWN Hash=0x0 1 bits (incl. gap and start) received

rawData[2]:

-11750

+8200

Sum: 8200

I have also tried printing this:

void setup() {     pinMode(2, INPUT);  // Change to pin 3     Serial.begin(9600); }  void loop() {     Serial.println(digitalRead(2));     delay(100); } void setup() {     pinMode(2, INPUT);  // Change to pin 3     Serial.begin(9600); }   void loop() {     Serial.println(digitalRead(2));     delay(100); }

but get only infinite 0s or infinite 1s... sometimes they alternate, but always unrelated to button presses on my remote. I just want to figure out the codes for each button so I can then make a script where the IR inputs are transformed into keyboard key presses.

From the materials online I thought this would take 10 minutes, but I lost an entire day on this because it seems that everyone that tried this it simply just worked.

3 Comments
2025/02/03
23:59 UTC

1

Im a complete beginner - Help Needed

I've been interested in arduinos and electronics for awhile and toying with the idea of getting a beginner kit or something of the sorts, I'm in high school studying Cs and have decent knowledge in Python what's a good cost effective piece of gear that I can get to start making cool stuff.
Any tips or tricks appreciated 🙏

1 Comment
2025/02/03
22:57 UTC

1

esp32 board with l298n motor driver

have anyone tried to controle the l298n driver with an esp32 board because there might be problems with the esp32 board as it deliveres 3.3V max and the driver operates on 5V logic levels I thing this might cause the esp32 to reboot occasionally and cause power issue in the board

1 Comment
2025/02/03
20:28 UTC

0

Help With Alarm System.

Hello there!

I have been working on making an alarm system with Arduino following this project: https://howtomechatronics.com/projects/arduino-security-alarm-system-project/ However, I wanted to add a delay after the alarm gets triggered so I can disarm it. To do this, I have removed tone(buzzer, 1000) from the block of code where the alarm gets triggered and replaced the enterPasswordfunction with this:

void enterPassword() {
  int k=5;
  int count = 9;
  tempPassword = "";
  activated = true;
  lcd.setCursor(0,0);
  lcd.print("ALARM ACTIVATED!");
  lcd.setCursor(0,1);
  lcd.print("Pass>");

  while(count > 0) {
lcd.setCursor(0,0);
lcd.print("Alarm in: ");
lcd.setCursor(11,0);
lcd.print(count);
tone(buzzer, 700, 100);
count--;
delay(1000);
  };

  lcd.setCursor(0,0);
  lcd.print("ALARM ACTIVATED!");
  //tone(buzzer, 2000);

  while(activated == true) {
keypressed = myKeypad.getKey();
if (keypressed != NO_KEY){
if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
keypressed == '8' || keypressed == '9' ) {
tempPassword += keypressed;
lcd.setCursor(k,1);
lcd.print("*");
k++;
};
};

if (k > 9 || keypressed == '#') {
tempPassword = "";
k=5;
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" *** ALARM *** ");
lcd.setCursor(0,1);
lcd.print("Pass>");
};

if ( keypressed == '*') {
if ( tempPassword == password ) {
noTone(buzzer);
activated = false;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Alarm Dissarmed");
delay(2000);
lcd.clear();
alarmActivated = false;
screenOffMsg = 0;
} else if (tempPassword != password) {
lcd.setCursor(0,1);
lcd.print("Wrong! Try Again");
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("ALARM ACTIVATED!");
lcd.setCursor(0,1);
lcd.print("Pass>");
};
};
  };
};

The issue with that is you cannot enter the password until the delay finishes. This is because, obviously, you can't run two while loops at the same time. I just don't know how to redo it. I am very new to programing the Arduino (most of my experience is in webdev,) so there might be some simple solution I'm missing. Either way, any help would be much appreciated.

3 Comments
2025/02/03
21:44 UTC

1

from where to start?

yo i wanna strart with the robotics thing and i was wondering from where to start

1 Comment
2025/02/03
19:26 UTC

1

Arduino Nano resets when Servo motor SG90 activates

Hi all. I made an Arduino nano project with a few sensors, servo and an SD card logger. Sometimes, when the servo activates, the Arduino resets. Everything is powered by a 2S LiPo battery through a 5v buck regulator (mp1584). When the servo moves there's a sudden voltage drop across the servo and I think that is causing the reset. Now, placing a 100uF capacitor across the servo 5V/GND pins seems to solve the issue but I wanted to know someone else's opinion before soldering it permanently. Thank you.

2 Comments
2025/02/03
18:47 UTC

1

r307 sensor

hi! im having trouble dealing with the r307 sensor. what i need to do is:

  • connect the sensor to my computer
  • capture an image using it
  • saving that image onto my computer

ive tried using the arduino and ive tried just using a USB-TTL connector

i send the sensor the commands for capturing and sending the image to the upper computer but there are a lot of things i cant seem to understand

(ill attach a link to the r307 user manual here: https://www.openhacks.com/uploadsproductos/r307_fingerprint_module_user_manual.pdf)

i cant figure out how many raw data bytes i'm meant to receive and then convert into a BMP image.

help is very very much needed please,, im an undergrad student working on my graduation project and ive been stuck on this problem for over a month now 😭

1 Comment
2025/02/03
19:11 UTC

3

A possibly dumb question about programming motor control with a joystick

So, I'm programming a model vehicle with 2 motors attached to a rigid frame that each control one wheel. As I can't make the wheels actually turn, the turns need to be defined as a speed difference between the two. I've seen tutorials on how to program a joystick to control motors and did it successfully, the problem is that in all the resources I found while searching the program only lets you control the speed, go forwards, backwards and make a sharp turn to either side by turning off one motor. My question is, how would I go about programming the vehicle to make a more gradual turn ( less difference in speed between the two wheels) when the joystick is not moving along the x or y axis, but in diagonal? I'm very thankful for anyone who takes the time to answer my question, I'm a beginner in programming so I understand it may be obvious.

6 Comments
2025/02/03
21:54 UTC

19

BarcodeGFX: My first Arduino library

Hey, folks! A few months ago, I was looking for a library to draw barcodes on e-paper displays for my IoT course. Surprisingly, I found nothing! So I decided to create my own: BarcodeGFX. It works with any display library that inherits from Adafruit_GFX.

After a few adjustments, I’m officially releasing it for the general public. It is available on GitHub and in the Arduino Library.

I hope BarcodeGFX will be useful for other people as well. Let me know what you guys think about it!

4 Comments
2025/02/03
20:42 UTC

1

Trying to controll a lavet type stepper motor

Hi, I am for fun trying to cobtroll a lavet type stepper motor in a watch I found. I am new to arduino so probably not the easiest task to start with, but i thought it would be fun :) The motor is designed for a square wave 1.4V pulse. Is this possible?

Thanks!

0 Comments
2025/02/03
20:20 UTC

1

help with motors

I replaced the motors on my robot's wheels, i made no changes to the code, and replugged the new motors into the same pins as the old motors, but now the robot won't move? not sure if i'm just an idiot but i don't don't see how it's any different than before? if you need to see some pics lmk

8 Comments
2025/02/03
19:56 UTC

2

Help with nano overheating

Im currently building a sattellite for a school project wich has the task of stabilising a camera towards the ground. Im using an arduino nano connected to a 7.4v Lipo battery which is also connected to 2 SG90 servo motors. When im powering the arduino through the USB port everything is fine, but when i power it with my battery to also power the servos. The processor gets much hotter. HELP!?

I have the following components connected:

SG90 x2 --> directly to 7.4V RC battery

MPU9250 --> 3.3v on the board

Adafruit GPS --> 3.3v on the board

Adafruit Radio --> 3.3v on the board

thermistor --> 5v on the board

ESP-32 --> 5v on the board.

7 Comments
2025/02/03
19:00 UTC

4

How many stepper motors can you control at once with an Arduino UNO?

All,

I want to control 4 stepper motors independently using an Arduino UNO. The problem is, most of the steppers I find use 4 outputs for each driver. Does anyone know of a way to control more?

14 Comments
2025/02/03
18:08 UTC

2

Voltage control with arduino

I've searched to long and can't find what I am looking for so I thought I would ask the group.

I want to be able to control voltage output from 5v to 24v with an output pin on the Arduino. All I can find are modules that have a potentiometer on it for the range I want. I can't find anything that allows an input to allow me to control it with a program.

14 Comments
2025/02/03
17:34 UTC

0

my school is giving me clones of Arduino uno and i am not able to upload code in that by Arduino IDE. i am always getting port errors . at the same time when i use my original board , it works flawlessly....how can i fix that ? (i am a beginner btw)

help required to fix arduino

7 Comments
2025/02/03
17:23 UTC

1

4 pin connector to breadboard

I have following connector that I would like to connect to a breadboard, without having to cutting and crimping each cable. What female connector does this fit? I wonder if I can find a female 4 pin to male dupont off the shelf for this?

https://preview.redd.it/ka0v87i3pxge1.jpg?width=3024&format=pjpg&auto=webp&s=7b46df86ef31b66ffa91dd5ab9f82755323cff36

https://preview.redd.it/boph4g75pxge1.jpg?width=3024&format=pjpg&auto=webp&s=fbe7edfa56837e36e4276afb8f1acad1ef0b4732

1 Comment
2025/02/03
14:27 UTC

1

Mood-bot assistance with face screen not working anymore (Previously did)

Hello everyone, I am not a coder not even close. I had bought a product that uses Adriuno, it is a Mood-Bot that is really just a screen that displays faces. The product default was expression carousel that really just switched the faces every second or so between 1-5 face expressions. I went to their discord, and they have the files for the expression carousel and one that makes the face static, I tried uploading the static version however at some point it just had a solid face, I unplugged and replugged to see if it was going to stay on that face however the screen didn't show back up. I have tried uploading the expression carousel a couple of times but that didn't work either. I then tried some steps from ChatGPT and Deepseek, I had gotten to the point where it had asked to do the Blink Test and it did work, the blue LED did flash every second or so. So at this point I believe the code is at least executing but the screen is having problems. It came pre-assembled so I don't think I need to take it apart as I never had it apart to begin with.

Product: https://www.mecrobremake.com/products/mood-bot?_pos=1&_psq=mood+bot&_ss=e&_v=1.0

From what I saw on their discord it is a "Lolin (wemos) D1 R2 Mini" but they seem not as active as I would like to hopefully get the fix sooner rather than later incase I do need to return it for whatever reason.

Bottom

Screen

Right Side

Back

CH340C Chip

Example of one of the faces

Static Angry Face

Expression that changes every few seconds.

TLDR: Got a product that worked but was switching faces every second or so, wanted to have a static face, tried to upload a static face from creators after a lot of trouble shooting and unsuccessfully trying to uploading the face as Arduino Nano (as I had no more information on what board it was or how to actually do it, but after I found out the - Lolin (wemos) D1 R2 Mini), the face no longer lights up, Blink Test does works. (Also I asked the devs on their discord but no answer as of yet so that's why I am asking here)

I have both the files for Angry, and the Expression Carousel and the Bitmap/Bitmap_2 but the bitmaps are a bit longer so not sure how to upload as image.

Btw I am completely new so easier explanations or ideas would be best.

I really hope it's fixable, I like the little dude and don't want a replacement if possible

0 Comments
2025/02/03
17:02 UTC

0

How do i make an emulated keyboard with an 4x4 keypad and an arduino uno r3?

.

9 Comments
2025/02/03
16:54 UTC

86

Homebrew NFC coil tag

I use my DLP 3D printer with some dry film to make this PCB NFC coil. The spacing and route width is not uniform but tolerable. Achieving 4.78 uH instead of calculated 5uH. I think i found my new favorite methode instead of using toner transfer.

I put M24LR04E NFC tag IC and connect it to an Arduino nano with I2C protocol. Upload some program and voila.. it worked. I can read the text i put on the program with my smartphone. It even worked even when i plugged it off the Arduino, without external power.

So i will continue playing with it. Maybe try this with an ATtiny and create some pasive sensor.

5 Comments
2025/02/03
13:40 UTC

0

Error using Arduino on Mac OS

F

1 Comment
2025/02/03
12:04 UTC

0

how do i transfer data from nicla vision to arduino uno?

so i am trying to make a projects which consist of a robotic arm moving based on the object the nicla vision camera recognizes but i can't find any information on how to transfer the data i get on the camera to the arduino uno board. did anyone do it or know how to do it?

1 Comment
2025/02/03
11:24 UTC

0

I need ideas regarding underpowered voltage regulators

Current PCB layout, but with current draw issues

I am currently designing a PCB to function as a portable MIDI interface for an open source project. As the brain, I use the Wemos D32, mainly because it has a battery connector and can charge the battery from USB, its WiFi connectivity and its relatively compact form factor. As a bonus I can provide the battery power via the VBAT pin on the PCB.

But as lots of ESP32 boards do, they come with a ME6211 for power which can only provide 500 mAh, which is not a lot considering that WiFi can lead to 400mAh spikes.

From my calculations, I need around 500-1000 mAh at 3.3V for my additional components (3 x CD74HC4067, 2 x AD9833, 1x PAM8403, 2 x 16 ohm passive piezo speakers). Most of the power goes towards sound generation.

I would like to add a circuit or a small PCB that can be powered from the battery via the pin VBAT or from usb via VUSB during charging, to not confuse the charging IC of the D32 with my additional load, that can also vary a bit.

My wishlist is

  • the battery should never be in danger,
  • little to no SMD components, everything should be easy to solder
  • I try to use as many standard off the shelf components as possible
  • I want only one USB port for Charging and Data
  • The USB port should be usable for a low latency data connection

Any thoughts or input would be helpful.

10 Comments
2025/02/03
09:46 UTC

3

MicroChess Update: En-Passant capture bug fixed and code uncommented!

I finally fixed an en-passant bug in the MicroChess project that had taken some time to figure out and the code has had the support commented out. It's fixed now and the code is all checked in at https://github.com/ripred/MicroChess. 😄

For those that didn't see the 6-post series only available here in our community some time back, MicroChess was an attempt to prove that the actual chess engine, not just the mechanical piece movement, could be done on the low level Arduino Uno or Nano with only 2K of RAM. I succeeded heh.

I'll dig out the link to the 6-part series of posts if anyone is interested in learning how to write game engines, game theory, bitfield packing, hardcore optimization and fairly advanced embedded techniques, and a popular recursive gaming algorithm called Minimax (with alpha-beta pruning 😎) used to play turn based games like chess or checkers.

The engine can play up to 7 ply levels deep (moves looked ahead alternating each players side and making their best move and then unrolling and responding). It supports castling, en-passant pawn captures (yay), quiescent move searches, opening book moves, FEN notation for setting up board situations, dozens of runtime options that can be set in the code and have full comments on them, and a lot more. It can examine around 900 moves per second which was as tight as I could get things running on an 8-bit core at 16Mhz. It actually increases to several thousand a seonc towards the end of the games when fewer pieces and moves need to be examined. Oh yeah, optional time limits are are available to force the engine to make it's best move seen so far when the limit is reached. There are a lot of options.

All in under 2K of RAM and 32K of flash code. Actually comes in just a few bytes shy of the flash limit heh.

All the Best!

ripred

0 Comments
2025/02/03
08:54 UTC

3

High-Frequency PWM Waveform Generator with RC Filter – A DIY Analog Signal Generator for Audio & Control!

After seeing another community members great post about controlling the internal AVR Timers about a week ago I was inspired to tackle making a decent waveform generator, using two timers and custom PWM generator code based off of one of the timers with the other timer updating the PWM value 256 times/sec. I think it's pretty good and only requires a 1K resistor and a 10nF cap and it outputs starting on pin 9 and then goes to the RC filter.

The sketch is capable of producing Square, Sawtooth, and Sine waves in the range from DC to around 1KHz. (the actual PWM rate used to accomplish this can go up to 62.5KHz). It uses two timers at the same time to shape and produce the final waveform.

The user is prompted to tell it what kind of waveform to produce, and then what frequency, through the serial debug window and then the values are computed and used.

Wiring the Hardware:

  1. Upload the sketch to your Arduino Uno.
  2. Connect the PWM output (pin 9) to one end of a 470 Ω resistor.
  3. Connect the other end of the 470 Ω resistor to a common node.
  4. Connect a 10 nF capacitor from that node to ground.
  5. (Optional) If you plan to drive a low-impedance load like an amplifier, connect the common node to the non-inverting input of a voltage-follower op-amp (e.g., LM358 with the inverting input connected to the output), and use the op-amp’s output as the final analog signal.
  6. Ensure that the Arduino’s ground, the capacitor’s ground, and any

additional circuit grounds are connected together.

Starting the Software:

Open the Serial Monitor (set the baud rate to 115200).The program will prompt you first to enter a waveform type:Next, enter your desired waveform frequency in Hertz (for example, 100 for a 100 Hz tone).

1 for Square 2 for Sawtooth 3 for Sine.

Example output:

High-Frequency PWM Waveform Generator
======================================
Enter waveform type (1 = square, 2 = sawtooth, 3 = sine):
3
Waveform type: 3
Enter desired waveform frequency in Hz (e.g., 100):
500
Waveform frequency: 500 Hz
Computed sample rate: 32000 Hz
Setup complete.
Remember to apply the RC low-pass filter (e.g., 470 Ω resistor + 10 nF capacitor) to PWM output on pin 9.

The Code:

/*
 * High-Frequency PWM Waveform Generator with RC Filter
 *
 * This sketch generates one of three waveforms (square, sawtooth, sine)
 * by updating the PWM duty cycle on pin 9 at a rate determined by the desired
 * waveform frequency and the number of samples per period.
 *
 * The PWM output is filtered through an external RC low-pass filter 
 * (e.g., a 470 Ω resistor in series with a 10 nF capacitor to ground) 
 * to produce a smooth analog voltage.
 *
 * User inputs (via Serial Monitor):
 *   - Waveform type: 1 = square, 2 = sawtooth, 3 = sine.
 *   - Desired waveform frequency in Hz.
 *
 * NOTE on Serial Input:
 * A custom function getInput() is used to prompt for and retrieve a complete,
 * non-empty line from the Serial Monitor without inserting delays. This avoids
 * the problem of leftover end-of-line characters (EOL's) being interpreted as
 * empty input.
 *
 * For more information on the Serial API, see:
 *   - Serial.begin(): https://docs.arduino.cc/reference/en/language/functions/communication/serial/begin/
 *   - Serial.available(): https://docs.arduino.cc/reference/en/language/functions/communication/serial/available/
 *   - Serial.readStringUntil(): https://docs.arduino.cc/reference/en/language/functions/communication/serial/readstringuntil/
 *
 * ++u/ripred3 – Feb 3, 2025
 *
 */

#include <Arduino.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>

#define NUM_SAMPLES 64      // Number of samples per waveform period
#define PWM_PIN 9           // PWM output pin (Timer1 output)

// ---------- Global Variables ----------
volatile uint8_t waveform_type = 0;   // 1: square, 2: sawtooth, 3: sine
volatile uint16_t sample_index = 0;   // Current index for waveform sample progression
volatile uint8_t saw_value = 0;       // Sawtooth waveform current value

// ---------- Sine Wave Lookup Table (8-bit values: 0-255) ----------
const uint8_t sine_table[NUM_SAMPLES] PROGMEM = {
  128, 140, 152, 163, 173, 182, 189, 195,
  200, 203, 205, 205, 203, 200, 195, 189,
  182, 173, 163, 152, 140, 128, 115, 102,
   90,  79,  70,  63,  57,  53,  51,  51,
   53,  57,  63,  70,  79,  90, 102, 115,
  128, 140, 152, 163, 173, 182, 189, 195,
  200, 203, 205, 205, 203, 200, 195, 189,
  182, 173, 163, 152, 140, 128, 115, 102
};

// ---------- Timer2 Prescaler Options ----------
struct PrescalerOption {
  uint16_t prescaler;
  uint8_t cs_bits;  // Clock select bits for Timer2 (CS22:0)
};

PrescalerOption options[] = {
  {1,    (1 << CS20)},
  {8,    (1 << CS21)},
  {32,   (1 << CS21) | (1 << CS20)},
  {64,   (1 << CS22)},
  {128,  (1 << CS22) | (1 << CS20)},
  {256,  (1 << CS22) | (1 << CS21)},
  {1024, (1 << CS22) | (1 << CS21) | (1 << CS20)}
};
#define NUM_OPTIONS (sizeof(options) / sizeof(options[0]))

// ---------- Timer2 ISR: Updates PWM Duty Cycle ----------
ISR(TIMER2_COMPA_vect) {
  uint8_t output_val = 0;
  
  switch (waveform_type) {
    case 1: // Square wave: output 255 for first half of samples, then 0.
      output_val = (sample_index < (NUM_SAMPLES / 2)) ? 255 : 0;
      break;
      
    case 2: // Sawtooth wave: continuously increment value.
      output_val = saw_value;
      saw_value++;  // 8-bit arithmetic wraps from 255 back to 0.
      break;
      
    case 3: // Sine wave: retrieve value from lookup table.
      output_val = pgm_read_byte(&(sine_table[sample_index]));
      break;
      
    default:
      output_val = 0;
      break;
  }
  
  sample_index++;
  if (sample_index >= NUM_SAMPLES) {
    sample_index = 0;
  }
  
  // Update Timer1's PWM duty cycle by writing to OCR1A.
  OCR1A = output_val;
}

// ---------- Function: getInput -----------------
// Prompts the user and waits (busy-waiting) for a non-empty line from the Serial Monitor.
// Uses Serial.available() and Serial.readStringUntil() without adding delay() calls.
// For Serial API details, see:
//   - Serial.available(): https://docs.arduino.cc/reference/en/language/functions/communication/serial/available/
//   - Serial.readStringUntil(): https://docs.arduino.cc/reference/en/language/functions/communication/serial/readstringuntil/
String getInput(const char* prompt) {
  Serial.println(prompt);
  String input = "";
  // Busy-wait until a non-empty line is received.
  while (input.length() == 0) {
    if (Serial.available() > 0) {
      input = Serial.readStringUntil('\n');
      input.trim(); // Remove any whitespace or EOL characters.
    }
  }
  return input;
}

// ---------- Setup Timer2 for Waveform Updates ----------
void setup_timer2(uint32_t sample_rate) {
  uint8_t chosen_cs = 0;
  uint16_t chosen_ocr = 0;
  
  // Determine a prescaler option yielding OCR2A <= 255.
  for (uint8_t i = 0; i < NUM_OPTIONS; i++) {
    uint32_t ocr = (F_CPU / (options[i].prescaler * sample_rate)) - 1;
    if (ocr <= 255) {
      chosen_cs = options[i].cs_bits;
      chosen_ocr = ocr;
      break;
    }
  }
  
  // If no valid prescaler was found, use the maximum prescaler.
  if (chosen_cs == 0) {
    chosen_cs = options[NUM_OPTIONS - 1].cs_bits;
    chosen_ocr = 255;
  }
  
  cli();  // Disable interrupts during Timer2 configuration.
  
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2  = 0;
  
  TCCR2A |= (1 << WGM21);  // Set Timer2 to CTC mode.
  OCR2A = chosen_ocr;
  TCCR2B |= chosen_cs;
  TIMSK2 |= (1 << OCIE2A); // Enable Timer2 Compare Match interrupt.
  
  sei();  // Re-enable interrupts.
}

// ---------- Setup Timer1 for PWM Output on Pin 9 ----------
void setup_timer1_pwm() {
  pinMode(PWM_PIN, OUTPUT);
  
  cli(); // Disable interrupts during Timer1 configuration.
  
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  
  // Configure Timer1 for 8-bit Fast PWM on channel A (pin 9) in non-inverting mode.
  TCCR1A |= (1 << WGM10) | (1 << COM1A1);
  TCCR1B |= (1 << CS10);  // No prescaling: PWM frequency ≈ 16MHz/256 ≈ 62.5 kHz.
  
  sei(); // Re-enable interrupts.
}

// ---------- Setup Function ----------
void setup() {
  Serial.begin(115200);  // Preferred baud rate.
  while (!Serial) { }     // Wait for the Serial Monitor connection.
  
  Serial.println(F("High-Frequency PWM Waveform Generator"));
  Serial.println(F("======================================"));
  
  // --- Get Waveform Type ---
  String typeString = getInput("Enter waveform type (1 = square, 2 = sawtooth, 3 = sine):");
  waveform_type = typeString.toInt();
  Serial.print(F("Waveform type: "));
  Serial.println(waveform_type);
  
  // --- Get Desired Waveform Frequency ---
  String freqString = getInput("Enter desired waveform frequency in Hz (e.g., 100):");
  uint32_t waveform_freq = freqString.toInt();
  Serial.print(F("Waveform frequency: "));
  Serial.print(waveform_freq);
  Serial.println(F(" Hz"));
  
  // Compute the sample rate as: waveform frequency * NUM_SAMPLES.
  uint32_t sample_rate = waveform_freq * NUM_SAMPLES;
  Serial.print(F("Computed sample rate: "));
  Serial.print(sample_rate);
  Serial.println(F(" Hz"));
  
  // Initialize PWM on Timer1.
  setup_timer1_pwm();
  
  // Initialize Timer2 to update the PWM duty cycle.
  setup_timer2(sample_rate);
  
  Serial.println(F("Setup complete."));
  Serial.println(F("Remember to apply the RC low-pass filter (e.g., 470 Ω resistor + 10 nF capacitor) to PWM output on pin 9."));
}

// ---------- Main Loop ----------
void loop() {
  // No processing is needed here as waveform generation is handled in the Timer2 ISR.
  // The loop remains empty to allow uninterrupted timer interrupts.
}

Let me know if I screwed anything up.

Cheers!

ripred

0 Comments
2025/02/03
08:17 UTC

15

Does Elegoo starter kit actually teach?

I am interested in engineering (mechanical and electrical), and I found the Elegoo starter kit. It looks fun to make projects with, but I am not sure if I will actually learn anything since I want to actually learn some basics of engineering. So, I am not sure if I should get it. My question is: is the Elegoo starter kit a toy, or will I actually learn from it? If so, how would I do that? Should I follow guides online? If so, which ones? Should I follow the book or find and create my own projects?

FYI, I am a complete beginner and have only made a sort of robot car from a set in a summer program. I don't remember the specific one.

Edit: Sorry I didn't realize that I had not included what I was talking about. It's Uno R3 Super Starter Kit

22 Comments
2025/02/03
03:34 UTC

Back To Top