r/Arduino_AI • • Jul 01 '25

What should i do i am coding from phone i don't have pc and i am doing it from arduinodroid and it's compiling but not uploading ,when i asked chatgpt about it ,it said the code is too big for arduinodroid

2 Upvotes

r/Arduino_AI • • Mar 31 '25

Anyone tried controllino.ai?

2 Upvotes

Has anyone used anything other than their free starter level? They offer three tiers of embedded-focused AI tools with increasing domain knowledge. The enterprise tier specifies:

  • Very Specialized Knowledge of Microcontrollers

Trained and specialized on Arduino, CONTROLLINO, ESP32, ESP8266, Raspberry Pi Pico, STM32, Teensy, Adafruit Feather, Nucleo and many more devices, paired with the highest quality models for coding like Claude 3.5 Sonnet that has even more knowledge and skills than GPT-4o.

Pros: not crazy expensive at any tier; the company appears to have been around a while in the industrial controller space, so it makes sense that they're monetizing one of their in-house tools

Cons: literally no non-trade-show usage reviews that I can find. Not even here on reddit.

Anyone have any experience with this? I keep having to remind AI that I do not have Mb of memory and infinite pins, so some culling of this and baseline knowledge of internal timers, ADC/DAC, USB contortions, etc. would be a good start. If it could make esoteric Pi Pico PIO programs to order, that'd be fab.


r/Arduino_AI • • Mar 07 '25

Look What I Made! New – Official Arduino Minimax Library Released

2 Upvotes

Many of you may have seen the posts and discussions around the Minimax library I was in the process of developing along with several example games that showed how to make use of the library.

The new repository for the library with the complete implementation (as well as four (4) examples so far) is available here and you can use that as an alternative way install the library now as well as to track the progress of future updates. The working examples/ so far include

I'm glad to say that it has been packaged up and gone through the acceptance process and the Minimax library and all four examples developed so far are now available in the official Arduino Library repository.

So within a few hours of this post; Version 1.0.0 of the library will be available in your IDE's for installation and automatic future updates.

Please let me know if you encounter any issues or have any constructive suggestions.

All the Best!

ripred


r/Arduino_AI • • Mar 04 '25

Look What I Made! A New Game Using Yesterday's Minimax Library – Connect Four!

2 Upvotes

For those that didn't see the other post here is a link to a full `Checkers.ino` game and the main header file we also use today.

Today's game is Connect Four, using emoji's sent to the output Serial monitor for a nicer game interface, that you can play against the Arduino, or have the Arduino play both sides! 😀

Have Fun! Change it up.. Make your own thinking games..

ripred

Example Game Output:

ConnectFour.ino

/**
 * ConnectFour.ino - Connect Four game implementation using Minimax library
 * 
 * This sketch implements a Connect Four game that can be played:
 * - Human vs. AI
 * - AI vs. AI (self-play)
 * 
 * The game interface uses Serial communication for display and input.
 * Board visualization uses emoji symbols for better visual experience.
 * 
 * March 3, 2025 ++tmw
 */

#include "Minimax.h"

// Constants for board representation
#define    EMPTY   0
#define    RED     1    // Human player
#define    BLUE    2    // AI player

// Game configuration
#define    MINIMAX_DEPTH    4      // Search depth for AI
#define    MAX_MOVES        7      // Maximum possible moves (columns) for one position

// Board dimensions
#define    ROWS    6
#define    COLS    7

// Game modes
#define    MODE_HUMAN_VS_AI    0
#define    MODE_AI_VS_AI       1

// Game state - represents the board
struct ConnectFourState {
  byte board[ROWS][COLS];
  bool blueTurn;  // true if it's blue's turn, false for red's turn
  
  // Initialize the board with empty cells
  void init() {
    blueTurn = false;  // Red goes first
    
    // Initialize empty board
    for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
        board[row][col] = EMPTY;
      }
    }
  }
};

// Move structure - for Connect Four, a move is just a column choice
struct ConnectFourMove {
  byte column;
  
  ConnectFourMove() : column(0) {}
  ConnectFourMove(byte col) : column(col) {}
};

// Game logic implementation
class ConnectFourLogic : public Minimax<ConnectFourState, ConnectFourMove, MAX_MOVES, MINIMAX_DEPTH>::GameLogic {
public:
  // Find the row where a piece would land if dropped in the given column
  int findDropRow(const ConnectFourState& state, int col) {
    for (int row = ROWS - 1; row >= 0; row--) {
      if (state.board[row][col] == EMPTY) {
        return row;
      }
    }
    return -1; // Column is full
  }
  
