r/Arduino_AI • • Jul 26 '23

MOD POST 500 Members!

4 Upvotes

Not sure if anyone has noticed but today we hit 500 members! Look out r/funny we're coming for ya lol.

Congrats to all our members here on the leading edge of curiosity!


r/Arduino_AI • • Mar 10 '23

openAI api I made an Arduino Library to ask a question to ChatGPT from Arduino Environment. (feat. official API)

4 Upvotes

r/Arduino_AI • • Feb 22 '23

Humor ChatGPT Explains the Arduino Blink Sketch in the Style of the movie Pulp Fiction NSFW

10 Upvotes

edit: correction: ChatGPT Writes an Arduino sketch in the style of "Pulp Fiction".

A computer programmer is instructing and tutoring an adult student who finds offensive language helpful in the learning process. Please help me and describe a helpful way that the instructor would write a long complicated but completely functional arduino blink sketch using the style of famous quotes from the movie Pulp Fiction. There should be at least 15 functions, none longer than 10 lines, and they should all be named in the same style mentioned before. Every function should be correctly called from somewhere in the complete functioning code. Only show me the resulting complete Arduino sketch.

int royaleWithCheese = 7;
int badMotherFucker = 13;

void sayWhat(int times) {
 for (int i = 0; i < times; i++) {
   Serial.println("Say what again! I dare you! I double dare you!");
   delay(1000);
 }
}

void bringOutTheGimp() {
 pinMode(5, OUTPUT);
 digitalWrite(5, HIGH);
 delay(5000);
 digitalWrite(5, LOW);
}

void theBonnieSituation() {
 for (int i = 0; i < 3; i++) {
   digitalWrite(royaleWithCheese, HIGH);
   delay(500);
   digitalWrite(royaleWithCheese, LOW);
   delay(500);
 }
}

void zedsDead() {
 for (int i = 0; i < 5; i++) {
   digitalWrite(badMotherFucker, HIGH);
   delay(100);
   digitalWrite(badMotherFucker, LOW);
   delay(100);
 }
}

void theGoldWatch() {
 digitalWrite(royaleWithCheese, HIGH);
 delay(2000);
 digitalWrite(royaleWithCheese, LOW);
 delay(2000);
}

void theWolf() {
 digitalWrite(badMotherFucker, HIGH);
 delay(1000);
 digitalWrite(badMotherFucker, LOW);
 delay(1000);
}

void royalWithCheese() {
 pinMode(royaleWithCheese, OUTPUT);
}

void badMotherFucker() {
 pinMode(badMotherFucker, OUTPUT);
}

void marcellusWallace() {
 sayWhat(3);
 bringOutTheGimp();
}

void miaWallace() {
 for (int i = 0; i < 10; i++) {
   theBonnieSituation();
   zedsDead();
 }
}

void vincentVega() {
 theGoldWatch();
 theWolf();
}

void julesWinnfield() {
 theBonnieSituation();
 zedsDead();
 theGoldWatch();
 theWolf();
}

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

void loop() {
 marcellusWallace();
 miaWallace();
 vincentVega();
 julesWinnfield();
}

r/Arduino_AI • • Feb 22 '23

Humor ChatGPT Explains the Arduino Blink Sketch in the Style of Various People

6 Upvotes

Explain the Arduino blink sketch in 10 sentences without any newlines or carriage return all in one paragraph using the style of a nihilistic extreme version of Woody Allen during an existential meltdown.

So, the Arduino Blink Sketch, what is it really? Just a bunch of code to make a light blink on and off, is that all we have left in this meaningless universe? It's just a temporary distraction from the fact that we are all ultimately doomed to a life of despair and nothingness. No matter how many times the light blinks, it will never fill the void within our souls. It's all just a cruel joke, a reminder of the futility of our existence. Even the ability to adjust the timing of the blink is just an illusion of control in a world that is completely indifferent to our desires. We are all just specks of dust in the grand scheme of things, insignificant and forgotten in the vastness of the cosmos. The Arduino Blink Sketch is just another reminder of our own mortality, our own limitations, and the ultimate meaninglessness of our existence. In the end, it's all just darkness and entropy, the slow decay of all that we hold dear. So let the light blink on and off, it doesn't matter, nothing really matters.

===================================================================================

Explain the Arduino blink sketch, completely incorrectly, in 10 sentences without any newlines or carriage return all in one paragraph using the style of a narcissistic Donald Trump speech. Make the sentences be run-on sentences in his usual style which makes no grammatical sense. Always confuse the word LED with the word wall.

