0% found this document useful (0 votes)
3 views26 pages

Code Mikro WIFI

The document is a C program for controlling an ESP8266 Wi-Fi module and a traffic light system. It includes constants, global variables, interrupt handlers, and functions for communication with the ESP8266, as well as traffic light control logic. The program allows for mode changes, timing adjustments, and LED state updates based on received commands and button presses.

Uploaded by

Trịnh Hòa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

Code Mikro WIFI

The document is a C program for controlling an ESP8266 Wi-Fi module and a traffic light system. It includes constants, global variables, interrupt handlers, and functions for communication with the ESP8266, as well as traffic light control logic. The program allows for mode changes, timing adjustments, and LED state updates based on received commands and button presses.

Uploaded by

Trịnh Hòa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

#include <stdbool.

h>

#include <stdint.h>

#include <stdio.h>

#include <string.h>

// ===== CONSTANTS =====

// ESP8266 Constants

#define ESP8266_STATION 0x01

#define ESP8266_SOFTAP 0x02

#define ESP8266_BOTH 0x03

#define ESP8266_TCP 1

#define ESP8266_UDP 0

#define ESP8266_TRANS_PASS 1

#define ESP8266_TRANS_NOR 0

#define ESP8266_OK 1

#define ESP8266_READY 2

#define ESP8266_FAIL 3

#define ESP8266_NOCHANGE 4

#define ESP8266_LINKED 5

#define ESP8266_UNLINK 6

#define ESP8266_CONNECT 7

// ===== GLOBAL VARIABLES =====

unsigned char TransmitData, ReceiveData;

bit transmit_flag, receive_flag;


unsigned int mode = 3; // Default is mode 3 (automatic)

unsigned char isChangedMode = 0; // Flag for mode change

unsigned char currentLedState = 0; // Current LED state: 0-off, 1-green, 2-


yellow, 3-red

unsigned char lastLedState = 0; // Previous LED state

unsigned char TimeMode = 'N'; // Time mode: 'N'-day, 'T'-night

unsigned char specialCommandReceived = 0;// Special command received


flag

// Default timing settings

unsigned int green_time = 10000; // Green light duration: 10 seconds

unsigned int yellow_time = 3000; // Yellow light duration: 3 seconds

unsigned int red_time = 5000; // Red light duration: 5 seconds

// Variables for handling UART transmission from interrupts

unsigned char esp8266_tx_buffer[10]; // Buffer for characters to be sent


from interrupt

unsigned char esp8266_tx_count = 0; // Count of characters in buffer

unsigned char esp8266_tx_flag = 0; // Flag to indicate buffer has data

// ===== FORWARD DECLARATIONS =====

void _esp8266_putch(char bt);

// ===== INTERRUPT HANDLER =====

// Interrupt routine for button press and UART receive

void interrupt(void)

if((RCIE_bit == 1) && (RCIF_bit == 1))


{

RCIF_bit = 0;

ReceiveData = UART1_Read();

receive_flag = 1;

// RB0 button - Switch to mode 1 (red light)

if (INT0IF_bit)

mode = 1;

isChangedMode = 1;

// Queue the data instead of direct transmission

esp8266_tx_buffer[esp8266_tx_count] = 'A';

esp8266_tx_count++;

esp8266_tx_flag = 1;

INT0IF_bit = 0; // Clear interrupt flag

// RB1 button - Switch to mode 2 (blinking yellow)

else if (INT1IF_bit)

mode = 2;

isChangedMode = 1;

// Queue the data instead of direct transmission

esp8266_tx_buffer[esp8266_tx_count] = 'B';

esp8266_tx_count++;

esp8266_tx_flag = 1;

INT1IF_bit = 0; // Clear interrupt flag


}

// RB2 button - Switch to mode 3 (automatic)

else if (INT2IF_bit)

mode = 3;

isChangedMode = 1;

// Queue the data instead of direct transmission

esp8266_tx_buffer[esp8266_tx_count] = 'C';

esp8266_tx_count++;

esp8266_tx_flag = 1;

INT2IF_bit = 0; // Clear interrupt flag

// Process any queued ESP8266 transmissions

void Process_ESP8266_TX_Queue()

if (esp8266_tx_flag) {

unsigned char i;

for (i = 0; i < esp8266_tx_count; i++) {

_esp8266_putch(esp8266_tx_buffer[i]);

esp8266_tx_count = 0;

esp8266_tx_flag = 0;

}
// ===== ESP8266 COMMUNICATION FUNCTIONS =====

// UART send

void _esp8266_putch(char bt)

while(!TXIF_bit);

TXREG = bt;

// UART receive

char _esp8266_getch()

if(OERR_bit)

CREN_bit = 0;

CREN_bit = 1;

while(!RCIF_bit);

return RCREG;

// Send string via UART

void ESP8266_send_string(char* st_pt)

while(*st_pt)

_esp8266_putch(*st_pt++);

}
}