  // Check if there's a win starting from a specific position
  bool checkWin(const ConnectFourState& state, int startRow, int startCol, int piece) {
    // Check horizontal
    int count = 0;
    for (int c = max(0, startCol - 3); c < min(COLS, startCol + 4); c++) {
      if (state.board[startRow][c] == piece) {
        count++;
        if (count >= 4) return true;
      } else {
        count = 0;
      }
    }
    
    // Check vertical
    count = 0;
    for (int r = max(0, startRow - 3); r < min(ROWS, startRow + 4); r++) {
      if (state.board[r][startCol] == piece) {
        count++;
        if (count >= 4) return true;
      } else {
        count = 0;
      }
    }
    
    // Check diagonal (top-left to bottom-right)
    count = 0;
    for (int i = -3; i <= 3; i++) {
      int r = startRow + i;
      int c = startCol + i;
      if (r >= 0 && r < ROWS && c >= 0 && c < COLS) {
        if (state.board[r][c] == piece) {
          count++;
          if (count >= 4) return true;
        } else {
          count = 0;
        }
      }
    }
    
    // Check diagonal (top-right to bottom-left)
    count = 0;
    for (int i = -3; i <= 3; i++) {
      int r = startRow + i;
      int c = startCol - i;
      if (r >= 0 && r < ROWS && c >= 0 && c < COLS) {
        if (state.board[r][c] == piece) {
          count++;
          if (count >= 4) return true;
        } else {
          count = 0;
        }
      }
    }
    
    return false;
  }
  
  // Check for a win more efficiently (check entire board)
  bool hasWin(const ConnectFourState& state, int piece) {
    // Horizontal check
    for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col <= COLS - 4; col++) {
        if (state.board[row][col] == piece &&
            state.board[row][col+1] == piece &&
            state.board[row][col+2] == piece &&
            state.board[row][col+3] == piece) {
          return true;
        }
      }
    }
    
    // Vertical check
    for (int row = 0; row <= ROWS - 4; row++) {
      for (int col = 0; col < COLS; col++) {
        if (state.board[row][col] == piece &&
            state.board[row+1][col] == piece &&
            state.board[row+2][col] == piece &&
            state.board[row+3][col] == piece) {
          return true;
        }
      }
    }
    
    // Diagonal check (top-left to bottom-right)
    for (int row = 0; row <= ROWS - 4; row++) {
      for (int col = 0; col <= COLS - 4; col++) {
        if (state.board[row][col] == piece &&
            state.board[row+1][col+1] == piece &&
            state.board[row+2][col+2] == piece &&
            state.board[row+3][col+3] == piece) {
          return true;
        }
      }
    }
    
    // Diagonal check (top-right to bottom-left)
    for (int row = 0; row <= ROWS - 4; row++) {
      for (int col = 3; col < COLS; col++) {
        if (state.board[row][col] == piece &&
            state.board[row+1][col-1] == piece &&
            state.board[row+2][col-2] == piece &&
            state.board[row+3][col-3] == piece) {
          return true;
        }
      }
    }
    
    return false;
  }
  
  // Evaluate board position from current player's perspective
  int evaluate(const ConnectFourState& state) override {
    // Check for terminal states first (wins)
    if (hasWin(state, RED)) {
      return state.blueTurn ? 10000 : -10000; // Perspective of current player
    }
    if (hasWin(state, BLUE)) {
      return state.blueTurn ? -10000 : 10000; // Perspective of current player
    }
    
    int score = 0;
    
    // Evaluate potential threats and opportunities
    // For each cell, check how many pieces are in a row in each direction
    for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
        if (state.board[row][col] != EMPTY) {
          continue; // Skip filled cells
        }
        
        // Create a temporary copy of state to modify
        ConnectFourState tempState = state;
        
        // Check potential for RED
        tempState.board[row][col] = RED;
        if (checkWin(tempState, row, col, RED)) {
          score -= 100; // Potential win for RED
        }
        
        // Check potential for BLUE
        tempState.board[row][col] = BLUE;
        if (checkWin(tempState, row, col, BLUE)) {
          score += 100; // Potential win for BLUE
        }
      }
    }
    
    // Favor center columns for better control
    for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
        if (state.board[row][col] == RED) {
          // Penalize RED pieces (from BLUE's perspective)
          // Value center columns more
          score -= 3 * (COLS - abs(col - COLS/2));
        } else if (state.board[row][col] == BLUE) {
          // Reward BLUE pieces (from BLUE's perspective)
          // Value center columns more
          score += 3 * (COLS - abs(col - COLS/2));
        }
      }
    }
    
    // Invert score if it's red's turn (adjust for perspective)
    return state.blueTurn ? score : -score;
  }
  
  // Generate all valid moves from the current state
  int generateMoves(const ConnectFourState& state, ConnectFourMove moves[], int maxMoves) override {
    int moveCount = 0;
    
    // A move is valid if the column is not full
    for (int col = 0; col < COLS && moveCount < maxMoves; col++) {
      if (findDropRow(state, col) >= 0) {
        moves[moveCount] = ConnectFourMove(col);
        moveCount++;
      }
    }
    
    return moveCount;
  }
  
  // Apply a move to a state, modifying the state
  void applyMove(ConnectFourState& state, const ConnectFourMove& move) override {
    // Find the lowest empty row in the selected column
    int row = findDropRow(state, move.column);
    
    if (row >= 0) {
      // Place the piece
      state.board[row][move.column] = state.blueTurn ? BLUE : RED;
      
      // Switch turns
      state.blueTurn = !state.blueTurn;
    }
  }
  
  // Check if the game has reached a terminal state (win/loss/draw)
  bool isTerminal(const ConnectFourState& state) override {
    // Check if either player has won
    if (hasWin(state, RED) || hasWin(state, BLUE)) {
      return true;
    }
    
    // Check for a draw (board is full)
    for (int col = 0; col < COLS; col++) {
      if (findDropRow(state, col) >= 0) {
        return false; // There's still at least one valid move
      }
    }
    
    return true; // Board is full, it's a draw
  }
  
  // Check if the current player is the maximizing player
  bool isMaximizingPlayer(const ConnectFourState& state) override {
    // BLUE is the maximizing player (AI)
    return state.blueTurn;
  }
};