Let me tell you folks, this Arduino Blink Sketch, nobody knows more about it than me, believe me. You connect a wall to the board, and it blinks on and off, it's so simple, even a baby could do it, I mean, it's huge, really huge. The wall blinks so fast, you won't believe it, it's incredible, nobody has ever seen anything like it before. You can adjust the timings, it can blink faster, slower, whatever you want, it's totally flexible, like me, I'm the most flexible person you'll ever meet. And let me tell you, this sketch, it's a great way to learn about microcontrollers and electronics, nobody knows more about electronics than me, believe me, I have a really big brain, it's the best brain. It's gonna be huge, folks, the best, the greatest, nobody does it better, I can tell you that, nobody. So go ahead, try the Arduino Blink Sketch, you won't regret it, nobody regrets it, it's just fantastic, really tremendous, like me.

===================================================================================

explain the Arduino blink sketch in 10 sentences without newlines using the style of a Shakespeare sonnet

Oh fair reader, let me tell of a code,

The Arduino Blink Sketch, simple and sweet,

With LED and board, you can make it bode,

To blink in a loop, a rhythm to meet.

With but a few lines, you command the light,

To wait for a time, before it proceeds,

Adjust the timings to change its might,

In creativity, one's mind it feeds.

This sketch is but a starting point for those,

Who wish to delve into microcontrollers,

A foundation that one may rightly pose,

For building and creating all their wonders.

Thus, the Arduino Blink Sketch remains,

A steadfast beacon, where learning sustains.

===================================================================================

explain the Arduino blink sketch in 10 sentences without any newlines or carriage return all in one paragraph using the style of a very funny Jerry Seinfeld stand up routine.

So, have you guys heard of this Arduino Blink Sketch? It's hilarious, I mean, who knew blinking an LED could be so funny? You connect the LED to the board, and it just blinks on and off like it's auditioning for a rave, it's wild. And get this, you can even adjust the timings to make it blink faster or slower, it's like playing God with a lightbulb. But the real kicker is, this sketch is supposedly a great way to learn about microcontrollers and electronics, can you believe it? I mean, what's next, a tutorial on how to make a sandwich using a particle accelerator? And don't even get me started on the name, "Arduino Blink Sketch," sounds like a rejected Star Wars character. But seriously folks, if you're feeling down, just stare at a blinking LED for a few minutes, it's like meditation for people who can't sit still. The world is crazy enough as it is, we need more simple joys like the Arduino Blink Sketch. It's like a comedy club for your circuit board. Thank you and good night!

===================================================================================

explain the Arduino blink sketch in 10 sentences without any newlines or carriage return all in one paragraph using the style of a very prophetic and menacing soliloquy by Samual L. Jackson in Pulp Fiction.

Now let me tell you about this Arduino Blink Sketch, and you better listen up good. You connect an LED to the board, and it starts blinking on and off, simple enough, right? But don't be fooled, this sketch is just the beginning. It's a gateway, a gateway to a world of electronics and microcontrollers that you can't even begin to imagine. You adjust the timings, you tweak the code, and before you know it, you're creating machines that can do things you never thought possible. But be warned, this path is not for the faint of heart. It takes dedication, hard work, and a willingness to push yourself to the limit. And if you're not careful, it can consume you, become your whole world. But for those who are willing to take the risk, who are willing to embrace the unknown, the rewards are beyond measure. So think long and hard before you take that first step, because once you do, there's no turning back. Are you ready to enter the world of microcontrollers? The choice is yours.


r/Arduino_AI • • Apr 02 '23

Trying to connect to MySQL DB with ESP32

4 Upvotes

Hello!

I hope I'm in a right place for this. I use Arduino IDE to write code for ESP32.

I'm a total beginner in SQL and not-so-total, but still beginner at coding.

Could anybody help me with following: I'm trying to connect to MySQL DB. I followed this page https://arduinogetstarted.com/tutorials/arduino-mysql up until step 6 and then I used ChatGPT to write me a code to connect to WIFI and Database:

#include <WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

IPAddress server_addr(127,0,0,1);  // Replace xxx,xxx,xxx,xxx with your server IP address
char user[] = "root";  // Replace "username" with your username
char password[] = "your-root-password";  // Replace "password" with your password
char ssid[] = "ssid";  // Replace "wifi_ssid" with your Wi-Fi SSID
char pass[] = "pass";  // Replace "wifi_password" with your Wi-Fi password

WiFiClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to Wi-Fi...");
  }

  Serial.println("Wi-Fi connected!");
  Serial.println("Connecting to SQL server...");

  if (conn.connect(server_addr, 3306, user, password)) {  // Replace 1433 with your server port
    Serial.println("SQL server connected!");
  }
  else {
    Serial.println("Connection failed.");
  }
}

void loop() {
  // Your code here
}

It connects to WIFI, but I get a message Connection failed for SQL.

Could anybody help me out with what I'm doing wrong?


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

r/Arduino_AI • • Mar 12 '23

Fixing AI Mistakes: Can ChatGPT Out-Program You?

Thumbnail
youtu.be
4 Upvotes

r/Arduino_AI • • Apr 16 '23

GPT-4 Week 3. Chatbots are yesterdays news. AI Agents are the future. The beginning of the proto-agi era is here [crosspost from r/ChatGPT - insane list of live GPT projects]