// Print string

void _esp8266_print(unsigned char *ptr)

while (*ptr != 0)

_esp8266_putch(*ptr++);

// Wait for string response

inline uint16_t _esp8266_waitFor(unsigned char *string)

unsigned char so_far = 0;

unsigned char received;

uint16_t counter = 0;

do

received = _esp8266_getch();

counter++;

if (received == string[so_far])

so_far++;

else

{
so_far = 0;

while (string[so_far] != 0);

return counter;

// ===== ESP8266 COMMAND FUNCTIONS =====

// Restart module

void esp8266_restart(void)

_esp8266_print("AT+RST\r\n");

_esp8266_waitFor("OK");

_esp8266_waitFor("ready");

// Check if module started

void esp8266_isStarted(void)

_esp8266_print("AT\r\n");

_esp8266_waitFor("OK");

// Enable/disable echo

void esp8266_echoCmds(bool echo)

_esp8266_print("ATE");
if (echo)

_esp8266_putch('1');

else

_esp8266_putch('0');

_esp8266_print("\r\n");

_esp8266_waitFor("OK");

// Set WiFi mode

void esp8266_mode(unsigned char mode)

_esp8266_print("AT+CWMODE=");

_esp8266_putch(mode + '0');

_esp8266_print("\r\n");

_esp8266_waitFor("OK");

// Set transmission mode

void esp8266_trans_mode(unsigned char mode)

_esp8266_print("AT+CIPMODE=");

_esp8266_putch(mode + '0');

_esp8266_print("\r\n");

_esp8266_waitFor("OK");

// Connect to AP
void esp8266_connect(unsigned char* ssid, unsigned char* pass)

_esp8266_print("AT+CWJAP=\"");

_esp8266_print(ssid);

_esp8266_print("\",\"");

_esp8266_print(pass);

_esp8266_print("\"\r\n");

_esp8266_waitFor("OK");

// Start TCP/UDP

void esp8266_start(unsigned char protocol, unsigned char* ip, unsigned int


port)

unsigned char port_str[5] = "\0\0\0\0";

_esp8266_print("AT+CIPSTART=\"");

if (protocol == ESP8266_TCP)

_esp8266_print("TCP");

else

_esp8266_print("UDP");

_esp8266_print("\",\"");

_esp8266_print(ip);

_esp8266_print("\",");

sprintf(port_str, "%u", port);

_esp8266_print(port_str);

_esp8266_print("\r\n");

_esp8266_waitFor("OK");
}

// Send data

void esp8266_send(void)

_esp8266_print("AT+CIPSEND\r\n");

_esp8266_waitFor("OK");

while (_esp8266_getch() != '>');

// Receive data

void esp8266_receive(unsigned char* store_in)

unsigned char length = 0;

unsigned char i;

unsigned char received;

_esp8266_waitFor("+IPD,");

do

received = _esp8266_getch();

if(received == ':') break;

length = length * 10 + (received - '0');

while (received >= '0' && received <= '9');

for (i = 0; i < length; i++)


{

store_in[i] = _esp8266_getch();

// Disconnect

void esp8266_disconnect(void)

_esp8266_print("AT+CWQAP\r\n");

_esp8266_waitFor("OK");

// Stop send mode

void esp8266_stop_send(void)

_esp8266_print("+++");

delay_ms(2000);

// Delete TCP

void esp8266_del_TCP(void)

_esp8266_print("AT+CIPCLOSE\r\n");

_esp8266_waitFor("OK");

// ===== TRAFFIC LIGHT CONTROL FUNCTIONS =====


// Control LED function

void Control_LED(unsigned char state)

LATE &= 0xF8; // Clear the 3 lower bits of LATE

// Control LED state

switch(state)

case 0: LATE0_bit = 0; LATE1_bit = 0; LATE2_bit = 0; break;//led off

case 1: LATE0_bit = 0; LATE1_bit = 0; LATE2_bit = 1; break;//led green


(RE2)

case 2: LATE0_bit = 0; LATE1_bit = 1; LATE2_bit = 0; break;//led yellow


(RE1)

case 3: LATE0_bit = 1; LATE1_bit = 0; LATE2_bit = 0; break;//led red (RE0)

default: break;

currentLedState = state; // Update LED state

// Update LED status via UART/WiFi

void Update_LED_Status()

// Only send when LED state changes

if (currentLedState != lastLedState)

// LED state character codes: 0-off(I), 1-green(D), 2-yellow(B), 3-red(A)


static const char LED_CODES[] = {'I', 'D', 'B', 'A'};

// Queue LED status update instead of sending directly

esp8266_tx_buffer[esp8266_tx_count] = LED_CODES[currentLedState];

esp8266_tx_count++;

esp8266_tx_flag = 1;

lastLedState = currentLedState;

// Configure buttons

void Configure_Buttons(unsigned char enable)

// enable = 1: enable buttons, enable = 0: disable buttons

TRISB0_bit = enable; // Mode 1 button

TRISB1_bit = enable; // Mode 2 button

TRISB2_bit = enable; // Mode 3 button

// Process received data from WiFi

void Process_Received_Data()

if (receive_flag)

receive_flag = 0;

specialCommandReceived = 0; // Reset special command flag


// Process mode change commands

if(ReceiveData == '@')

mode = 1;

isChangedMode = 1;

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'A';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == '#')