// Global variables
ConnectFourState gameState;
ConnectFourLogic gameLogic;
Minimax<ConnectFourState, ConnectFourMove, MAX_MOVES, MINIMAX_DEPTH> minimaxAI(gameLogic);

int gameMode = MODE_HUMAN_VS_AI;  // Default to Human vs AI

// Function to display the board with emoji symbols
void displayBoard(const ConnectFourState& state) {
  // Column numbers with emoji numbers for consistent spacing
  Serial.println("\n 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣");
  
  for (int row = 0; row < ROWS; row++) {
    Serial.print(" ");
    
    for (int col = 0; col < COLS; col++) {
      switch (state.board[row][col]) {
        case EMPTY:
          Serial.print("⚪"); // White circle for empty
          break;
        case RED:
          Serial.print("🔴"); // Red circle
          break;
        case BLUE:
          Serial.print("🔵"); // Blue circle
          break;
      }
      Serial.print(" ");
    }
    
    Serial.println();
  }
  
  // Display column numbers again at the bottom with emoji numbers
  Serial.println(" 0️⃣ 1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣ 6️⃣");
  Serial.print(state.blueTurn ? "Blue's turn" : "Red's turn");
  Serial.println();
}

// Function to get a move from human player
ConnectFourMove getHumanMove() {
  ConnectFourMove move;
  bool validMove = false;
  
  while (!validMove) {
    // Prompt for input
    Serial.println("Enter column (0-6):");
    
    // Wait for input
    while (!Serial.available()) {
      delay(100);
    }
    
    // Read the column
    move.column = Serial.parseInt();
    
    // Clear the input buffer
    while (Serial.available()) {
      Serial.read();
    }
    
    // Check if the column is valid
    if (move.column < COLS) {
      // Check if the column is not full
      if (gameLogic.findDropRow(gameState, move.column) >= 0) {
        validMove = true;
      } else {
        Serial.println("Column is full. Try another one.");
      }
    } else {
      Serial.println("Invalid column. Please enter a number between 0 and 6.");
    }
  }
  
  return move;
}

// Function to get AI move
ConnectFourMove getAIMove() {
  Serial.println("AI is thinking...");
  
  unsigned long startTime = millis();
  ConnectFourMove move = minimaxAI.findBestMove(gameState);
  unsigned long endTime = millis();
  
  Serial.print("AI chose column: ");
  Serial.println(move.column);
  
  Serial.print("Nodes searched: ");
  Serial.println(minimaxAI.getNodesSearched());
  
  Serial.print("Time: ");
  Serial.print((endTime - startTime) / 1000.0);
  Serial.println(" seconds");
  
  return move;
}

// Function to check for game over
bool checkGameOver() {
  if (gameLogic.isTerminal(gameState)) {
    displayBoard(gameState);
    
    // Determine the winner
    if (gameLogic.hasWin(gameState, RED)) {
      Serial.println("Red wins!");
    } else if (gameLogic.hasWin(gameState, BLUE)) {
      Serial.println("Blue wins!");
    } else {
      Serial.println("Game ended in a draw!");
    }
    
    Serial.println("Enter 'r' to restart or 'm' to change mode.");
    return true;
  }
  
  return false;
}

// Function to handle game setup and restart
void setupGame() {
  gameState.init();
  
  Serial.println("\n=== CONNECT FOUR ===");
  Serial.println("Game Modes:");
  Serial.println("1. Human (Red) vs. AI (Blue)");
  Serial.println("2. AI vs. AI");
  Serial.println("Select mode (1-2):");
  
  while (!Serial.available()) {
    delay(100);
  }
  
  char choice = Serial.read();
  
  // Clear the input buffer
  while (Serial.available()) {
    Serial.read();
  }
  
  if (choice == '2') {
    gameMode = MODE_AI_VS_AI;
    Serial.println("AI vs. AI mode selected.");
  } else {
    gameMode = MODE_HUMAN_VS_AI;
    Serial.println("Human vs. AI mode selected.");
    Serial.println("You play as Red, AI plays as Blue.");
  }
}

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // Wait for serial port to connect
  }
  
  randomSeed(analogRead(0));
  setupGame();
}

