Traffic Light Simulation with Timed State Change in Console

C program simulating a three-state traffic light with timed state changes in console, demonstrating basic concurrent programming and timing concepts.

Brief Introduction

Traffic Light Simulation with Timed State Change in Console (c)
DESCRIPTION:
This C program simulates the operation of a three-state traffic light (red, yellow, green) by printing the current state to the console and automatically changing it after a defined time interval. It is a simple yet robust example of timed state management in C, useful for understanding basic concepts of concurrent programming and timing.

ADDITIONAL NOTES:
The program is ready to use on Unix-like systems. For Windows, replace the sleep() function with Sleep() from the windows.h library and adjust the timing from seconds to milliseconds. The simulation is textual and does not require external hardware.

EXPLANATIONS:
- The variable 'stato' represents the current color of the traffic light: 0=Red, 1=Green, 2=Yellow.
- The sleep() function blocks execution for a number of seconds, simulating the duration of each state.
- The infinite while(1) loop allows the simulation to run indefinitely, changing the state in sequence.
- The printf() function prints the current state to the console, providing visual feedback to the user.
- The use of switch-case makes the code clear and easily extendable to add other states or behaviors.

Example Code: c

#include <stdio.h>
#include <unistd.h> // for sleep()

// Definition of duration times for each state in seconds
#define DURATA_ROSSO 5
#define DURATA_VERDE 5
#define DURATA_GIALLO 2

int main() {
    int stato = 0; // 0=Red, 1=Green, 2=Yellow

    while (1) {
        switch (stato) {
            case 0:
                // Red state
                printf("Traffic Light: RED\n");
                sleep(DURATA_ROSSO); // Waits DURATA_ROSSO seconds
                stato = 1; // Switch to Green
                break;
            case 1:
                // Green state
                printf("Traffic Light: GREEN\n");
                sleep(DURATA_VERDE); // Waits DURATA_VERDE seconds
                stato = 2; // Switch to Yellow
                break;
            case 2:
                // Yellow state
                printf("Traffic Light: YELLOW\n");
                sleep(DURATA_GIALLO); // Waits DURATA_GIALLO seconds
                stato = 0; // Return to Red
                break;
            default:
                // Unexpected state, reset to Red
                stato = 0;
                break;
        }
    }

    return 0; // Not reached
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Software: standard C compiler (gcc, clang, etc.)

Software: standard C library (stdio.h, time.h, unistd.h)

Configuration: no external dependencies required

Hardware: no specific hardware required, runs on console/terminal

Note: the program uses the sleep() function for timing, available on POSIX systems (Linux, macOS). On Windows, adapting the sleep function may be necessary.

Similar Topics

Counting Characters in a String Without Using strlen
Learn how to count characters in a C string manually without using strlen by iterating until the terminator for better understanding of string handling.
Calculation of the average grade of a student with 4 subjects
C program to read four subject grades, validate inputs between and 1, calculate the average, and display it with two decimal precision.
Program that replaces spaces with underscores in a string
This C program replaces spaces with underscores in a string using a modular function. It demonstrates safe input handling and simple string manipulation techniq
Simple calculator with switch ( +, -, *, / )
Simple C console calculator program using switch for operations plus minus multiply divide with input validation and division by zero handling.
Managing a List of Students with Structures and Sorting by Grade
Learn how to manage and sort a list of students using C structures and qsort function based on their final grades efficiently.
Text-based phonebook with name search and file saving
C program implementing a text-based phonebook with name search, add, display, and file save/load features for up to 1 contacts.
Implementation of a queue with array and basic operations in C
Learn how to implement a robust queue in C using a circular array with enqueue, dequeue, isEmpty, isFull, and peek operations for efficient data handling.
Simulation of a stack using arrays with overflow handling
C stack implementation using arrays with push, pop, display functions and overflow/underflow error handling for reliable stack operations.