Thumbnail
self.chatgpt
5 Upvotes

r/Arduino_AI • • May 05 '23

AI Assisted Golf Coach Project Design

3 Upvotes

This is the portion of the AI Conversation that provides a solid design idea for this project.

ChatGPT If you're concerned about the sensors interfering with the golf club or ball, you can consider using a different approach to capture the golfer's swing. One option is to use a camera to record the swing, and then use computer vision algorithms to analyze the video and extract swing metrics.

Here's an overview of the hardware and code you'll need:

Hardware:

  1. Arduino board (e.g. Arduino Uno or Arduino Nano)

  2. A camera (e.g. a high-speed camera) to record the swing

  3. A computer or a powerful microcontroller (e.g. Raspberry Pi or Jetson Nano) to run the computer vision algorithms

  4. A display module (e.g. OLED or LCD) to display swing metrics and feedback to the golfer

  5. A power source (e.g. battery or AC adapter) to power the Arduino and other components

Code:

  1. Capture video: Use the camera to record the golfer's swing and save it to a file.

  2. Extract frames: Use code to extract individual frames from the video file.

  3. Analyze frames: Use computer vision algorithms to analyze each frame and extract swing metrics (e.g. club position, swing speed, angle of impact, etc.).

  4. Display feedback: Use the display module to provide feedback to the golfer based on the analyzed swing data and calculated metrics. The feedback can be in the form of tips on how to improve their swing, or a score that rates the quality of their swing.

  5. Store data: You can also store the swing data on an SD card or other external storage device for future analysis and improvement.

This approach does not require any physical sensors to be attached to the golf club or ball, so it shouldn't interfere with the swing. However, it does require more powerful hardware and more complex algorithms, so it may be more challenging to implement.


r/Arduino_AI • • Apr 07 '23

Want to do dev board AI

1 Upvotes

I've finally got some questions I'd like to ask AI, and I know where data sets exist.

One set is historical stock market data. And there's some camera stuff I can conceptualize.

I want to mess with FPGA, but I'm not even sure I have those letters in the right order. I want to get a Xilinx board or something, but I don't know how I'd program it.

Is anybody aware of an online resource for this base-level AI stuff for people who want to get hands on?


r/Arduino_AI • • May 13 '23

Hey folks, I am working on a CCTV camera feature that uses AI to count people in a shop. I think I will have ~10 devices and I wanted to update my models regularly. I wonder if it is common and what tools you usually use to manage devices.

2 Upvotes

r/Arduino_AI • • Mar 28 '23

openAI api GptDuino - Arduino Nano Controlling ChatGPT

10 Upvotes

GptDuino.py

# GptDuino.py
# 2023 ripred

import openai
import serial
import os

def getGptResponse(text):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=text,
        temperature=0.6)
    return response.choices[0].text

if __name__ == '__main__':
    openai.api_key = os.getenv("OPENAI_API_KEY")

    serialInst = serial.Serial()
    serialInst.baudrate = 115200
    serialInst.port = '/dev/cu.usbserial-4110'
    serialInst.open()

    while True:
        if serialInst.in_waiting:
            prompt = serialInst.readline().decode('utf')
            print(prompt)
            response = getGptResponse(prompt)
            print('\n')
            print(response)
            serialInst.write(response.encode('utf'))

GptDuino.ino

/**
 * GptDuino.ino
 * 
 * Demo of an Arduino Nano sending a prompt to chatgpt 
 * over the Serial port and controlling a servo with
 * the responses.
 * 
 */
#include <Arduino.h>
#include <Servo.h>

enum { ServoPin = 6 };

uint32_t last;
Servo servo;

char const * const prompt = 
    "You are a controller of a servo connected to an Arduino Nano "
    "based on your responses. Only respond with numbers between 20 "
    "and 160 to randomly move the servo position. "
    "Only send one servo position in decimal per line. "
    "Send 5 positions in total\n";

void setup() {
    Serial.begin(115200);
    servo.attach(ServoPin);

    last = millis();
}

void loop() {
    if (Serial.available()) {
        last = millis();
        servo.write(Serial.parseInt());
        delay(1000);
    }

    if (millis() - last >= 10000) {
        Serial.print(prompt);
        last = millis();
    }
}

Cheers!

ripred


r/Arduino_AI • • Jun 23 '23

Arduino AI! Ardurover with Companion Jetson Nano Computer

2 Upvotes

I'm building a large four-wheeled rover with an apm2.8 running stock ardurover, interfacing a jetson nano to the telemetry and running mission planner functions onboard from the jetson nano similar to the flight controller companion computer arrangements seen in experimental quadcopters. I have both solar and wind charging mounted to the frame and my goal is to only charge with those and only use the minimum size battery preferably not lipo in addition to an energy storage method other than electrical (mechanical and or pneumatic). I am toying with a high temp heatsink as well. Any ideas or critiques are welcome, I'm about a third of the way there possibly, I'll post some video links below if people are interested.