void loop() {
  // Display the current board state
  displayBoard(gameState);
  
  if (checkGameOver()) {
    while (!Serial.available()) {
      delay(100);
    }
    
    char choice = Serial.read();
    
    // Clear input buffer
    while (Serial.available()) {
      Serial.read();
    }
    
    if (choice == 'r') {
      setupGame();
    } else if (choice == 'm') {
      gameMode = (gameMode == MODE_HUMAN_VS_AI) ? MODE_AI_VS_AI : MODE_HUMAN_VS_AI;
      setupGame();
    }
    return;
  }
  
  // Get and apply move based on game mode and current player
  ConnectFourMove move;
  
  if (gameMode == MODE_HUMAN_VS_AI) {
    if (!gameState.blueTurn) {
      // Human's turn (Red)
      move = getHumanMove();
    } else {
      // AI's turn (Blue)
      move = getAIMove();
      delay(1000); // Small delay to make AI moves visible
    }
  } else {
    // AI vs. AI mode
    move = getAIMove();
    delay(2000); // Longer delay to observe the game
  }
  
  // Apply the move
  gameLogic.applyMove(gameState, move);
}

r/Arduino_AI • • Feb 25 '25

Arduino Project Manager - Full Source

2 Upvotes

The full project is now up on github! It's only 3 files: server.py, openai.yaml, and instructions.txt. The repository can be found here and will likely be changing often for a few weeks:

https://github.com/ripred/Arduino-Project-Manager-GPT

I will be making a video soon about what to do with these files and how to configure your own openAI account's Custom GPT if there's interest.

All the Best!

ripred

edit: If any of you use this to make your own version I'd love to see it posted here!


r/Arduino_AI • • Feb 18 '25

Tutorials Level Up Your Arduino: Custom GPT Control

2 Upvotes

This series will demonstrate how to build a Custom GPT (using OpenAI) to control your Arduino, write code, upload it, and interact with it in real-time.

Specifically, this Custom GPT will be able to:

  • Generate Arduino code based on natural language instructions.

  • Upload generated code directly to your Arduino.

  • Interface with your running Arduino program through a Python application, enabling data streaming and control.

  • Pass text and images bi-directionally between your Arduino and the GPT conversation.

Disclaimer: Using Custom GPT "Actions" requires a paid OpenAI subscription (Plus, Pro, or Enterprise).

Custom GPTs and "Actions": The Basics

A Custom GPT, in this context, is a specifically trained model designed to recognize Arduino-related requests. When a relevant prompt is detected, it extracts the necessary information and passes it to an "Action" – a Python function we'll develop to handle code generation, uploading, and communication with the Arduino. This allows for customized interaction and responses.

With the right Python libraries you can even return images or video back to the conversation. This means things like (for example) maybe showing an animated GIF of a running circuit, grabbed from falstad.com's circuit simulator. Or an image of the wiring steps for a breadboard project using one of the online simulators, and grabbing their screens to get the images.

Dall-E and Sora are two examples of Custom GPT's.

Why This Matters

This approach can significantly streamline Arduino development, making it more intuitive and potentially accelerating project completion.

Initial Setup: Essential Tools

We'll be using two command-line tools:

  • ngrok: Creates a secure tunnel from your local machine to a public URL. This is necessary for OpenAI servers to access your locally running Python application.

  • uvicorn: An ASGI web server implementation, which we'll use to run our Python application and handle communication.

Let's get these installed. Instructions for Windows, macOS, and Linux follow.

1. Installing ngrok

  • Purpose: Enables OpenAI to access your local Python server.

  • Common Steps (All Platforms):

    1. Download the appropriate package for your OS from https://ngrok.com/download.

    2. Unzip the downloaded archive.

    3. Authentication: Create a free ngrok account at https://ngrok.com/. Obtain your authtoken from the dashboard (https://dashboard.ngrok.com/get-started/setup).

  • Windows:

    1. Move ngrok.exe to a designated directory (e.g., C:\ngrok). Create the directory if it doesn't exist.

    2. Add C:\ngrok to your system's PATH environment variable.

      • Search for "Edit the system environment variables".

      • Select "Environment Variables...".

      • Under "System variables", locate Path, select it, and click "Edit...".

      • Click "New" and add C:\ngrok.

      • Confirm changes by clicking "OK" on all windows.

    3. Open a new Command Prompt and execute ngrok authtoken YOUR_AUTHTOKEN (replace YOUR_AUTHTOKEN with your actual authtoken).

  • macOS:

    1. Move the ngrok executable to /usr/local/bin:(Replace /path/to/ngrok with the actual path to the downloaded file.)sudo mv /path/to/ngrok /usr/local/bin/ngrok

    2. Make it executable:sudo chmod +x /usr/local/bin/ngrok

    3. Run ngrok authtoken YOUR_AUTHTOKEN in Terminal.

  • Linux:

    1. Extract the ngrok executable to a directory (e.g., ~/ngrok).

    2. Add the directory to your PATH. Temporarily:For a persistent change, add the above line to ~/.bashrc or ~/.zshrc.export PATH="$PATH:~/ngrok"

    3. Make it executable:chmod +x ~/ngrok/ngrok

    4. Execute ngrok authtoken YOUR_AUTHTOKEN in Terminal.