mode = 2;

isChangedMode = 1;

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'B';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == '$')

mode = 3;

isChangedMode = 1;
// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'C';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == 'F')

specialCommandReceived = 1;

Configure_Buttons(0);

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'F';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == 'O')

specialCommandReceived = 1;

Configure_Buttons(1);

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'O';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == 'N')

{
specialCommandReceived = 1; // Mark as special command

TimeMode = 'N'; // Switch to day mode

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'N';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == 'T')

specialCommandReceived = 1; // Mark as special command

TimeMode = 'T'; // Switch to night mode

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = 'T';

esp8266_tx_count++;

esp8266_tx_flag = 1;

else if(ReceiveData == 'Z')

GIE_bit = 0;

esp8266_stop_send();

esp8266_trans_mode(ESP8266_TRANS_NOR);

esp8266_del_TCP();

// Process green light timing (3-10s)

else if(ReceiveData >= 'a' && ReceiveData <= 'h')


{

isChangedMode = 1; // Mark as special command

switch(ReceiveData)

case 'a': green_time = 3000; break; // 3 seconds

case 'b': green_time = 4000; break; // 4 seconds

case 'c': green_time = 5000; break; // 5 seconds

case 'd': green_time = 6000; break; // 6 seconds

case 'e': green_time = 7000; break; // 7 seconds

case 'f': green_time = 8000; break; // 8 seconds

case 'g': green_time = 9000; break; // 9 seconds

case 'h': green_time = 10000; break; // 10 seconds

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = ReceiveData;

esp8266_tx_count++;

esp8266_tx_flag = 1;

// Process yellow light timing (3-10s)

else if(ReceiveData >= 'j' && ReceiveData <= 'p')

isChangedMode = 1; // Mark as special command

switch(ReceiveData)

case 'j': yellow_time = 3000; break; // 3 seconds

case 'k': yellow_time = 4000; break; // 4 seconds


case 'l': yellow_time = 5000; break; // 5 seconds

case 'm': yellow_time = 6000; break; // 6 seconds

case 'n': yellow_time = 7000; break; // 7 seconds

case 'o': yellow_time = 8000; break; // 8 seconds

case 'p': yellow_time = 9000; break; // 9 seconds

case 'i': yellow_time = 10000; break; // 10 seconds

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = ReceiveData;

esp8266_tx_count++;

esp8266_tx_flag = 1;

// Process red light timing (3-10s)

else if(ReceiveData >= 'q' && ReceiveData <= 'x')

isChangedMode = 1; // Mark as special command

switch(ReceiveData)

case 'q': red_time = 3000; break; // 3 seconds

case 'r': red_time = 4000; break; // 4 seconds

case 's': red_time = 5000; break; // 5 seconds

case 't': red_time = 6000; break; // 6 seconds

case 'u': red_time = 7000; break; // 7 seconds

case 'v': red_time = 8000; break; // 8 seconds

case 'w': red_time = 9000; break; // 9 seconds

case 'x': red_time = 10000; break; // 10 seconds


}

// Queue response instead of direct send

esp8266_tx_buffer[esp8266_tx_count] = ReceiveData;

esp8266_tx_count++;

esp8266_tx_flag = 1;

// Special commands don't change mode

if(specialCommandReceived)

isChangedMode = 0;

// Custom delay with event processing

void Custom_delay_ms(unsigned int ms)

unsigned int i;

// Divide into 10ms chunks to allow quick event processing

for(i = 0; i < ms; i += 10)

delay_ms(10); // Basic 10ms delay

if (isChangedMode) return; // Exit if mode changed

if (receive_flag) Process_Received_Data(); // Process WiFi data

Process_ESP8266_TX_Queue(); // Process any queued transmissions

Update_LED_Status(); // Update LED status