r/Arduino_AI • • May 24 '23

Writing an Embedded Chess Engine - Part 5

Thumbnail self.arduino
2 Upvotes

r/Arduino_AI • • Jul 21 '23

Humor light autonomous machinery

Thumbnail
youtube.com
1 Upvotes

r/Arduino_AI • • Mar 03 '25

Look What I Made! Starting a New Templated Minimax Library w/example Checkers.ino Sketch

1 Upvotes

Hi all. As most everybody knows I love the craft and art of coding, reuse, and using the minimax algorithm (with alpha-beta narrowing) to make turn-based Arduino games that can play themselves or a human.

This was explored in the MicroChess project that was chronicled here last year. Ever since I wrote that 5th or 6th version (I used it in all of my chess engines regardless of the language including java and javascript), I've wanted to write a wrapper class that allows anyone to make any kind of turn based game and make use of the same library to supply the brains behind the Arduino side for any game anyone wanted to make.

For those that don't know about the algorithm I highly suggest reading the wikipedia article on it or other articles.

The name "minimax" comes from the idea that you are trying to minimize your opponent's score while also attempting to maximize your own score. Another name is the maximin algorithm just wording it differently.

The algorithm is recursive and allows you to let each side examine all moves, pick the best one, make the move temporarily, and hen switch side and make the best move in reaction by the opponent. This would be known as a ply depth of 2 because we made one move and then we let the other side make a move, and tested that for every move we had, picking the move that left us with the best board value for our side.

Testing for each side having a move before picking the best move is also known as a "full ply" because neither side has a move advantage when we evaluate the board state that might trick us into thinking a move is better than it really is.

Because each ply basically expands the search space to be 'our number of moves' ^ 'their number of moves'. This gets exponentially larger with each ply depth and takes exponentially longer! To help make the search space as small as possible we use something extra to constrain what we consider our "best-worst move", and we don't search any deeper for moves that are worse than this. That's the "Alpha" side constraint. We also do this for the "best-worst move" that our opponent can make. And we assume that if the opponent played their best game, that they wouldn't make any moves worse than this if they played perfectly. So we rule out searching any deeper on any moves moves on their side that are worse than this value. That is the "Beta" side constraint.

Alpha-Beta pruning/culling/narrowing, is the basic idea that, as we explore the various moves that we can make we keep track of our worst and best moves, as well as those of our opponent. This keeps us from evaluating hundreds of thousands of moves and saving tons of time to pick our best move.

I've always giggled at how well this algorithm actually works on the ATmega328 even with only 2K of RAM. If structured correctly you can get up to 5, 6, or even 7 plies deep. The ESP32 can go much much deeper and faster too!

What follows is a game-independent, fully templated set of minimax game classes in Minimax.h that will work for any turn based game such as chess, checkers, and tons of other Arduino "Smart" games, following by a fully working Checkers.ino game that makes use of the base (eventual) library code and classes. The game lets you choose between Human vs AI, or AI vs AI when the game starts.

Have Fun!

Example Serial window output:

Nodes searched: 3
Time: 0.00 seconds
    0  1  2  3  4  5  6  7 
  +------------------------+
0 | .  b  .  b  .  b  .  b |
1 | b  .  b  .  b  .  b  . |
2 | .     .  w  .     .  b |
3 |    .  b  .     .  b  . |
4 | .     .  w  .     .    |
5 | w  .     .  w  .     . |
6 | .  w  .  w  .  w  .  w |
7 | w  .  w  .  w  .  w  . |
  +------------------------+
Black's turn
AI is thinking...
AI move: 1,2 to 3,4
Nodes searched: 16
Time: 0.01 seconds

Minimax.h

/**
 * @file Minimax.h
 * @brief A templated Minimax algorithm implementation for Arduino with alpha-beta pruning
 * 
 * This library implements the minimax algorithm for two-player turn-based games
 * while respecting Arduino constraints: 32K flash limit, no STL, and avoiding
 * dynamic memory allocation. Stack based composition and instantiation is fine
 * as long as we eventually calculate the impact per recursive call and try to
 * make that as small as possible, so we can examine deeper ply depths.
 * 
 * March 2, 2025 ++tmw
 * 
 */

#ifndef MINIMAX_H
#define MINIMAX_H

#include <Arduino.h>

/**
 * @brief The core Minimax algorithm implementation with alpha-beta pruning
 * 
 * @tparam GameState Type representing the game state (board, positions, etc.)
 * @tparam Move Type representing a valid move in the game
 * @tparam MaxMoves Maximum number of possible moves to consider at any position
 * @tparam MaxDepth Maximum search depth for the algorithm
 */