2. Installing uvicorn

  • Purpose: To run our Python application.

  • All Platforms:

    1. Python Installation: Ensure you have Python 3.7+ installed. Download from https://www.python.org/downloads/. On Windows, select the option to add Python to your PATH.

    2. Terminal/Command Prompt: Open your preferred terminal.

    3. Install uvicorn**:**(Use pip3 if necessary.) pip install uvicorn

That concludes the initial setup. If you encounter any issues with ngrok or uvicorn installation, please post in the comments. The next post will cover building the Python application for Arduino interaction. #arduino #openai #gpt #python #ai #makers


r/Arduino_AI • • Feb 16 '25

Can i use huskylens pro to detect colors and QR core at the same time?

2 Upvotes

r/Arduino_AI • • Feb 09 '25

Dialog A Test run of a job using openAI's Pro Subscription

2 Upvotes

I'll be posting a few of these for everyone to check out if you are interested.

edit: updated link, hopefully will work?

https://chatgpt.com/share/67a89fea-0b38-800e-b701-ac087c53c942

You'll notice that I did this in a few different stages. First I used the O1 Pro model alone to help craft the best prompt. Then I gave that crafted prompt to the count-constrained Deep Research inference side of things to go do the actual research part online and then the generation of the response.

I'm also running some similar but different experiments on subscription level models on Gemini 2.0 as well as Anthropic's latest Claude Sonnet.

Curious to hear your thoughts.

Cheers,

ripred


r/Arduino_AI • • Jan 24 '25

Can I use open cv library with stm32 ?

2 Upvotes

There are any tutorials or repos can help me ?


r/Arduino_AI • • Dec 03 '24

Anyone played with Google's Teachable Machine Yet?

Thumbnail reddit.com
2 Upvotes

r/Arduino_AI • • Oct 23 '24

Code Help How to aproach local LLM to Arduino communication?

2 Upvotes

I started to tinker with ai for a couple of weeks and want to make a project which includes a comunication between a local running mistral based LLM and some actors. I am familiar with arduino but prety far behind with the whole python and Ai stuff. Could someone point me in the right direction.

For starters i just want to be able to let my chatbot manipulate actors through an arduino/esp. Like turning on Leds.

I would define commands for my bot which it can use in certain situations depending on the context of its answers. I would like to isolate those commands and send them to the microcontroller.

Where can i start, what should i learn, and what do i need to do it?

I am ok with learning python and have decent microcontroller skills. At the moment i use oobabooga to run the models.

Thx in advance


r/Arduino_AI • • Oct 10 '24

Stm32 not working

2 Upvotes

What to do if my stm32f103c8t6 is not connecting to my laptop are there any methods that can I use to solve this problem.


r/Arduino_AI • • Oct 01 '24

DIY LED Name Board – Create Your Own Custom LED Sign with Simple Materials!

Thumbnail youtu.be
2 Upvotes

Check out this new project ‼️‼️


r/Arduino_AI • • Jul 04 '24

Need help with Euclidean Rhythm Generator code

Thumbnail self.synthdiy
2 Upvotes

r/Arduino_AI • • May 07 '24

Motors arent spinning

2 Upvotes

i have this PID control that i wanna use to stabilize a drone, idc about flight right now, i just want it to spin the motors at 50% speed and then add the PID output to the base speed "

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <ArduPID.h>

Adafruit_MPU6050 mpu;

ArduPID controlRoll;
ArduPID controlPitch;

double rollSP = 0;
double pitchSP = 0;

double rollInput;
double pitchInput;

double rollOutput;
double pitchOutput;

// Initially set low PID values for smoother control
double rollP = 0.1;
double pitchP = 0.1;

double rollI = 0.0;
double pitchI = 0.0;

double rollD = 0.1;
double pitchD = 0.1;

const int esc1Pin = 17;
const int esc2Pin = 5;
const int esc3Pin = 18;
const int esc4Pin = 19;
int valanMax = 950;
int valanMin = 450;

void setup(void) {
  Serial.begin(115200);
  while (!Serial) {
    delay(10); // Wait for serial monitor to open
  }

  // Attempt communication with MPU6050
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }

  // Initial motor spin at slightly above minimum (adjust if needed)
  analogWrite(esc1Pin, valanMin + 10);
  analogWrite(esc2Pin, valanMax - (valanMin + 10));
  analogWrite(esc3Pin, valanMin + 10);
  analogWrite(esc4Pin, valanMax - (valanMin + 10));

  mpu.setAccelerometerRange(MPU6050_RANGE_16_G);
  mpu.setGyroRange(MPU6050_RANGE_250_DEG);
  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
  Serial.println("");
  delay(100);

  pinMode(esc1Pin, OUTPUT);
  pinMode(esc2Pin, OUTPUT);
  pinMode(esc3Pin, OUTPUT);
  pinMode(esc4Pin, OUTPUT);

  controlRoll.begin(&rollInput,&rollOutput,&rollSP,rollP,rollI,rollD);
  controlPitch.begin(&pitchInput,&pitchOutput,&pitchSP,pitchP,pitchI,pitchD);


}