Process_ESP8266_TX_Queue(); // Process any newly queued
transmissions

// Day traffic light cycle

void Day_Traffic_Cycle()

// Green light cycle

Control_LED(1); // Turn on green light

Update_LED_Status(); // Update status

Process_ESP8266_TX_Queue(); // Process queued transmissions

Custom_delay_ms(green_time); // Wait for configured time

if(isChangedMode) return; // Exit if mode changed

// Yellow light cycle

Control_LED(2); // Turn on yellow light

Update_LED_Status();

Process_ESP8266_TX_Queue();

Custom_delay_ms(yellow_time);

if(isChangedMode) return;

// Red light cycle

Control_LED(3); // Turn on red light

Update_LED_Status();

Process_ESP8266_TX_Queue();

Custom_delay_ms(red_time);
}

// Night traffic light cycle (blinking yellow)

void Night_Traffic_Cycle()

// Yellow light on for 1 second

Control_LED(2);

Update_LED_Status();

Process_ESP8266_TX_Queue();

Custom_delay_ms(1000);

if(isChangedMode) return;

// Light off for 1 second

Control_LED(0);

Update_LED_Status();

Process_ESP8266_TX_Queue();

Custom_delay_ms(1000);

// ===== MAIN PROGRAM =====

void main(void)

ADCON1 |= 0x0F;

CMCON |= 7;

// Initialize I/O ports

PORTB = 0x00; LATB = 0x00;


TRISB0_bit = 1; // Configure mode 1 button

TRISB1_bit = 1; // Configure mode 2 button

TRISB2_bit = 1; // Configure mode 3 button

PORTE = 0x00; LATE = 0x00;

TRISE0_bit = 0; // Red light

TRISE1_bit = 0; // Yellow light

TRISE2_bit = 0; // Green light

// Configure external interrupts for buttons

INT0E_bit = 1; // Enable RB0 interrupt

INT1IE_bit = 1; // Enable RB1 interrupt

INT2IE_bit = 1; // Enable RB2 interrupt

INT0IF_bit = 0; // Clear RB0 interrupt flag

INT1IF_bit = 0; // Clear RB1 interrupt flag

INT2IF_bit = 0; // Clear RB2 interrupt flag

INTCON2 = 0x00; // Additional interrupt configuration

UART1_Init(115200);

delay_ms(100);

// Reset ESP8266 module

RC0_bit = 0; delay_ms(100); RC0_bit = 1;

delay_ms(1000);

// Initialize and configure ESP8266

esp8266_restart();
esp8266_echoCmds(0);

esp8266_isStarted();

esp8266_mode(ESP8266_STATION);

esp8266_connect("trinhoa","19122003");

esp8266_start(ESP8266_TCP, "192.168.130.119", 8000);

// Turn on LED to indicate successful connection

esp8266_trans_mode(ESP8266_TRANS_PASS);

esp8266_send();

// Configure UART interrupt for receiving data

RCIF_bit = 0;

PIE1.RCIE = 1;

GIE_bit = 1;

PEIE_bit = 1;

// Initialize initial states

currentLedState = 0;

lastLedState = 0;

isChangedMode = 0;

receive_flag = 0;

specialCommandReceived = 0;

esp8266_tx_count = 0;

esp8266_tx_flag = 0;

// Main loop
while(1)

// Process data received via WiFi

if(receive_flag)

Process_Received_Data();

// Process any queued transmissions

Process_ESP8266_TX_Queue();

isChangedMode = 0; // Reset mode change flag

// Process by mode

switch(mode)

case 1: // Red light fixed mode

Control_LED(3); // Turn on red light

Update_LED_Status();

Process_ESP8266_TX_Queue();

while(!isChangedMode)

if(receive_flag) Process_Received_Data(); // Check WiFi continuously

Process_ESP8266_TX_Queue();

Update_LED_Status();

Process_ESP8266_TX_Queue();

delay_ms(50); // Prevent high CPU load


}

break;

case 2: // Blinking yellow mode

while(!isChangedMode)

// Yellow light on for 1 second

Control_LED(2);

Update_LED_Status();

Process_ESP8266_TX_Queue();

Custom_delay_ms(1000);

if(isChangedMode) break;

// Light off for 1 second

Control_LED(0);

Update_LED_Status();

Process_ESP8266_TX_Queue();

Custom_delay_ms(1000);

break;

default: // Automatic mode (mode 3)

while(!isChangedMode)

// Select operation mode based on day/night time

if(TimeMode == 'N')

Day_Traffic_Cycle(); // Day mode


else

Night_Traffic_Cycle(); // Night mode

if(isChangedMode) break;

break;

You might also like