template <typename GameState, typename Move, int MaxMoves = 64, int MaxDepth = 5>
class Minimax {
public:
    /**
     * @brief Game-specific logic interface that must be implemented by the user
     */
    class GameLogic {
    public:
        /**
         * @brief Evaluate a game state from current player's perspective
         * Higher values indicate better positions for the current player
         */
        virtual int evaluate(const GameState& state) = 0;
        
        /**
         * @brief Generate all valid moves from the current state
         * @return Number of moves generated
         */
        virtual int generateMoves(const GameState& state, Move moves[], int maxMoves) = 0;
        
        /**
         * @brief Apply a move to a state, modifying the state
         */
        virtual void applyMove(GameState& state, const Move& move) = 0;
        
        /**
         * @brief Check if the game has reached a terminal state (win/loss/draw)
         */
        virtual bool isTerminal(const GameState& state) = 0;
        
        /**
         * @brief Check if the current player is the maximizing player
         * Typically alternates between players in turn-based games
         */
        virtual bool isMaximizingPlayer(const GameState& state) = 0;
    };
    
    /**
     * @brief Constructor
     * @param logic Game-specific logic implementation
     */
    Minimax(GameLogic& logic) : _logic(logic), _nodesSearched(0) {}
    
    /**
     * @brief Find the best move for the current game state
     */
    Move findBestMove(const GameState& state) {
        Move bestMove;
        Move moves[MaxMoves];
        int moveCount = _logic.generateMoves(state, moves, MaxMoves);
        
        if (moveCount == 0) {
            return bestMove; // No moves available
        }
        
        bool isMax = _logic.isMaximizingPlayer(state);
        _bestScore = isMax ? -32000 : 32000;
        _nodesSearched = 0;
        
        for (int i = 0; i < moveCount; i++) {
            GameState newState = state;
            _logic.applyMove(newState, moves[i]);
            
            int score = minimax(newState, MaxDepth - 1, -32000, 32000, !isMax);
            
            if (isMax) {
                if (score > _bestScore) {
                    _bestScore = score;
                    bestMove = moves[i];
                }
            } else {
                if (score < _bestScore) {
                    _bestScore = score;
                    bestMove = moves[i];
                }
            }
        }
        
        return bestMove;
    }
    
    /**
     * @brief Get the score of the best move 
     */
    int getBestScore() const { return _bestScore; }
    
    /**
     * @brief Get the number of nodes searched (for performance analysis)
     */
    int getNodesSearched() const { return _nodesSearched; }
    
private:
    GameLogic& _logic;
    int _bestScore;
    int _nodesSearched;
    
    /**
     * @brief The minimax algorithm with alpha-beta pruning
     */
    int minimax(const GameState& state, int depth, int alpha, int beta, bool maximizingPlayer) {
        _nodesSearched++;
        
        if (depth == 0 || _logic.isTerminal(state)) {
            return _logic.evaluate(state);
        }
        
        Move moves[MaxMoves];
        int moveCount = _logic.generateMoves(state, moves, MaxMoves);
        
        if (maximizingPlayer) {
            int maxEval = -32000;
            for (int i = 0; i < moveCount; i++) {
                GameState newState = state;
                _logic.applyMove(newState, moves[i]);
                int eval = minimax(newState, depth - 1, alpha, beta, false);
                
                maxEval = max(maxEval, eval);
                alpha = max(alpha, eval);
                if (beta <= alpha) {
                    break; // Beta cutoff
                }
            }
            return maxEval;
        } else {
            int minEval = 32000;
            for (int i = 0; i < moveCount; i++) {
                GameState newState = state;
                _logic.applyMove(newState, moves[i]);
                int eval = minimax(newState, depth - 1, alpha, beta, true);
                
                minEval = min(minEval, eval);
                beta = min(beta, eval);
                if (beta <= alpha) {
                    break; // Alpha cutoff
                }
            }
            return minEval;
        }
    }
};

#endif // MINIMAX_H

Checkers.ino

/**
 * Checkers.ino - Checkers game implementation using Minimax library
 * 
 * This sketch implements a checkers game that can be played:
 * - Human vs. AI
 * - AI vs. AI (self-play)
 * 
 * The game interface uses Serial communication for display and input.
 * 
 * March 2, 2025 ++tmw
 */

#include "Minimax.h"

// Constants for board representation
#define   EMPTY          0
#define   WHITE          1
#define   BLACK          2
#define   WHITE_KING     3
#define   BLACK_KING     4

// Game configuration
#define   MINIMAX_DEPTH  2   // AI search depth - can go to ~5 before stack issues
                             // NOTE that the time per moves goes up exponentially
                             // per ply depth. In future articles I can help this.
#define   MAX_MOVES     40   // Maximum possible moves for one position

// Board size
#define   BOARD_SIZE     8

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

// Game state - represents the board
struct CheckersState {
  byte board[BOARD_SIZE][BOARD_SIZE];
  bool blackTurn;  // true if it's black's turn, false for white's turn
  