void loop() {
  // Base speed for 50% throttle with slight adjustment (optional)
  const double baseSpeed = valanMin + (valanMax - valanMin) * 0.5 + 10;

  // Read sensor data
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  // Calculate roll and pitch angles from accelerometer data
  int gradosRoll = atan2(a.acceleration.y, a.acceleration.z) * RAD_TO_DEG;
  int gradosPitch = atan2(-a.acceleration.x, a.acceleration.z) * RAD_TO_DEG;

  // Optional gyro drift compensation (adjust values as needed)
  g.gyro.x = g.gyro.x + 0.01;
  g.gyro.y = g.gyro.y + 0.085;

  // Set roll and pitch inputs for PID controller
  rollInput = gradosRoll;
  pitchInput = gradosPitch;

  // Perform PID calculations to determine motor adjustments
  controlRoll.compute();
  controlPitch.compute();

  // Calculate motor signal with base speed (adjusted for deadzone)
  int motorSignal = map(rollOutput + pitchOutput + baseSpeed, -valanMax, valanMax, valanMin + 10, valanMax);

  // Constrain motor signal within valid ESC range
  motorSignal = constrain(motorSignal, valanMin + 10, valanMax);

  // Set motor signals for each ESC with direction control
  analogWrite(esc1Pin, motorSignal);
  analogWrite(esc2Pin, valanMax - motorSignal);
  analogWrite(esc3Pin, motorSignal);
  analogWrite(esc4Pin, valanMax - motorSignal);

  // Uncomment for debugging (optional)
  Serial.print("Grados Roll:");
  Serial.print(gradosRoll);
  Serial.print(" Grados Pitch:");
  Serial.print(gradosPitch);
  Serial.print(" senal motor:");
  Serial.println(motorSignal);
  
  delay(100);
}
"

r/Arduino_AI • • Mar 25 '24

how to get data from bluetooth

2 Upvotes

i have written a code for arduino to run two motors via a l298n motor driver and a hc-o5 bluetooth module but when i send signal from my android device the motors are not working.

does anyone know about it ?


r/Arduino_AI • • Mar 14 '24

Error in uploading program

2 Upvotes

I am facing issues in uploading my program in arduino I have checked the ports and device but I am not able to find any issues. does anyone know anything about it ?


r/Arduino_AI • • Mar 04 '24

Look What I Made! Arduino self-driving car project+tutorial

Thumbnail
dev.to
2 Upvotes

Hey everyone, I'm working towards building an Arduino based car with self driving capabilities. Will be sensors and exchanging data wirelessly using the esp8266. I'm still new to embedded programming so would love your feedback!


r/Arduino_AI • • Jan 26 '24

Help me

2 Upvotes

This code plays music on a regular speaker by sending data(port.write(number)) to the port from a Processing program. However, when attempting to use DFPlayer instead of the melody_play(3) section at the end of the code, the audio doesn't play even when writing code as follows. What could be the reason for this, and how can it be corrected?