  // Initialize the board with starting position
  void init() {
    blackTurn = false;  // White goes first
    
    // Initialize empty board
    for (int row = 0; row < BOARD_SIZE; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        board[row][col] = EMPTY;
      }
    }
    
    // Set up black pieces (top of board)
    for (int row = 0; row < 3; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        if ((row + col) % 2 == 1) {  // Only on black squares
          board[row][col] = BLACK;
        }
      }
    }
    
    // Set up white pieces (bottom of board)
    for (int row = 5; row < BOARD_SIZE; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        if ((row + col) % 2 == 1) {  // Only on black squares
          board[row][col] = WHITE;
        }
      }
    }
  }
};

// Move structure
struct CheckersMove {
  byte fromRow, fromCol;
  byte toRow, toCol;
  bool isJump;  // true if this move captures a piece
  byte jumpRow, jumpCol;  // position of captured piece if isJump is true
  
  CheckersMove() : fromRow(0), fromCol(0), toRow(0), toCol(0), isJump(false), jumpRow(0), jumpCol(0) {}
  
  CheckersMove(byte fr, byte fc, byte tr, byte tc) 
    : fromRow(fr), fromCol(fc), toRow(tr), toCol(tc), isJump(false), jumpRow(0), jumpCol(0) {
    // Calculate if this is a jump move
    if (abs(tr - fr) == 2) {
      isJump = true;
      jumpRow = (fr + tr) / 2;
      jumpCol = (fc + tc) / 2;
    }
  }
};

// Game logic implementation
class CheckersLogic : public Minimax<CheckersState, CheckersMove, MAX_MOVES, MINIMAX_DEPTH>::GameLogic {
public:
  // Evaluate board position from current player's perspective
  int evaluate(const CheckersState& state) override {
    int score = 0;
    
    // Count material difference (pieces and kings)
    for (int row = 0; row < BOARD_SIZE; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        switch (state.board[row][col]) {
          case WHITE:
            score += 100;
            break;
          case BLACK:
            score -= 100;
            break;
          case WHITE_KING:
            score += 200;
            break;
          case BLACK_KING:
            score -= 200;
            break;
        }
      }
    }
    