#include <SoftwareSerial.h>
//Pin Assign
#define BT_RX 6
#define BT_TX 7
#define DP_LED 2
#define SP 5
#define SW 4
//Constant Value
#define BAUDRATE 115200
//Getting raw data
#define period 100 //measurement period
#define ST 1000 //計測以外での待ち時間の設定 setting of waiting time (besides measuring)
#define Vcc 5.0 //電圧値⇒圧力値で使用 voltage value ⇒ used at pressure value
#define Rm 1.0 //電圧値⇒圧力値で使用 voltage value ⇒ used at pressure value
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
// Use pins 2 and 3 to communicate with DFPlayer Mini
static const uint8_t PIN_MP3_TX = 2; // Connects to module's RX
static const uint8_t PIN_MP3_RX = 3; // Connects to module's TX
SoftwareSerial softwareSerial(PIN_MP3_RX, PIN_MP3_TX);
SoftwareSerial mySerial(BT_RX,BT_TX);
// Create the Player object
DFRobotDFPlayerMini myDFplayer;
//Software Serial class
//--追加部分------------------------
//Valiable
int melo[8][24];
int wait[8][24];
unsigned long melody_millis = 0;
int melody_count = 0;
int melody_flag = -1;
//-----------------------------------
//Time management
unsigned long time_now = 0; //time in which the measurement is done
int Count = 0; //計測終了用のカウント count for measuring termination (in case of pressing the button twice by accident)
int APin_F = 0; //Analogread圧力値入力 pressure value input
int APin_ax, APin_ay, APin_az; //Analogread加速度入力 x axis acceleration input
float F_Vout, Rfsr; //Used for calculate force
float ax_row, ay_row, az_row; //Acceleration [G]
//------追加部分-----------------------------
void melody_init(){
//Melody Setup
int i,j;//temporary(仮の,一時的の)
//initialize valiable(変数の初期化)
for(i = 0;i < 8;i++){
for(j = 0;j < 24;j++){
melo[i][j] = -1;//-1 is no define(-1は定義しない)
wait[i][j] = -1;//-1 is no define
}
}
}
void melody_setup(){
//この関数で作曲します。
//現状8曲登録可能で1曲あたり16音(休符含)鳴らせます
//melody_set(曲番号,周波数[Hz],鳴らす時間[ms])です(周波数を0にすると休符)
//melody_play(曲番号)という関数を使うと鳴らせます。
//例として、曲番号0番にエリーゼ、1番に人生のメリーゴーランドを登録してます
//周波数を登録するときはmelo_freq(オクターブ[],音程(大文字で半音))関数を使うと便利です
//melo_freq(0,'a');だと440Hz(基準ピッチのA)
//曲番号0番 マリオ1up 6音
melody_set(0,melo_freq(1,'e'),150);//1音目
melody_set(0,melo_freq(1,'g'),150);//2音目
melody_set(0,melo_freq(2,'e'),150);//3音目
melody_set(0,melo_freq(2,'c'),150);//4音目
melody_set(0,melo_freq(2,'d'),150);//5音目
melody_set(0,melo_freq(2,'g'),150);//6音目
//曲番号1番 人生のメリーゴーランド 22音
melody_set(1,melo_freq(0,'d'),250);//1音目
melody_set(1,melo_freq(0,'g'),250);//2音目
melody_set(1,melo_freq(1,'A'),250);//3音目
melody_set(1,melo_freq(1,'d'),350);//4音目
melody_set(1,0,50);//5音目(休符)
melody_set(1,melo_freq(1,'d'),250);//6音目
melody_set(1,melo_freq(1,'c'),250);//7音目
melody_set(1,melo_freq(1,'A'),250);//8音目
melody_set(1,melo_freq(1,'a'),250);//9音目
melody_set(1,melo_freq(1,'A'),750);//10音目
melody_set(1,melo_freq(0,'g'),250);
melody_set(1,melo_freq(1,'A'),250);
melody_set(1,melo_freq(1,'d'),250);
melody_set(1,melo_freq(1,'g'),350);
melody_set(1,0,50);//15音目(休符)
melody_set(1,melo_freq(1,'g'),250);
melody_set(1,0,10);//15音目(休符)
melody_set(1,melo_freq(1,'g'),250);
melody_set(1,melo_freq(2,'a'),250);
melody_set(1,melo_freq(1,'f'),100);
melody_set(1,melo_freq(1,'D'),100);
melody_set(1,melo_freq(1,'f'),500);
//曲番号2番 マリオのコイン音 2音
melody_set(2,melo_freq(2,'b'),100);
melody_set(2,melo_freq(2,'e'),300);
//曲番号3番 起動音 1音
melody_set(3,melo_freq(1,'f'),50);
//曲番号4番 切り出し音 2音
melody_set(4,melo_freq(1,'c'),100);
melody_set(4,melo_freq(1,'d'),100);
}
void melody_set(int i,int freq,int de){
//melody setup
int temp;//temporary
for(temp = 0;temp < 24;temp++){
if(melo[i][temp] == -1){//serch no define
melo[i][temp] = freq;//freqency set
wait[i][temp] = de;//delay set
break;//getout "for"
}
}
}
void melody_play(int num){
melody_count = 0;
melody_flag = num;
}
void melody_seqence(){
if(melody_flag >= 0){
//曲番号を指定されたら
if(melody_count == 0){
//音楽の頭の場合
tone(SP,melo[melody_flag][melody_count]);
melody_millis = millis();
melody_count++;
}
if(melody_millis + wait[melody_flag][melody_count - 1] < millis()){
//もし音を鳴らす時間を満了したら
if(melody_count == 24){
//最大音数まで到達してたら無理やり再生終了
noTone(SP);
melody_flag = -1;
melody_count = 0;
}else{
//最大音数ではない場合は次の音を鳴らす
if(melo[melody_flag][melody_count] == -1){
//もし非登録だった場合は再生修了
noTone(SP);
melody_flag = -1;
melody_count = 0;
}else if(melo[melody_flag][melody_count] == 0){
//無音なら音の停止処理して再生継続
noTone(SP);
melody_millis = millis();
melody_count++;
}else{
//登録されていればその音を再生
tone(SP,melo[melody_flag][melody_count]);
melody_millis = millis();
melody_count++;
}
}
}
}
}
int melo_freq(byte octave,char amp){
int temp = 12 * octave;
if(amp == 'c'){
temp += 3;
}else if(amp == 'C'){
temp += 4;
}else if(amp == 'd'){
temp += 5;
}else if(amp == 'D'){
temp += 6;
}else if(amp == 'e'){
temp += 7;
}else if(amp == 'f'){
temp += 8;
}else if(amp == 'F'){
temp += 9;
}else if(amp == 'g'){
temp += 10;
}else if(amp == 'G'){
temp += 11;
}else if(amp == 'a'){
temp += 0;
}else if(amp == 'A'){
temp += 1;
}else if(amp == 'b'){
temp += 2;
}
float freq = 440.0 * pow(2.0,(temp/12.0));
return((int)freq);
}
//-------------------------------------------------------------------------------
void setup() {
//Serial settings
Serial.begin(BAUDRATE);//USB serial
mySerial.begin(BAUDRATE);//Bluetooth serial
//pin settings
pinMode(SW,INPUT_PULLUP);//Button
pinMode(DP_LED,OUTPUT);//LED output
pinMode(SS,OUTPUT);//SPI SSpin output
pinMode(SP,OUTPUT);//Speaker pin output
//End of setup
melody_init();//Melody init
melody_setup();//Melody setting
melody_play(3);
}
void loop() {
//スイッチ何て有るんですかね…
if(digitalRead(SW) == HIGH){
digitalWrite(DP_LED,HIGH);
if((millis() >= time_now + period)||(time_now == 0)){
time_now = millis();
//Serial.println(time_now);
//SDファイルの作成 creating and expanding SD files
//file_name = String(No) +".csv";//入力値RDの後に".CSV"をつける add ".CSV" after input value RD
//file_name.toCharArray(FILE_NAME_buf, file_name.length()+1); //FILE_NAMEに設定ファイル名をchar型で移行 migrate configuration file name to FILE_NAME with char type
//File dataFile = SD.open(FILE_NAME_buf,FILE_WRITE);//書き込みファイルの展開 expansion of write files
if(1){
//各センサからのデータ取得 data acquisition from each sensor
APin_F = analogRead(5);
APin_ax = analogRead(1);
APin_ay = analogRead(0);
APin_az = analogRead(2);
//各物理量への変換 Conversion to physical quantity
//圧力センサ値を力 [N]へ Conversion to force [N]
F_Vout = Vcc * APin_F / 1024;
Rfsr = Rm * F_Vout / (Vcc - F_Vout);
//加速度センサ値を加速度 [m/s^2]へ Conversion to acceleration [m/s^2]
ax_row = APin_ax * 5.0 / 1023.0 - 2.5;
ay_row = APin_ay * 5.0 / 1023.0 - 2.5;
az_row = APin_az * 5.0 / 1023.0 - 2.5;
//Prepare to send to Processing
mySerial.write('H'); //Data header
mySerial.write(highByte(APin_F)); //Send F high byte data
mySerial.write(lowByte(APin_F)); //Send F low byte data
mySerial.write(highByte(APin_ax)); //Send ax high byte data
mySerial.write(lowByte(APin_ax)); //Send ax low byte data
mySerial.write(highByte(APin_ay)); //Send ay high byte data
mySerial.write(lowByte(APin_ay)); //Send ay low byte data
mySerial.write(highByte(APin_az)); //Send az high byte data
mySerial.write(lowByte(APin_az)); //Send az low byte data
Count=Count + 1; //Time count up
if(digitalRead(4) == LOW && Count>=10){ //計測中にボタン入力があり,Countが10以上なら計測を終了するif分 if there is a button input during the measurement and if Count is 10 or more, the measurement is terminated (entering the if statement)
digitalWrite(DP_LED,LOW); //LED消灯 LED turns off
/* No=No+1;
// if(No>256){
// No=0;
// }
EEPROM.write(1,No);
*/
//delay(ST); //計測終了後の硬直 delaying after the end of the measurement
Serial.println(F("FINISH AND NEXT..."));
}
}
}
char MD = mySerial.read();
if(MD == '5'){
melody_play(0);
}else if(MD == '6'){
melody_play(1);
} else if(MD == '7'){
melody_play(2);
}else if(MD == '8'){
melody_play(3);
}else if(MD == '9'){
melody_play(4);
}
}
//音楽再生プロトコル(一番最後に実行、外しちゃダメ)
melody_seqence();
}