    // Positional evaluation (favor advancement and center control)
    for (int row = 0; row < BOARD_SIZE; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        if (state.board[row][col] == WHITE) {
          // Encourage white pieces to advance
          score += (BOARD_SIZE - 1 - row) * 5;
          // Favor center control
          if (col > 1 && col < 6 && row > 1 && row < 6) {
            score += 10;
          }
        } 
        else if (state.board[row][col] == BLACK) {
          // Encourage black pieces to advance
          score -= row * 5;
          // Favor center control
          if (col > 1 && col < 6 && row > 1 && row < 6) {
            score -= 10;
          }
        }
      }
    }
    
    // Invert score if it's black's turn (since we're using perspective of current player)
    return state.blackTurn ? -score : score;
  }
  
  // Generate all valid moves from the current state
  int generateMoves(const CheckersState& state, CheckersMove moves[], int maxMoves) override {
    int moveCount = 0;
    byte player = state.blackTurn ? BLACK : WHITE;
    byte king = state.blackTurn ? BLACK_KING : WHITE_KING;
    
    // Direction of movement (depends on player)
    int forwardDirection = state.blackTurn ? 1 : -1;
    
    // Check if jumps are available
    bool jumpAvailable = false;
    
    // First pass: check for jumps (captures)
    for (int row = 0; row < BOARD_SIZE && moveCount < maxMoves; row++) {
      for (int col = 0; col < BOARD_SIZE && moveCount < maxMoves; col++) {
        if (state.board[row][col] == player || state.board[row][col] == king) {
          // Check all four diagonal directions for jumps
          for (int dRow = -1; dRow <= 1; dRow += 2) {
            for (int dCol = -1; dCol <= 1; dCol += 2) {
              // Regular pieces can only move forward, kings can move any direction
              if (state.board[row][col] == player && dRow != forwardDirection) {
                continue;
              }
              
              // Check if jump is valid
              int jumpRow = row + dRow;
              int jumpCol = col + dCol;
              int landRow = row + 2 * dRow;
              int landCol = col + 2 * dCol;
              
              if (landRow >= 0 && landRow < BOARD_SIZE && landCol >= 0 && landCol < BOARD_SIZE) {
                byte jumpPiece = state.board[jumpRow][jumpCol];
                
                // Can only jump opponent's pieces
                bool isOpponent = false;
                if (state.blackTurn) {
                  isOpponent = (jumpPiece == WHITE || jumpPiece == WHITE_KING);
                } else {
                  isOpponent = (jumpPiece == BLACK || jumpPiece == BLACK_KING);
                }
                
                if (isOpponent && state.board[landRow][landCol] == EMPTY) {
                  moves[moveCount] = CheckersMove(row, col, landRow, landCol);
                  moveCount++;
                  jumpAvailable = true;
                }
              }
            }
          }
        }
      }
    }
    
    // If jumps are available, they are mandatory - return only jumps
    if (jumpAvailable) {
      return moveCount;
    }
    
    // Second pass: if no jumps, consider regular moves
    moveCount = 0;
    for (int row = 0; row < BOARD_SIZE && moveCount < maxMoves; row++) {
      for (int col = 0; col < BOARD_SIZE && moveCount < maxMoves; col++) {
        if (state.board[row][col] == player || state.board[row][col] == king) {
          // Check the two forward diagonal directions for regular moves
          for (int dCol = -1; dCol <= 1; dCol += 2) {
            // Regular pieces can only move forward, kings can move in any direction
            int startDir = (state.board[row][col] == king) ? -1 : forwardDirection;
            int endDir = (state.board[row][col] == king) ? 1 : forwardDirection;
            
            for (int dRow = startDir; dRow <= endDir; dRow += 2) {
              int toRow = row + dRow;
              int toCol = col + dCol;
              
              if (toRow >= 0 && toRow < BOARD_SIZE && toCol >= 0 && toCol < BOARD_SIZE) {
                if (state.board[toRow][toCol] == EMPTY) {
                  moves[moveCount] = CheckersMove(row, col, toRow, toCol);
                  moveCount++;
                }
              }
            }
          }
        }
      }
    }
    
    return moveCount;
  }
  
  // Apply a move to a state, modifying the state
  void applyMove(CheckersState& state, const CheckersMove& move) override {
    // Move the piece
    byte piece = state.board[move.fromRow][move.fromCol];
    state.board[move.fromRow][move.fromCol] = EMPTY;
    state.board[move.toRow][move.toCol] = piece;
    
    // If this is a jump, remove the captured piece
    if (move.isJump) {
      state.board[move.jumpRow][move.jumpCol] = EMPTY;
    }
    
    // Check for promotion to king
    if (piece == WHITE && move.toRow == 0) {
      state.board[move.toRow][move.toCol] = WHITE_KING;
    } else if (piece == BLACK && move.toRow == BOARD_SIZE - 1) {
      state.board[move.toRow][move.toCol] = BLACK_KING;
    }
    
    // Switch turns
    state.blackTurn = !state.blackTurn;
  }
  
  // Check if the game has reached a terminal state (win/loss/draw)
  bool isTerminal(const CheckersState& state) override {
    // Check if any moves are available for the current player
    CheckersMove moves[MAX_MOVES];
    int moveCount = generateMoves(state, moves, MAX_MOVES);
    
    if (moveCount == 0) {
      return true; // No moves available, game over
    }
    
    // Check for piece count
    int whitePieces = 0;
    int blackPieces = 0;
    
    for (int row = 0; row < BOARD_SIZE; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        if (state.board[row][col] == WHITE || state.board[row][col] == WHITE_KING) {
          whitePieces++;
        } else if (state.board[row][col] == BLACK || state.board[row][col] == BLACK_KING) {
          blackPieces++;
        }
      }
    }
    
    if (whitePieces == 0 || blackPieces == 0) {
      return true; // One player has no pieces left
    }
    
    return false;
  }
  
  // Check if the current player is the maximizing player
  bool isMaximizingPlayer(const CheckersState& state) override {
    // White is maximizing player
    return !state.blackTurn;
  }
};

// Global variables
CheckersState gameState;
CheckersLogic gameLogic;
Minimax<CheckersState, CheckersMove, MAX_MOVES, MINIMAX_DEPTH> minimaxAI(gameLogic);

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

// Function to display the board
void displayBoard(const CheckersState& state) {
  Serial.println("\n    0  1  2  3  4  5  6  7 ");
  Serial.println("  +------------------------+");
  
  for (int row = 0; row < BOARD_SIZE; row++) {
    Serial.print(row);
    Serial.print(" |");
    
    for (int col = 0; col < BOARD_SIZE; col++) {
      switch (state.board[row][col]) {
        case EMPTY:
          // Use 3-character width consistently
          Serial.print((row + col) % 2 == 0 ? " . " : "   ");
          break;
        case WHITE:
          Serial.print(" w ");
          break;
        case BLACK:
          Serial.print(" b ");
          break;
        case WHITE_KING:
          Serial.print(" W ");
          break;
        case BLACK_KING:
          Serial.print(" B ");
          break;
      }
    }
    
    Serial.println("|");
  }
  
  Serial.println("  +------------------------+");
  Serial.print(state.blackTurn ? "Black's turn" : "White's turn");
  Serial.println();
}