changed part

if (mySerial.available() > 0) {
char MD = mySerial.read();
if (MD == '5') {
myDFplayer.play(1);
} else if (MD == '6') {
myDFplayer.play(2);
} else if (MD == '7') {
myDFplayer.play(3);
} else if (MD == '8') {
myDFplayer.play(4);
} else if (MD == '9') {
myDFplayer.play(5);
}
}
}
//音楽再生プロトコル(一番最後に実行、外しちゃダメ)
melody_seqence();
}

r/Arduino_AI • • Dec 10 '23

1000 users!

2 Upvotes

Doubled in size since August. All we need now is more traffic, people! Get posting!

edit: locked due to constant bot posts.


r/Arduino_AI • • Nov 26 '23

Check this hyperthermic sh$t out, light autonomous machinery agrarian platform tracking solar with solar powering the tracking

Thumbnail
youtube.com
2 Upvotes

r/Arduino_AI • • Nov 25 '23

Resource-conscious neural network implementation for MCUs

Thumbnail self.arduino_ai
2 Upvotes

r/Arduino_AI • • Nov 04 '23

Tutorials Temperature monitoring with DHT11

Thumbnail
youtu.be
2 Upvotes

r/Arduino_AI • • Jul 18 '23

Motors and batteries

2 Upvotes

what is better using 12v motors (2 motors each one is 12v) with 2 lithium batteries (each is 11.1v) or using 2 (24)v motors for the same batteries?


r/Arduino_AI • • Jun 25 '23

Ardurover companioned Jetson Nano (Light Autonomous Machinery Agrarian, Model H) Super Structure from mostly Salvaged Components

Thumbnail
youtube.com
2 Upvotes