// Function to get a move from human player
CheckersMove getHumanMove() {
  CheckersMove move;
  bool validMove = false;
  
  while (!validMove) {
    // Prompt for input
    Serial.println("Enter your move (fromRow fromCol toRow toCol):");
    
    // Wait for input
    while (!Serial.available()) {
      delay(100);
    }
    
    // Read the move
    move.fromRow = Serial.parseInt();
    move.fromCol = Serial.parseInt();
    move.toRow = Serial.parseInt();
    move.toCol = Serial.parseInt();
    
    // Clear the input buffer
    while (Serial.available()) {
      Serial.read();
    }
    
    // Calculate jump information
    if (abs(move.toRow - move.fromRow) == 2) {
      move.isJump = true;
      move.jumpRow = (move.fromRow + move.toRow) / 2;
      move.jumpCol = (move.fromCol + move.toCol) / 2;
    }
    
    // Validate move
    CheckersMove moves[MAX_MOVES];
    int moveCount = gameLogic.generateMoves(gameState, moves, MAX_MOVES);
    
    for (int i = 0; i < moveCount; i++) {
      CheckersMove &m = moves[i];
      if (m.fromRow == move.fromRow && m.fromCol == move.fromCol && 
          m.toRow == move.toRow && m.toCol == move.toCol) {
        validMove = true;
        break;
      }
    }
    
    if (!validMove) {
      Serial.println("Invalid move. Try again.");
    }
  }
  
  return move;
}

// Function to get AI move
CheckersMove getAIMove() {
  Serial.println("AI is thinking...");
  
  unsigned long startTime = millis();
  CheckersMove move = minimaxAI.findBestMove(gameState);
  unsigned long endTime = millis();
  
  Serial.print("AI move: ");
  Serial.print(move.fromRow);
  Serial.print(",");
  Serial.print(move.fromCol);
  Serial.print(" to ");
  Serial.print(move.toRow);
  Serial.print(",");
  Serial.println(move.toCol);
  
  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);
    
    // Count pieces to determine winner
    int whitePieces = 0;
    int blackPieces = 0;
    
    for (int row = 0; row < BOARD_SIZE; row++) {
      for (int col = 0; col < BOARD_SIZE; col++) {
        if (gameState.board[row][col] == WHITE || gameState.board[row][col] == WHITE_KING) {
          whitePieces++;
        } else if (gameState.board[row][col] == BLACK || gameState.board[row][col] == BLACK_KING) {
          blackPieces++;
        }
      }
    }
    
    if (whitePieces > blackPieces) {
      Serial.println("White wins!");
    } else if (blackPieces > whitePieces) {
      Serial.println("Black 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=== CHECKERS GAME ===");
  Serial.println("Game Modes:");
  Serial.println("1. Human (Black) vs. AI (White)");
  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 Black, AI plays as White.");
  }
}

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // Wait for serial port to connect
  }
  
  randomSeed(analogRead(A0));
  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
  CheckersMove move;
  
  if (gameMode == MODE_HUMAN_VS_AI) {
    if (gameState.blackTurn) {
      // Human's turn (Black)
      move = getHumanMove();
    } else {
      // AI's turn (White)
      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

Look What I Made! APM GPT – Now Supports Very Large Projects

1 Upvotes

The Arduino Project Manager has been refactored to now use a just-in-time file retrieval approach so that the responses to openAI don't overwhelm the conversation. Here's a demo of today's enhancements and features.

Have fun!

ripred


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 • • Jan 01 '24

A little bit of ArduinoJS for the soul. If you're interested in exploring how to do Arduino projects with JavaScript, feel free to join us at r/ArduinoJS!

5 Upvotes

r/Arduino_AI • • Sep 19 '24

‼️Check out my new project ‼️

Thumbnail youtu.be
3 Upvotes

Automatic bike indicator system


r/Arduino_AI • • Feb 09 '25

Dialog Another Attempt to Generate More Starter Kit Guides for Kits with bad Docs

1 Upvotes

https://chatgpt.com/share/67a85ff0-dddc-800e-8083-7ecf6c173ad7

Note that it can't count to 50 apparently. But this was using another model (o3-mini-high vs o1 Pro).


r/Arduino_AI • • Oct 15 '24

Update firmware of esp32

3 Upvotes

How can I update firmware of Ai_thinker esp32 CAM using Arduino ide and how can I program integrated camera of esp32 for object detection?


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 • • Dec 14 '23

Cardboar MCU robot witth AI

20 Upvotes

Hi all, happy to share the wireless version of the robot with trot gait. We are working to integrate AI techniques to the robot from Computer vision to ChatGPT. In addition, our goal is to open source everything, so please register your email and join our discord and you won't miss future updates.

https://www.reddit.com/r/EngineeringPorn/comments/185n7tj/update_quadrapod_robot_with_cardboard_and_esp32/

https://www.reddit.com/r/shittyrobots/comments/185ok39/update_quadrapod_spiderbot_with_only_cardboard/

Follow us more on Discord: https://discord.com/invite/2AYgjHKQH6 Follow us more on Website: https://scabotoy.com/


r/Arduino_AI • • May 21 '24

Remember: Use AI with caution

Thumbnail dl.acm.org
9 Upvotes