Raspberry Pi IoT In C Using Linux Drivers

Second Edition

Programs

 

DriverC2E360

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into a NetBeans of VS Code project. 

 The only downside is that you have to create a project to paste the code into.

To do this follow the instructionin the book-- in particular make sure you have added any libraries to the link step and are running as root if required. 

All of the programs below were copy and pasted from working programs in the IDE. They have been formatted using the built in formatter and hence are not identical in layout to the programs in the book. This is to make copy and pasting them easier. The programs in the book are formatted to be easy to read on the page.

If anything you consider important is missing or if you have any requests or comments  contact:

This email address is being protected from spambots. You need JavaScript enabled to view it. 


 

Page 26

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
    printf("Hello C World");
    int test = 42;
    printf("%d\n", test);
    return (EXIT_SUCCESS);
}


Page 44

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
    int fd = open("/sys/class/leds/ACT/trigger", O_WRONLY);
    write(fd, "none",4);
    close(fd);
    fd = open("/sys/class/leds/ACT/brightness", O_WRONLY);
    while (1)
    {
        write(fd, "0",1);
        sleep(2);
        write(fd, "1",1);
        sleep(2);
    }
}

Page 45

#include <stdio.h>
import io
from time import sleep

fd = io.open("/sys/class/leds/ACT/trigger","w")
fd.write("timer")
fd.close()

fd = io.open("/sys/class/leds/ACT/delay_on", "w")
fd.write("2000")
fd.close()

fd = io.open("/sys/class/leds/ACT/delay_off", "w")
fd.write("3000")
fd.close()

 


Page 54

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int res;
int main(int argc, char **argv) {
    for (;;) {
         res = gpiod_ctxless_set_value("0", 4, 1, 1,  "output test", NULL, NULL);
         res = gpiod_ctxless_set_value("0", 4, 0, 1,  "output test", NULL, NULL);
    }
}
 

 Remember to change "0" to "4" if running on a Pi 5.

Page 55 

#define _DEFAULT_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int res;

int delayms(int ms)
{
    struct timespec delay = {0, ms * 1000 * 1000};
    return nanosleep(&delay, NULL);
}

int main(int argc, char **argv)
{

    for (;;)
    {
        res = gpiod_ctxless_set_value("0", 4, 1, 1, "output test", (gpiod_ctxless_set_value_cb)delayms, (void *)100);
        res = gpiod_ctxless_set_value("0", 4, 0, 1, "output test", (gpiod_ctxless_set_value_cb)delayms, (void *)100);
    }
}

 Remember to change "0" to "4" if running on a Pi 5.

Page 56 

#define _DEFAULT_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int res;
int delayms(int ms)
{
    struct timespec delay = {0, ms * 1000 * 1000};
    return nanosleep(&delay, NULL);
}
int main(int argc, char **argv)
{
    int offsets[] = {4, 17};
    int state1[] = {1, 0};
    int state2[] = {0, 1};
    for (;;)
    {
        gpiod_ctxless_set_value_multiple("0", offsets, state1, 2, 1, "output test", (gpiod_ctxless_set_value_cb)delayms, (void *)1);
        gpiod_ctxless_set_value_multiple("0", offsets, state2, 2, 1, "output test", (gpiod_ctxless_set_value_cb)delayms, (void *)2);
    }
}
 
 Remember to change "0" to "4" if running on a Pi 5.

Page 58

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    const char *name = gpiod_chip_name(chip);
    int num = gpiod_chip_num_lines(chip);
    printf("%s %d", name, num);
    gpiod_chip_close(chip);

 Remember to change chip number 0 to 4 if running on a Pi 5.

Page 60 

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);
    res = gpiod_line_request_output(line4, "test output", 0);

    for (;;)
    {
        res = gpiod_line_set_value(line4, 1);
        res = gpiod_line_set_value(line4, 0);
    };

 Remember to change chip number 0 to 4 if running on a Pi 5.

 

Page 64

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line_bulk bulk;
    gpiod_line_bulk_init(&bulk);
    gpiod_line_bulk_add(&bulk, gpiod_chip_get_line(chip, 4));
    gpiod_line_bulk_add(&bulk, gpiod_chip_get_line(chip, 17));

    res = gpiod_line_request_bulk_output(&bulk, "test", 0);
    for (;;)
    {
        gpiod_line_set_value_bulk(&bulk, (int[2]){0, 1});
        gpiod_line_set_value_bulk(&bulk, (int[2]){1, 0});
    };
}
 

 Remember to change chip number 0 to 4 if running on a Pi 5.

 

Page 66 

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

void gpiod_line_release(struct gpiod_line *line);

int main(int argc, char **argv)
{
    int res;
    struct timespec delay = {0, 10 * 1000 * 1000};
    struct timespec time1, time2;

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_input(line4, "RMeasure");
    nanosleep(&delay, NULL);
    gpiod_line_release(line4);

    res = gpiod_line_request_output(line4, "RMeasure", 0);
    nanosleep(&delay, NULL);
    gpiod_line_release(line4);

    clock_gettime(CLOCK_REALTIME, &time1);
    gpiod_line_request_input(line4, "RMeasure");
    while (gpiod_line_get_value(line4) == 0)
    {
    };
    clock_gettime(CLOCK_REALTIME, &time2);
    printf("Time=%d", (time2.tv_nsec - time1.tv_nsec) / 1000);
}  
 

 Remember to change chip number 0 to 4 if running on a Pi 5.


 

Page 70

#define __ARM_PCS_VFP
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
int main(int argc, char **argv)
{
    int fd;
    struct gpiochip_info info;

    fd = open("/dev/gpiochip0", O_RDONLY);

    int ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &info);
    close(fd);

    printf("label: %s\n name: %s\n number of lines: %u\n", info.label, info.name, info.lines);
    return 0;
}
 

If you run this on a Pi 5 change gpiochip0 to gpiochip4.

Page 73

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd, ret;

    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    req.lineoffsets[1] = 17;
    req.flags = GPIOHANDLE_REQUEST_OUTPUT;
    req.default_values[0] = 0;
    req.default_values[1] = 0;
    strcpy(req.consumer_label, "Output test");
    req.lines = 2;

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    close(fd);

    struct gpiohandle_data data;
    data.values[0] = 0;
    data.values[1] = 1;
    while (1)
    {
        data.values[0] = !data.values[0];
        data.values[1] = !data.values[1];
        ret = ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
    }
    return 0;

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 74 

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
int main(int argc, char **argv)
{
    int fd, ret;
    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    req.lineoffsets[1] = 17;
    req.flags = GPIOHANDLE_REQUEST_INPUT;
    strcpy(req.consumer_label, "Input test");
    req.lines = 2;
    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    close(fd);
    struct gpiohandle_data data;
    ret = ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
    printf("%hhu , %hhu", data.values[0], data.values[1]);
    close(req.fd);
    return 0;
}

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 75 

#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/gpio.h>
#include <sys/ioctl.h>
#include <time.h>
int main(int argc, char **argv)
{
    int fd, ret;
    struct timespec delay = {0, 10 * 1000 * 1000};
    struct timespec time1, time2;
    fd = open("/dev/gpiochip0", O_RDONLY);
    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    strcpy(req.consumer_label, "RC Measure");
    req.lines = 1;

    req.flags = GPIOHANDLE_REQUEST_INPUT;
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    nanosleep(&delay, NULL);
    close(req.fd);

    req.flags = GPIOHANDLE_REQUEST_OUTPUT;
    struct gpiohandle_data data;
    data.values[0] = 0;
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    ret = ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
    nanosleep(&delay, NULL);
    close(req.fd);

    req.flags = GPIOHANDLE_REQUEST_INPUT;
    clock_gettime(CLOCK_REALTIME, &time1);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    ret = ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);

    while (data.values[0] == 0)
    {
        ret = ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data)
    }
    clock_gettime(CLOCK_REALTIME, &time2);
    printf("Time=%d", (time2.tv_nsec - time1.tv_nsec) / 1000);
    return 0;

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.


 

Page 83

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);
    gpiod_line_request_both_edges_events(line4, "event test");
    gpiod_line_event_wait(line4, NULL);
    printf("Event on line 4");
}

Page 84

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

void gpiod_line_release(struct gpiod_line *line);
int main(int argc, char **argv)
{
    int res;

    struct timespec delay = {0, 10 * 1000 * 1000};
    struct timespec time1;

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_input(line4, "RMeasure");
    nanosleep(&delay, NULL);
    gpiod_line_release(line4);

    res = gpiod_line_request_output(line4, "RMeasure", 0);
    nanosleep(&delay, NULL);
    gpiod_line_release(line4);
    clock_gettime(CLOCK_REALTIME, &time1);

    gpiod_line_request_rising_edge_events(line4, "RMeasuret");
    struct gpiod_line_event event;
    gpiod_line_event_read(line4, &event);
    printf("Event on line 4 %d, %d", event.event_type,  (event.ts.tv_nsec - time1.tv_nsec) / 1000);
}

 

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 85

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

void gpiod_line_release(struct gpiod_line *line);
int main(int argc, char **argv)
{
    int res;
    struct timespec time1;

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_both_edges_events(line4, "Measure");

    struct gpiod_line_event event;
    while (true)
    {
        do
        {
            res = gpiod_line_event_read(line4, &event);
        } while (event.event_type != GPIOD_LINE_EVENT_RISING_EDGE);

        time1.tv_nsec = event.ts.tv_nsec;

        do
        {
            res = gpiod_line_event_read(line4, &event);
        } while (event.event_type != GPIOD_LINE_EVENT_FALLING_EDGE);

        printf("Pulse Width %d \r\n",
               (event.ts.tv_nsec - time1.tv_nsec) / 1000);
        fflush(stdout);
    }

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

 

Page 86

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

void gpiod_line_release(struct gpiod_line *line);
int main(int argc, char **argv)
{
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_input(line4, "button");
    printf("Press button \n\r");
    fflush(stdout);
    sleep(20);
    if (gpiod_line_get_value(line4) == 1)
    {
        printf("button pressed");
    }
    else
    {
        printf("button not pressed");
    }
}

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 87

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

void gpiod_line_release(struct gpiod_line *line);
int main(int argc, char **argv)
{
    int res;
    struct timespec timeout = {0, 0};

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_both_edges_events(line4, "button");

    printf("Press button \n\r");
    fflush(stdout);
    sleep(20);
    struct gpiod_line_event event;

    res = gpiod_line_event_wait(line4, &timeout);
    if (res > 0)
    {
        res = gpiod_line_event_read(line4, &event);
        printf("button pressed %d", event.ts.tv_nsec);
    }
    else
    {
        printf("button not pressed");
    }

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 88

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

int gpiod_line_event_poll(struct gpiod_line *line, struct gpiod_line_event *event);

int main(int argc, char **argv)
{
    int res;

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_both_edges_events(line4, "button");

    struct gpiod_line_event event;

    while (true)
    {
        res = gpiod_line_event_poll(line4, &event);
        if (res > 0)
        {
            gpiod_line_event_read(line4, &event);
            printf("Event on line 4 %d,%d \n\r ",  event.event_type, event.ts);
            fflush(stdout);
        }
    }
}

int gpiod_line_event_poll(struct gpiod_line *line,   struct gpiod_line_event *event)
{
    struct timespec timeout = {0, 0};
    int res = gpiod_line_event_wait(line, &timeout);
    if (res > 0)
        res = gpiod_line_event_read(line, event);
    if (res == 0)
        res = 1;
    return res;
}

 

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 92

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
#include <sys/epoll.h>

int main(int argc, char **argv)
{
    int fd, ret;

    struct gpioevent_request req;
    req.lineoffset = 4;
    req.handleflags = GPIOHANDLE_REQUEST_INPUT;
    req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE;
    strcpy(req.consumer_label, "Event test");

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &req);
    close(fd);

    static struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = req.fd;
    int epfd = epoll_create(1);
    int res = epoll_ctl(epfd, EPOLL_CTL_ADD, req.fd, &ev);

    int nfds = epoll_wait(epfd, &ev, 1, 20000);
    if (nfds != 0)
    {
        struct gpioevent_data edata;
        read(req.fd, &edata, sizeof edata);
        printf("%u,%llu", edata.id, edata.timestamp);
    }
}

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 93

#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
#include <sys/epoll.h>
#include <gpiod.h>

int main(int argc, char **argv)
{
    int res;

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_rising_edge_events(line4, "button");
    int fd = gpiod_line_event_get_fd(line4);

    static struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = fd;
    int epfd = epoll_create(1);
    res = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);

    int nfds = epoll_wait(epfd, &ev, 1, 20000);
    if (nfds != 0)
    {
        struct gpioevent_data edata;
        read(fd, &edata, sizeof edata);
        printf("%u,%llu", edata.id, edata.timestamp);
    }
}

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 97

#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <gpiod.h>
#include <sys/epoll.h>
#include <pthread.h>

typedef void (*eventHandler)(struct gpiod_line_event *);
typedef struct
{
    struct gpiod_line *line;
    eventHandler func;
} intVec;
void myHandler(struct gpiod_line_event *event)
{
    printf("%d,%d \n\r", event->event_type,
           event->ts.tv_nsec / 1000);
    fflush(stdout);
}

void *waitInterrupt(void *arg)
{
    intVec *intData = (intVec *)arg;
    struct gpiod_line_event event;
    while (true)
    {
        int res = gpiod_line_event_read(intData->line, &event);
        if (res == 0)
            intData->func(&event);
    }
}

int main(int argc, char **argv)
{
    int fd, ret, res;

    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);

    res = gpiod_line_request_rising_edge_events(line4, "button");

    intVec intData;
    intData.line = line4;
    intData.func = &myHandler;

    pthread_t intThread;
    if (pthread_create(&intThread, NULL, waitInterrupt,  (void *)&intData))
    {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    for (;;)
    {
        printf("Working\n\r");
        fflush(stdout);
        sleep(2);
    }

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

Page 100

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h> 
#include <unistd.h>
#include <stdlib.h>

int event_cb(int event, unsigned int offset, const struct timespec *timestamp, void *unused)
{
   printf("[%ld.%09ld] %s\n", timestamp->tv_sec, timestamp->tv_nsec,
     (event == GPIOD_CTXLESS_EVENT_CB_RISING_EDGE)? "rising" :
     (event == GPIOD_CTXLESS_EVENT_CB_FALLING_EDGE)? "falling" :
     (event == GPIOD_CTXLESS_EVENT_CB_TIMEOUT) ? "timeout" : "??");
     fflush(stdout);
     return GPIOD_CTXLESS_EVENT_CB_RET_OK;
}


int main(int argc, char **argv) {
    int res;
    struct timespec time;
    time.tv_nsec=0;
    time.tv_sec=20;
    res = gpiod_ctxless_event_monitor("0",
            GPIOD_CTXLESS_EVENT_BOTH_EDGES, 4, 0, "monitor test",
               &time, NULL, event_cb, NULL);
}

Remember to change gpiochip0 to gpiochip4 if you are running on a Pi 5.

 


Page 110 

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    char buffer[25];

    int fd = open("/sys/bus/iio/devices/iio:device0/name", O_RDONLY);
    read(fd, buffer, 25);
    close(fd);
    printf("%s", buffer);

    fd = open("/sys/bus/iio/devices/iio:device0/in_temp_input", O_RDONLY);
    read(fd, buffer, 25);
    close(fd);
    int temp;
    sscanf(buffer, "%d", &temp);

    printf("%f\n\r", temp / 1000.0);
    fd = open("/sys/bus/iio/devices/iio:device0/in_humidityrelative_input", O_RDONLY);
    read(fd, buffer, 25);
    close(fd);
    int hum;
    sscanf(buffer, "%d", &hum);
    printf("%f\n\r", hum / 1000.0);
}

Page 112

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}
void checkDht11()
{
    FILE *fd = doCommand("sudo  dtparam -l");
    char output[1024];
    int txfound = 0;

    char indicator[] = "dht11  gpiopin=4";
    char command[] = "sudo dtoverlay dht11 gpiopin=4";
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, indicator) != NULL)
        {
            txfound = 1;
        }
    }
    if (txfound == 0)
    {
        fd = doCommand(command);
    }

    pclose(fd);
}

int main(int argc, char **argv)
{
    char buffer[25];
    checkDht11();
    int fd = open( "/sys/bus/iio/devices/iio:device0/name", O_RDONLY);
    read(fd, buffer, 25);
    close(fd);
    printf("%s", buffer);

    fd = open( "/sys/bus/iio/devices/iio:device0/in_temp_input", O_RDONLY);
    read(fd, buffer, 25);
    close(fd);
    int temp;
    sscanf(buffer, "%d", &temp);

    printf("%f\n\r", temp / 1000.0);

    fd = open("/sys/bus/iio/devices/iio:device0/in_humidityrelative_input", O_RDONLY);
    read(fd, buffer, 25);
    close(fd);
    int hum;
    sscanf(buffer, "%d", &hum);
    printf("%f\n\r", hum / 1000.0);

 


 

Page 133

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

void pwm(struct gpiod_line *line, int);

int main(int argc, char **argv)
{
    int period = 20;
    int duty = 25;
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);
    res = gpiod_line_request_output(line4, "test output", 0);

    struct timespec ontime = {0, 0};
    struct timespec offtime = {0, 0};
    ontime.tv_nsec = period * duty * 10 * 1000;
    offtime.tv_nsec = (period - period * duty / 100) * 1000 * 1000;

    for (;;)
    {
        res = gpiod_line_set_value(line4, 1);
        nanosleep(&ontime, NULL);
        res = gpiod_line_set_value(line4, 0);
        nanosleep(&offtime, NULL);
    };
}
 

Remember to change "0" to "4" if you are running on a Pi 5.

Page  134

#define _GNU_SOURCE
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

struct pwmargs
{
    struct gpiod_line *line;
    struct timespec ontime;
    struct timespec offtime;
};

void *pwmrun(void *arg)
{
    struct pwmargs *pwmdata = (struct pwmargs *)arg;
    int res;
    for (;;)
    {
        res = gpiod_line_set_value(pwmdata->line, 1);
        nanosleep(&(pwmdata->ontime), NULL);
        res = gpiod_line_set_value(pwmdata->line, 0);
        nanosleep(&(pwmdata->offtime), NULL);
    };
}

int pwm(struct gpiod_line *line, int period, int duty)
{
    static struct pwmargs pwmdata;
    pwmdata.line = line;
    pwmdata.ontime.tv_sec = 0;
    pwmdata.ontime.tv_nsec = period * duty * 10;
    pwmdata.offtime.tv_sec = 0;
    pwmdata.offtime.tv_nsec = (period - period * duty / 100) * 1000;

    pthread_t pwmThread;
    if (pthread_create(&pwmThread, NULL, pwmrun, (void *)&pwmdata))
    {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    return 0;
};

int main(int argc, char **argv)
{
    int res;
    struct gpiod_chip *chip = gpiod_chip_open_by_number(0);
    struct gpiod_line *line4 = gpiod_chip_get_line(chip, 4);
    res = gpiod_line_request_output(line4, "test output", 0);

    pwm(line4, 20 * 1000, 25);
    for (;;)
    {
    };
}
 

Remember to change "0" to "4" if you are running on a Pi 5.

Page 137

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <fcntl.h>

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}
void checkPWM()
{
    FILE *fd = doCommand("sudo  dtparam -l");
    char output[1024];
    int txfound = 0;

    char indicator[] = "pwm-2chan";
    char command[] = "sudo dtoverlay pwm-2chan";
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, indicator) != NULL)
        {
            txfound = 1;
        }
    }
    if (txfound == 0)
    {
        fd = doCommand(command);
        sleep(2);
    }

    pclose(fd);
}

int main(int argc, char **argv)
{
    checkPWM();

    int fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY);
    write(fd, "0", 1);
    close(fd);
    sleep(2);
    fd = open("/sys/class/pwm/pwmchip0/pwm0/period", O_WRONLY);
    write(fd, "10000000", 8);
    close(fd);
    fd = open("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", O_WRONLY);
    write(fd, "8000000", 7);
    close(fd);
    fd = open("/sys/class/pwm/pwmchip0/pwm0/enable", O_WRONLY);
    write(fd, "1", 1);
    close(fd);
}

 

Remember to change "0" to "4" if you are running on a Pi 5.

Page 139

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <fcntl.h>

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}
void checkPWM()
{
    FILE *fd = doCommand("sudo  dtparam -l");
    char output[1024];
    int txfound = 0;

    char indicator[] = "pwm";
    char command[] = "sudo dtoverlay pwm-2chan, pin=18 func=2 pin2=12 func2=4" ;
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, indicator) != NULL)
        {
            txfound = 1;
            printf("Overlay already loaded\n\r");
        }
    }
    if (txfound == 0)
    {
        fd = doCommand(command);
        sleep(2);
    }

    pclose(fd);
}

int main(int argc, char **argv)
{
    checkPWM();  
    int fd = open("/sys/class/pwm/pwmchip2/export", O_WRONLY);
    write(fd, "0", 1);
    close(fd);
    sleep(2);
    fd = open("/sys/class/pwm/pwmchip2/pwm0/period", O_WRONLY);
    write(fd, "10000001", 8);
    close(fd);
    fd = open("/sys/class/pwm/pwmchip2/pwm0/duty_cycle", O_WRONLY);
    write(fd, "4000000", 7);
    close(fd);
    fd = open("/sys/class/pwm/pwmchip2/pwm0/enable", O_WRONLY);
    write(fd, "1", 1);
    close(fd);
   
    fd = open("/sys/class/pwm/pwmchip2/export", O_WRONLY);
    write(fd, "2", 1);
    close(fd);
    sleep(2);
    fd = open("/sys/class/pwm/pwmchip2/pwm2/period", O_WRONLY);
    write(fd, "10000001", 8);
    close(fd);
    fd = open("/sys/class/pwm/pwmchip2/pwm2/duty_cycle", O_WRONLY);
    write(fd, "5000000", 7);
    close(fd);
    fd = open("/sys/class/pwm/pwmchip2/pwm2/enable", O_WRONLY);
    write(fd, "1", 1);
    close(fd);
}
 

Page 141 - full listing of finished program on Page 155

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdarg.h>

 #define Pi5

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}
void checkPWM()
{
    FILE *fd = doCommand("sudo  dtparam -l");
    char output[1024];
    int txfound = 0;

    char indicator[] = "pwm-2chan";
    char command[] = "sudo dtoverlay pwm-2chan pin=12 func=4 pin2=13 func2=4";
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, indicator) != NULL)
        {
            txfound = 1;
        }
    }
    if (txfound == 0)
    {
        pclose(fd);
        fd = doCommand(command);
    }

    pclose(fd);
}
enum pwm
{
    OpenChan,
    SetFreq,
    SetDuty,
    EnableChan,
    DisableChan,
    CloseChan,
    InvertChan
};

int pwmAction(enum pwm action, int chan, ...)
{
    static int fdf[2];
    static int fdd[2];

    int fd;
    char buf[150];
    char schan[6];
    va_list params;
    int param;

    if (chan != 0 && chan != 1)
        return -1;

#if defined(Pi5)
    char path[] = "/sys/class/pwm/pwmchip2/";
#else
    char path[] = "/sys/class/pwm/pwmchip0/";
#endif
    char chanNum[2];
    snprintf(schan, 6, "%s%d", "pwm", chan);
    snprintf(chanNum, 2, "%d", chan);

    int L;

    switch (action)
    {
    case OpenChan:
        checkPWM();
        snprintf(buf, 150, "%s%s", path, "export");
        fd = open(buf, O_WRONLY);
        write(fd, chanNum, 1);
        close(fd);
        sleep(2);
        snprintf(buf, 150, "%s%s%s", path, schan, "/period");
        fdf[chan] = open(buf, O_WRONLY);
        snprintf(buf, 150, "%s%s%s", path, schan, "/duty_cycle");
        fdd[chan] = open(buf, O_WRONLY);
        break;

    case SetFreq:
        va_start(params, chan);
        param = va_arg(params, int);
        L = snprintf(buf, 150, "%d", param);
        write(fdf[chan], buf, L);
        break;
    case SetDuty:
        va_start(params, chan);
        param = va_arg(params, int);
        L = snprintf(buf, 150, "%d", param);
        write(fdd[chan], buf, L);
        break;
    case EnableChan:
        snprintf(buf, 150, "%s%s%s", path, schan, "/enable");
        fd = open(buf, O_WRONLY);
        write(fd, "1", 1);
        close(fd);
        break;
    case DisableChan:
        snprintf(buf, 150, "%s%s%s", path, schan, "/enable");
        fd = open(buf, O_WRONLY);
        write(fd, "0", 1);
        close(fd);
        break;
    case CloseChan:
        close(fdf[chan]);
        close(fdd[chan]);
        snprintf(buf, 150, "%s%s%s", path, "/unexport");
        printf("%s\n", buf);
        fd = open(buf, O_WRONLY);
        write(fd, chanNum, 1);
        close(fd);
        break;

    case InvertChan:
        va_start(params, chan);
        param = va_arg(params, int);
        snprintf(buf, 150, "%s%s%s", path, schan, "/polarity");
        fd = open(buf, O_WRONLY);
        if (param == 0)
        {
            L = snprintf(buf, 150, "%s", "normal");
            write(fd, buf, L);
        }
        if (param == 1)
        {
            L = snprintf(buf, 150, "%s", "inversed");
            write(fd, buf, L);
        }
        close(fd);
        break;
    }

    return 0;
}

int main(int argc, char **argv)
{
    pwmAction(OpenChan, 0, 0);
   

    int t = 20 * 1000000;
    pwmAction(SetFreq, 0, t);
    int d1 = t * 2.5 / 100;
    int d2 = t * 12 / 100;
   
    pwmAction(EnableChan, 0, 0);

    for (;;)
    {
        pwmAction(SetDuty, 0, d1);
        sleep(1);
        pwmAction(SetDuty, 0, d2);
        sleep(1);
    }
}

 


Page 167 

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include <stdint.h>

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}
void checkSPI0()
{
    FILE *fd = doCommand("sudo  dtparam -l");
    char output[1024];
    int txfound = 0;

    char indicator[] = "spi=on";
    char command[] = "sudo dtparam spi=on";
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, indicator) != NULL)
        {
            txfound = 1;
        }
    }
    if (txfound == 0)
    {
        fd = doCommand(command);
        sleep(2);
    }

    pclose(fd);
}

int main(int argc, char **argv)
{
    checkSPI0();

    uint8_t tx[] = {0xAA};
    uint8_t rx[] = {0};

    struct spi_ioc_transfer tr =
        {
            .tx_buf = (unsigned long)tx,
            .rx_buf = (unsigned long)rx,
            .len = 1,
            .delay_usecs = 0,
            .speed_hz = 500000,
            .bits_per_word = 8,
        };

    int fd = open("/dev/spidev0.0", O_RDWR);  
    int status = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
    if (status < 0)
        printf("can't send data");
    printf("%X,%X\n", tx[0],rx[0]);
    close(fd);
}

 

Page 177

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include <stdint.h>

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}
void checkSPI0()
{
    FILE *fd = doCommand("sudo  dtparam -l");
    char output[1024];
    int txfound = 0;

    char indicator[] = "spi=on";
    char command[] = "sudo dtparam spi=on";
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, indicator) != NULL)
        {
            txfound = 1;
        }
    }
    if (txfound == 0)
    {
        fd = doCommand(command);
        sleep(2);
    }

    pclose(fd);
}

int main(int argc, char **argv)
{
    checkSPI0();

    uint8_t tx[] = {0x01, 0x80, 0x00};
    uint8_t rx[3];

    struct spi_ioc_transfer tr =
        {
            .tx_buf = (unsigned long)tx,
            .rx_buf = (unsigned long)rx,
            .len = 3,
            .delay_usecs = 0,
            .speed_hz = 0,
            .bits_per_word = 0,
        };

    int fd = open("/dev/spidev0.0", O_RDWR);

    static uint8_t mode = 0;
    int status = ioctl(fd, SPI_IOC_WR_MODE, &mode);
    if (status == -1)
        printf("can't set spi mode");

    static uint8_t bits = 8;
    status = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
    if (status == -1)
        printf("can't set bits per word");

    static uint32_t speed = 100000;
    status = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
    if (status == -1)
        printf("can't set max speed hz");

    status = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
    if (status < 0)
        printf("can't send data");

    int data = ((int)rx[1] & 0x03) << 8 | (int)rx[2];
    float volts = (((float)data) * 3.3f) / 1023.0f;
    printf("%f V\n\r", volts);

    close(fd);

 

Page 197

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>

void checkI2CBus();
FILE *doCommand(char *cmd);

int main(int argc, char **argv)
{
    checkI2CBus();
    int i2cfd = open("/dev/i2c-1", O_RDWR);
    ioctl(i2cfd, I2C_SLAVE, 0x40);
    char buf[4] = {0xE7};
    write(i2cfd, buf, 1);
    read(i2cfd, buf, 1);
    close(i2cfd
    return (EXIT_SUCCESS);
}

Page 206

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>

void checkI2CBus();
FILE *doCommand(char *cmd);
uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check);

int main(int argc, char **argv)
{

    checkI2CBus();

    int i2cfd = open("/dev/i2c-1", O_RDWR);
    ioctl(i2cfd, I2C_SLAVE, 0x40);
    char buf[3] = {0xF3};
    write(i2cfd, buf, 1);

    while (1)
    {
        int result = read(i2cfd, buf, 3);
        if (result > 0)
            break;
        usleep(10 * 1000);
    }
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n\rlsb %d \n\rchecksum %d \n\r", msb, lsb, check);

    unsigned int data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float temp = (float)(-46.85 + (175.72 * data16 / (float)65536));
    printf("Temperature %f C \n\r", temp);
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    buf[0] = 0xF5;
    write(i2cfd, buf, 1);

    while (1)
    {
        int result = read(i2cfd, buf, 3);
        if (result > 0)
            break;
        usleep(10 * 1000);
    }
    msb = buf[0];
    lsb = buf[1];
    check = buf[2];
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float hum = -6 + (125.0 * (float)data16) / 65536;
    printf("Humidity %f %% \n\r", hum);
    close(i2cfd);
    return (EXIT_SUCCESS);
}

uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check)
{
    uint32_t data32 = ((uint32_t)msb << 16) | ((uint32_t)lsb << 8) | (uint32_t)check;
    uint32_t divisor = 0x988000;
    for (int i = 0; i < 16; i++)
    {
        if (data32 & (uint32_t)1 << (23 - i))
            data32 ^= divisor;
        divisor >>= 1;
    };
    return (uint8_t)data32;
}

void checkI2CBus()
{
    FILE *fd = doCommand("sudo dtparam -l");
    char output[1024];
    int txfound = 0;
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, "i2c_arm=on") != NULL)
        {
            txfound = 1;
        }
        if (strstr(output, "i2c_arm=off") != NULL)
        {
            txfound = 0;
        }
    }
    pclose(fd);
    if (txfound == 0)
    {
        fd = doCommand("sudo dtparam i2c_arm=on");
        pclose(fd);
    }
}

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}

 

Page 219

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>


void checkI2CBus();


int main(int argc, char **argv)
{
    int i2cfd = open("/dev/i2c-1", O_RDWR);
    ioctl(i2cfd, I2C_SLAVE, 0x40);
    char buf[3] = {0xE3};
    write(i2cfd, buf, 1);
    int result = read(i2cfd, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n\rlsb %d \n\rchecksum %d \n\r", msb, lsb, check);
}

Page 222

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>

void checkI2CBus();
int i2cReadRegister(int i2cfd, uint8_t slaveaddr, uint8_t reg, uint8_t *buf, int len);

int main(int argc, char **argv)
{
    checkI2CBus();
    int i2cfd = open("/dev/i2c-1", O_RDWR);
    char buf2[1] = {0};
    i2cReadRegister(i2cfd, 0x40, 0xE7, buf2, 1);
    printf("%d \n\r", buf2[0]);
    return (EXIT_SUCCESS);
}

 


Page 227

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int fd = open("/sys/class/hwmon/hwmon0/temp1_input", O_RDONLY);
    char buf[100] = {0};
    read(fd, buf, 100);
    printf("%s\n\r", buf);
    float temp;
    sscanf(buf, "%f", &temp);
    temp = temp / 1000;
    printf("%f\n\r", temp);
}

Page 234

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>

void loadHTU21();

int main(int argc, char **argv)
{
    loadHTU21();
    float temp;
    float hum;

    {
        char output[1024] = {0};
        int fdtemp = open("/sys/bus/iio/devices/iio:device0/in_temp_input", O_RDWR);
        read(fdtemp, output, sizeof(output));
        close(fdtemp);
        printf("%s\n\r", output);
        sscanf(output, "%f", &temp);
        temp = temp / 1000;
        fflush(stdout);
    }

    {
        char output[1024] = {0};
        int fdhum = open("/sys/bus/iio/devices/iio:device0/in_humidityrelative_input", O_RDWR);
        read(fdhum, output, sizeof(output));
        close(fdhum);
        printf("%s\n\r", output);
        sscanf(output, "%f", &hum);
        hum = hum / 1000;
        fflush(stdout);
    }
    printf("%f\n\r", temp);
    printf("%f\n\r", hum);

    return (EXIT_SUCCESS);
}

void loadHTU21()
{
    FILE *fd = doCommand("sudo dtparam -l");
    char output[1024];
    int txfound = 0;
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, "i2c-sensor  htu21=true") != NULL)
        {
            txfound = 1;
        }
    }
    pclose(fd);
    if (txfound == 0)
    {
        fd = doCommand("sudo dtoverlay i2c-sensor htu21");
        pclose(fd);
    }
}

 

Page 248

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <fcntl.h>

FILE *doCommand(char *cmd)
{
    FILE *fp = popen(cmd, "r");
    if (fp == NULL)
    {
        printf("Failed to run command %s \n\r", cmd);
        exit(1);
    }
    return fp;
}

void load1w(int pin)
{
    FILE *fd = doCommand("sudo dtparam -l");
    char output[1024];
    int txfound = 0;
    while (fgets(output, sizeof(output), fd) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, "w1-gpio") != NULL)
        {
            txfound = 1;
        }
    }
    pclose(fd);
    if (txfound == 0)
    {
        char cmd[100];
        snprintf(cmd, 100, "sudo dtoverlay w1-gpio gpiopin=%d", pin);

        fd = doCommand(cmd);
        pclose(fd);
    }
}

int getDevices(char path[][100], int *num)
{
    char buffer[500];
    int fd = open("/sys/bus/w1/drivers/w1_master_driver/w1_bus_master1/w1_master_slaves", O_RDONLY);
    read(fd, buffer, 500);
    close(fd);
    *num = 0;
    for (char *p = strtok(buffer, "\n"); p != NULL; p = strtok(NULL, "\n"))
    {
        snprintf(path[(*num)++], 100, "/sys/bus/w1/devices/%s", p);
    }
    num--;
}

int getData(char path[], char name[], char data[], int n)
{
    char file[100];
    snprintf(file, 100, "%s/%s", path, name);
    int fd = open(file, O_RDONLY);
    int c = read(fd, data, n);
    close(fd);
    data[c] = 0;
    return c;
}

int main(int argc, char **argv)
{
    load1w(4);
    char path[10][100];
    int num;
    getDevices(path, &num);
    printf("%d  %s\n\r", num, path[0]);
    if (num < 1)
        exit(-1);

    char output[1024] = {0};
    char file[100];

    getData(path[0], "name", output, 100);
    printf("Name %s\n\r", output);

    getData(path[0], "resolution", output, 100);
    printf("Resolution %s\n\r", output);

    getData(path[0], "w1_slave", output, 100);
    printf("w1_slave %s\n\r", output);

    getData(path[0], "temperature", output, 100);
    printf("temperature %s\n\r", output);
    float temp;
    sscanf(output, "%f", &temp);
    temp = temp / 1000;
    printf("temperature %f C\n\r", temp);

    getData(path[0], "alarms", output, 100);
    printf("alarms %s\n\r", output);
}


 

Page 269

launch.json

{
  "configurations": [    
    {
      "name": "Remote C Debug",
      "type": "cppdbg",
      "request": "launch",
      "program": "${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${config:remoteDirectory}/${relativeFileDirname}",
      "environment": [],
      "externalConsole": false,
      "pipeTransport": {
           "debuggerPath": "/usr/bin/gdb",
           "pipeProgram": "C:/Windows/System32/OpenSSH/ssh",
           "pipeArgs": [
                    "${config:sshUser}@${config:sshEndpoint}"
                ],
           "pipeCwd": "${workspaceFolder}"
      },
      "MIMode": "gdb",
      "setupCommands": [
       {
           "description": "Enable pretty-printing for gdb",
           "text": "-enable-pretty-printing",
           "ignoreFailures": true
       }
      ],
      "sourceFileMap": {
                "${config:remoteDirectory}/${relativeFileDirname}": "${fileDirname}"
       },
      "preLaunchTask": "CopyBuildRemote",
     }
  ]
}

tasks.json

{
   "version": "2.0.0",
   "tasks": [
      {
         "label": "copyToRemote",
         "type": "shell",
         "command": "scp -r ${fileDirname} ${config:sshUser}@${config:sshEndpoint}:${config:remoteDirectory}/",
         "problemMatcher": [],
         "presentation": {
            "showReuseMessage": false,
            "clear": true
         }
      },
      {
         "label": "copyHeader",
         "type": "shell",
         "command": "mkdir ${workspaceFolder}/headers/;scp -r  ${config:sshUser}@${config:sshEndpoint}:${config:header} ${workspaceFolder}/headers/ ",
         "problemMatcher": [],
         "presentation": {
            "showReuseMessage": false,
            "clear": true
         }
      },
      {
         "label": "buildRemote",
         "type": "shell",
         "command": "ssh ${config:sshUser}@${config:sshEndpoint} 'gcc  -g -std=${config:std} ${config:remoteDirectory}/${relativeFileDirname}/${fileBasename} ${config:libs} -o${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}'",
         "problemMatcher": [],
         "presentation": {
            "showReuseMessage": false,
            "clear": false
         }
      },
      {
         "label": "runRemote",
         "type": "shell",
         "command": "ssh ${config:sshUser}@${config:sshEndpoint} '${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}'",
         "problemMatcher": [
            "$gcc"
         ],
         "presentation": {
            "showReuseMessage": true,
            "clear": false
         }
      },
      {
         "label": "CopyBuildRunRemote",
         "dependsOrder": "sequence",
         "dependsOn": [
            "copyToRemote",
            "buildRemote",
            "runRemote"
         ],
         "problemMatcher": [],
         "group": {
            "kind": "build",
            "isDefault": true
         }
      },
      {
         "label": "CopyBuildRemote",
         "dependsOrder": "sequence",
         "dependsOn": [
            "copyToRemote",
            "buildRemote",
         ],
         "problemMatcher": [],
      },
      {
         "label": "StopREmoteC",
         "type": "shell",
         "command": "ssh ${config:sshUser}@${config:sshEndpoint} 'pkill ${fileBasenameNoExtension}'",
         "problemMatcher": [],
         "presentation": {
            "showReuseMessage": true,
         }
      },
      {
         "label": "copyARMheaders",
         "type": "shell",
         "command": "mkdir ${workspaceFolder}/include/; scp -r  ${config:sshUser}@${config:sshEndpoint}:/usr/include ${workspaceFolder}/include/ ",
         "problemMatcher": [],
         "presentation": {
            "showReuseMessage": true,
            "clear": true
         }
      },
   ],
}

c_cpp_properties.json for Mingw 

{
    "configurations": [
      {
        "name": "Win32",
        "includePath": [
                  "${workspaceFolder}/**",
                  "C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/i686-w64-mingw32/include"
                  ],
        "defines": [
                  "_DEBUG",
                  "UNICODE",
                  "_UNICODE"
                  ],
        "cStandard": "c99",
        "intelliSenseMode": "gcc-arm"
      }
    ],
   "version": 4
  }

 

IOT Raspberry Pi Programs

FrontCover300

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into a NetBeans of VS Code project. 

 

Note: The VS Code task listings are at the very end of this page.

The only downside is that you have to create a project to paste the code into.

To do this follow the instructionin the book- in particular remember to add the bcm2835 library and also any library references that may be needed. 

All of the programs below were copy and pasted from working programs in the IDE.

If anything you consider important is missing or if you have any requests or comments  contact me

This email address is being protected from spambots. You need JavaScript enabled to view it.

 

Page 32

#include <stdio.h>
#include <stdlib.h> 
int main(int argc, char** argv) {
    printf("Hello C World");
    return(EXIT_SUCCESS); 
}
 

Page 38

#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_delay(500);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
        bcm2835_delay(500);
    }
    bcm2835_close();
    return 0;
}
 

Page 50

#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    for (;;)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}
 

Page 54

#define _DEFAULT_SOURCE
#include <bcm2835.h>
#include <stdio.h>
#include <time.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    volatile int i;
    struct timespec delay = {0, 10 * 1000};
    for (;;)
    {
        bcm2835_gpio_set(RPI_BPLUS_GPIO_J8_07);
        nanosleep(&delay, NULL);
        bcm2835_gpio_clr(RPI_BPLUS_GPIO_J8_07);
        nanosleep(&delay, NULL);
    }
    bcm2835_close();
    return 0;
}
 

Page 56

#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    volatile int i;
    int n = 10;
    for (;;)
    {
        for (i = 0; i < n; i++)
        {
        };
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        for (i = 0; i < n; i++)
        {
        };
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}
 

Page 57

 
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <time.h> 

#define BILLION 1000000000L 

int main(int argc, char** argv) {
    struct timespec btime, etime;

    volatile int i;
    clock_gettime(CLOCK_REALTIME, &btime);
    for (i = 0; i < 10000000; i++) {
    };
    clock_gettime(CLOCK_REALTIME, &etime);
    double nseconds =  (double) ((etime.tv_sec - btime.tv_sec)* BILLION)+(double) (etime.tv_nsec - btime.tv_nsec);
    int n = (int) 10 /nseconds * BILLION + 0.5;
    printf("time = %f (s)  \n \r",nseconds / BILLION);
    printf("n= %d \n\r", n);
    return (EXIT_SUCCESS);
}

Page 58

 
#include <bcm2835.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07,
                      BCM2835_GPIO_FSEL_OUTP);
    for (;;)
    {
        bcm2835_gpio_set(RPI_BPLUS_GPIO_J8_07);
        bcm2835_delayMicroseconds(1);
        bcm2835_gpio_clr(RPI_BPLUS_GPIO_J8_07);
        bcm2835_delayMicroseconds(1);
    }
    bcm2835_close();
    return 0;
}
 

Page 59

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07,
                      BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11,
                      BCM2835_GPIO_FSEL_OUTP);
    volatile int i;
    for (;;)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
    }
    return (EXIT_SUCCESS);
}
 

Page 60

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    uint32_t mask = (1 << RPI_BPLUS_GPIO_J8_07) | (1 << RPI_BPLUS_GPIO_J8_11);
    for (;;)
    {
        bcm2835_gpio_set_multi(mask);
        bcm2835_gpio_clr_multi(mask);
    }

    return (EXIT_SUCCESS);
}
 

 Page 81

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);

    while (1)
    {
        if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
        {
            printf("Line Low \n\r");
            fflush(stdout);
        };
    }
    return 0;
}
 

Page 82

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);

    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        bcm2835_delayMicroseconds(1000);
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        bcm2835_delayMicroseconds(1000);
        printf("Button Push \n\r");
        fflush(stdout);
    }
    return 0;
}
 

Page 83

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    uint64_t t;
    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        t = bcm2835_st_read();
        bcm2835_delayMicroseconds(1000);
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000);
        if (t > 5000000)
        {
            printf("Putton held \n\r");
        }
        else
        {
            printf("Button Push \n\r");
        }
        fflush(stdout);
    }
    return 0;
}
 

Page 84

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{

    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);

    volatile int i;
    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        for (i = 0; i < 5000; i++)
        {
            if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        printf("%d\n\r", i);
        fflush(stdout);
    }
    return (EXIT_SUCCESS);
}
 

Page 85

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    volatile int i;
    uint64_t t;
    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        t = bcm2835_st_read();
        for (i = 0; i < 5000; i++)
        {
            if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        t = bcm2835_st_read() - t;
        printf("%d,%llu\n\r", i, t);
        fflush(stdout);
    }
    return (EXIT_SUCCESS);
}
 

Page 86

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);

    uint64_t t;
    while (1)
    {
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        t = bcm2835_st_read();
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
            ;
        t = bcm2835_st_read() - t;
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
    }
    return (EXIT_SUCCESS);
}
 

 Page 89

 
 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    uint64_t t;
    int s = 0;
    int i;
    while (1)
    {
        t = bcm2835_st_read();
        i = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);
        switch (s)
        {
        case 0: //Button not pushed
            if (!i)
            {
                s = 1;
                printf("Button Push \n\r");
                fflush(stdout);
            }
            break;
        case 1: //Button pushed
            if (i)
            {
                s = 0;
            }
            break;
        default:
            s = 0;
        }
        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000 - t);
    }
    return 0;
}

Page 91

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    uint64_t t, tpush = 0;
    int s = 0, i;
    while (1)
    {
        t = bcm2835_st_read();
        i = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);
        switch (s)
        {
        case 0: //Button not pushed
            if (!i)
            {
                s = 1;
                tpush = t;
            }
            break;
        case 1: //Button pushed
            if (i)
            {
                s = 0;
                if ((t - tpush) > 5000000)
                {
                    printf("Button held \n\r");
                }
                else
                {
                    printf("Button pushed \n\r");
                }
                fflush(stdout);
            }
            break;
        default:
            s = 0;
        }
        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000 - t);
    }
    return 0;
}
 

Page 92

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_13, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_15, BCM2835_GPIO_FSEL_OUTP);

    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, LOW);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, LOW);

    uint64_t t;

    int buttonState = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);

    int state = 0;
    while (1)
    {

        t = bcm2835_st_read();
        int buttonNow = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);
        int edge = buttonState - buttonNow;
        buttonState = buttonNow;

        switch (state)
        {
        case 0:
            if (edge)
            {
                state = 1;
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, HIGH);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, LOW);
            }
            break;
        case 1:
            if (edge)
            {
                state = 2;
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, HIGH);
            }
            break;
        case 2:
            if (edge)
            {
                state = 0;
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, LOW);
            }
            break;
        }

        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000 - t);
    }
    return 0;
}
 

Page 103

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd;
    struct gpiochip_info info;

    fd = open("/dev/gpiochip0", O_RDONLY);

    int ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &info);
    close(fd);
    printf("label: %s\n name: %s\n number of lines: %u\n", info.label, info.name, info.lines);
    return 0;
}
 

Page 106

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd, ret;

    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    req.lineoffsets[1] = 17;
    req.flags = GPIOHANDLE_REQUEST_OUTPUT;
    req.default_values[0] = 0;
    req.default_values[1] = 0;
    strcpy(req.consumer_label, "Output test");
    req.lines = 2;

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    close(fd);

    struct gpiohandle_data data;
    data.values[0] = 0;
    data.values[1] = 1;
    while (1)
    {
        data.values[0] = !data.values[0];
        data.values[1] = !data.values[1];
        ret = ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
    }
    return 0;
}
 

Page 107

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd, ret;

    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    req.lineoffsets[1] = 17;
    req.flags = GPIOHANDLE_REQUEST_INPUT;
    strcpy(req.consumer_label, "Input test");
    req.lines = 2;

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    close(fd);

    struct gpiohandle_data data;
    ret = ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
    printf("%hhu , %hhu", data.values[0], data.values[1]);
    close(req.fd);
    return 0;
}
 

Page 114

Note a full program just a function definition
 
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void checkIRQ()
{
    FILE *fp = popen("sudo dtparam -l", "r");
    if (fp == NULL)
    {
        printf("Failed to run command\n\r");
        exit(1);
    }
    char output[1024];
    int txfound = 0;
    while (fgets(output, sizeof(output), fp) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, "gpio-no-irq") != NULL)
        {
            txfound = 1;
        }
    }
    pclose(fp);

    if (txfound == 0)
    {
        fp = popen("sudo dtoverlay gpio-no-irq", "r");
        if (fp == NULL)
        {
            printf("Failed to run command\n\r");
            exit(1);
        }
        pclose(fp);
    }
}
 

Page 118

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_ren(RPI_BPLUS_GPIO_J8_07);

    volatile int i;
    uint64_t t;
    while (1)
    {
        bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
        while (0 == bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
            ;
        t = bcm2835_st_read();
        bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
        for (i = 0; i < 5000; i++)
        {
            if (1 == bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        t = bcm2835_st_read() - t;
        printf("%d,%llu\n\r", i, t);
        fflush(stdout);
    }
    return (EXIT_SUCCESS);
}
 

Page 119

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_clr_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);

    uint64_t t;
    while (1)
    {
        bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
        t = bcm2835_st_read();
        for (;;)
        {
            if (1 == bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        t = bcm2835_st_read() - t;
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
    }
    return (EXIT_SUCCESS);
}
 

 Page 120

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    printf("Press button \n\r");
    fflush(stdout);
    sleep(20);
    if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
    {
        printf("Button pressed \n\r");
    }
    else
    {
        printf("No Button press\n\r");
    };
    return 0;
}
 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    bcm2835_gpio_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
    printf("Press button \n\r");
    fflush(stdout);
    sleep(20);
    if (bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
    {
        printf("Button pressed \n\r");
    }
    else
    {
        printf("No Button press\n\r");
    };
    return 0;
}
 

 Page 124

 
#include <string.h>
#include <stdio.h> 
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
#include <sys/epoll.h>

int main(int argc, char **argv) {
    int fd, ret;

    struct gpioevent_request req;
    req.lineoffset = 4;
    req.handleflags = GPIOHANDLE_REQUEST_INPUT;
    req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE;
    strcpy(req.consumer_label, "Event test");

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &req);
    close(fd);

    static struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = req.fd;
    int epfd = epoll_create(1);
    int res = epoll_ctl(epfd, EPOLL_CTL_ADD, req.fd, &ev);

    int nfds = epoll_wait(epfd, &ev, 1, 20000);
    if (nfds != 0) {
        struct gpioevent_data edata;
        read(req.fd, &edata, sizeof edata);
        printf("%u,%llu", edata.id, edata.timestamp);
    }
}
 

Page 129

 
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
#include <sys/epoll.h>

#include <pthread.h>
uint64_t t[20];
typedef void (*eventHandler)(int);

typedef struct
{
    int epfd;
    int fd;
    eventHandler func;
} intVec;

void myHandler(int fd)
{
    struct gpioevent_data edata;
    read(fd, &edata, sizeof edata);
    printf("%u,%llu \n\r", edata.id, edata.timestamp);
    fflush(stdout);
}
void *waitInterrupt(void *arg)
{
    intVec *intData = (intVec *)arg;
    struct epoll_event ev;
    for (;;)
    {
        int nfds = epoll_wait(intData->epfd, &ev, 1, 20000);

        if (nfds != 0)
        {
            intData->func(intData->fd);
        }
    }
}
int main(int argc, char **argv)
{
    int fd, ret;
    struct gpioevent_request req;
    req.lineoffset = 4;
    req.handleflags = GPIOHANDLE_REQUEST_INPUT;
    req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE;
    strcpy(req.consumer_label, "Event test");

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &req);
    close(fd);
    static struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = req.fd;
    int epfd = epoll_create(1);
    int res = epoll_ctl(epfd, EPOLL_CTL_ADD, req.fd, &ev);
    intVec intData;
    intData.epfd = epfd;
    intData.fd = req.fd;
    intData.func = &myHandler;
    pthread_t intThread;
    if (pthread_create(&intThread, NULL, waitInterrupt,
                       (void *)&intData))
    {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    for (;;)
    {
        printf("Working\n\r");
        fflush(stdout);
        sleep(2);
    }
}
 

page 131

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <bcm2835.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>

#define BUFFER_MAX 50

typedef void (*eventHandler)();

int openGPIO(int pin, int direction);
int writeGPIO(int gpio, int value);
int readGPIO(int gpio);
int setEdgeGPIO(int gpio, char *edge);
void *waitInterrupt(void *arg);
int attachGPIO(int gpio, char *edge, eventHandler func);

int fd[32] = {0};
typedef struct
{
    int fd;
    int gpio;
    eventHandler func;
} intVec;

intVec intData;
static int count;

void myIntHandler()
{
    count++;
};
int main(int argc, char **argv)
{
    attachGPIO(4, "both", myIntHandler);
    for (;;)
    {
        printf("Interrupt %d\n\r", count);
        fflush(stdout);
    };
    return 0;
}

int openGPIO(int gpio, int direction)
{
    if (gpio < 0 || gpio > 31)
        return -1;
    if (direction < 0 || direction > 1)
        return -2;
    int len;
    char buf[BUFFER_MAX];
    if (fd[gpio] != 0)
    {
        close(fd[gpio]);
        fd[gpio] = open("/sys/class/gpio/unexport", O_WRONLY);
        len = snprintf(buf, BUFFER_MAX, "%d", gpio);
        write(fd[gpio], buf, len);
        close(fd[gpio]);
        fd[gpio] = 0;
    }

    fd[gpio] = open("/sys/class/gpio/export", O_WRONLY);
    len = snprintf(buf, BUFFER_MAX, "%d", gpio);
    write(fd[gpio], buf, len);
    close(fd[gpio]);
    len = snprintf(buf, BUFFER_MAX,
                   "/sys/class/gpio/gpio%d/direction", gpio);
    fd[gpio] = open(buf, O_WRONLY);
    if (direction == 1)
    {
        write(fd[gpio], "out", 4);
        close(fd[gpio]);
        len = snprintf(buf, BUFFER_MAX,
                       "/sys/class/gpio/gpio%d/value", gpio);
        fd[gpio] = open(buf, O_WRONLY);
    }
    else
    {
        write(fd[gpio], "in", 3);
        close(fd[gpio]);
        len = snprintf(buf, BUFFER_MAX,
                       "/sys/class/gpio/gpio%d/value", gpio);
        fd[gpio] = open(buf, O_RDONLY);
    }
    return 0;
}

int writeGPIO(int gpio, int b)
{
    if (b == 0)
    {
        write(fd[gpio], "0", 1);
    }
    else
    {
        write(fd[gpio], "1", 1);
    }

    lseek(fd[gpio], 0, SEEK_SET);
    return 0;
}

int readGPIO(int gpio)
{
    char value_str[3];
    int c = read(fd[gpio], value_str, 3);
    lseek(fd[gpio], 0, SEEK_SET);

    if (value_str[0] == '0')
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

int setEdgeGPIO(int gpio, char *edge)
{
    char buf[BUFFER_MAX];
    int len = snprintf(buf, BUFFER_MAX,
                       "/sys/class/gpio/gpio%d/edge", gpio);
    int fd = open(buf, O_WRONLY);
    write(fd, edge, strlen(edge) + 1);
    close(fd);
    return 0;
}

int attachGPIO(int gpio, char *edge, eventHandler func)
{
    openGPIO(gpio, 0);
    setEdgeGPIO(gpio, edge);
    readGPIO(gpio);
    intData.fd = fd[gpio];
    intData.gpio = gpio;
    intData.func = func;
    pthread_t intThread;
    if (pthread_create(&intThread,
                       NULL, waitInterrupt, (void *)&intData))
    {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    return 0;
}
void *waitInterrupt(void *arg)
{

    intVec *intData = (intVec *)arg;
    int gpio = intData->gpio;
    struct pollfd fdset[1];
    fdset[0].fd = intData->fd;
    fdset[0].events = POLLPRI;
    fdset[0].revents = 0;
    for (;;)
    {
        int rc = poll(fdset, 1, -1);
        if (fdset[0].revents & POLLPRI)
        {
            intData->func();
            lseek(fdset[0].fd, 0, SEEK_SET);
            readGPIO(gpio);
        }
    }
    pthread_exit(0);
}

Page 143

#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 2);
    bcm2835_pwm_set_data(0, 1);
    return (0);
}
 

Page 144

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_gpio_fsel(13, BCM2835_GPIO_FSEL_ALT0);
    bcm2835_pwm_set_clock(2);

    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 2);
    bcm2835_pwm_set_data(0, 1);

    bcm2835_pwm_set_mode(1, 1, 1);
    bcm2835_pwm_set_range(1, 8);
    bcm2835_pwm_set_data(1, 2);
    return (EXIT_SUCCESS);
}
 

Page 145

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 256);
    for (;;)
    {
        bcm2835_pwm_set_data(0, 16);
        bcm2835_delayMicroseconds((int)26.666 * 8);
        bcm2835_pwm_set_data(0, 128);
        bcm2835_delayMicroseconds((int)26.666 * 8);
    }
    return (EXIT_SUCCESS);
}
 

Page 147

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 256);
    for (;;)
    {
        bcm2835_pwm_set_data(0, 16);
        bcm2835_delayMicroseconds((int)26.666 * 8);
        bcm2835_pwm_set_data(0, 128);
        bcm2835_delayMicroseconds((int)26.666 * 8);
    }
    return (EXIT_SUCCESS);
}
 

Page 148

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    int C = 34091;
    bcm2835_pwm_set_range(0, C);
    bcm2835_pwm_set_data(0, C / 2);
    return (EXIT_SUCCESS);
}

Page 150

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv){
    if (!bcm2835_init())
            return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);
    int w = 1;
    int inc = 1;
    for (;;)
    {
        bcm2835_pwm_set_data(0, w);
        w = w + inc;
        if (w > 1024 || w <= 0)
            inc = -inc;
        bcm2835_delayMicroseconds(5000);
    }
    return (EXIT_SUCCESS);
}
    bcm2835_delayMicroseconds(5000);
    }
    return (EXIT_SUCCESS);
}
 

Page 151

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);
    int w = 0;
    int inc = 1;
    for (;;)
    {
        bcm2835_pwm_set_data(0, w * w * w);
        w = w + inc;
        if (w > 10 || w <= 0)
            inc = -inc;
        bcm2835_delayMicroseconds(50000);
    }
    return (EXIT_SUCCESS);
}
 

Page 152

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);
    int w = 0;
    int inc = 1;

    for (;;)
    {
        bcm2835_pwm_set_data(0, (w * w * w) >> 3);
        w = w + inc;
        if (w > 20 || w <= 0)
            inc = -inc;
        bcm2835_delayMicroseconds(50000);
    }
    return (EXIT_SUCCESS);
}
 

Page 155

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(375);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);

    for (;;)
    {
        bcm2835_pwm_set_data(0, 25);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 50);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 128);
        bcm2835_delayMicroseconds(2000000);
    }
    return (EXIT_SUCCESS);
}
 

Page 156 

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(375);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);

    for (;;)
    {
        bcm2835_pwm_set_data(0, 52 * 0 / 180 + 920);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 52 * 90 / 180 + 920);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 52 * 180 / 180 + 920);
        bcm2835_delayMicroseconds(2000000);
    }
    return (EXIT_SUCCESS);
}

Page 158

Function only - needs to run as root.
 
void bcm2835_pwm_set_clock_source(
    uint32_t source,
    uint32_t divisorI,
    uint32_t divisorF)
{
    divisorI &= 0xfff;
    divisorF &= 0xfff;
    source &= 0xf;
    uint8_t mask = bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0xffffffef;
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | mask);
    while ((bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0x80) != 0)
    {
    };
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | source | 0x200);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | 0x210 | source);
}
 

Page 160

 This needs to be run as root.
 
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <bcm2835.h>

void bcm2835_pwm_set_clock_source(uint32_t source,uint32_t divisorI,uint32_t divisorF)
{
    divisorI &= 0xfff;
    divisorF &= 0xfff;
    source &= 0xf;
    uint8_t mask = bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) &  0xffffffef;
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL,  BCM2835_PWM_PASSWRD | mask);
    while ((bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0x80) != 0)
    {
    };
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | source | 0x200);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | 0x210 | source);
}

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock_source(6, 2, 0);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 256);
    int i;
    for (;;)
    {
        for (i = 0; i < 256; i = i + 10)
        {
            bcm2835_pwm_set_data(0, i);
            bcm2835_delayMicroseconds(2);
        }
    }
    return (EXIT_SUCCESS);
}
 

Page 178 

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    char buf[] = {0xE7};
    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_148);
    bcm2835_i2c_setSlaveAddress(0x40);
    bcm2835_i2c_write(buf, 1);
    bcm2835_i2c_read(buf, 1);
    printf("User Register = %X \r\n", buf[0]);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}
 

 Page 178

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

void setTimeout(uint32_t timeout) {
    volatile uint32_t* stimeout = bcm2835_bsc1 + BCM2835_BSC_CLKT / 4;
    bcm2835_peri_write(stimeout, timeout);
}

int main(int argc, char** argv) {
    if (!bcm2835_init())
        return 1;

    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_150);
    setTimeout(0);
    char buf[4] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n\r lsb %d \n\r checksum %d \n\r", msb, lsb, check);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}
 

Page 180 

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

void setTimeout(uint32_t timeout)
{
    volatile uint32_t *stimeout = bcm2835_bsc1 + BCM2835_BSC_CLKT / 4;
    bcm2835_peri_write(stimeout, timeout);
}

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_2500);
    setTimeout(20000);
    char buf[3] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n\r lsb %d \n\r checksum %d \n\r", msb, lsb, check);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}
 

Page 184

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

void setTimeout(uint16_t timeout);
uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check);
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_2500);
    setTimeout(20000);
    char buf[4] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];

    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    unsigned int data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float temp = (float)(-46.85 + (175.72 * data16 / (float)65536));
    printf("Temperature %f C \n\r", temp);

    buf[0] = 0xF5;
    bcm2835_i2c_write(buf, 1);
    while (bcm2835_i2c_read(buf, 3) == BCM2835_I2C_REASON_ERROR_NACK)
    {
        bcm2835_delayMicroseconds(500);
    };
    msb = buf[0];
    lsb = buf[1];
    check = buf[2];
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float hum = -6 + (125.0 * (float)data16) / 65536;
    printf("Humidity %f %% \n\r", hum);
    bcm2835_i2c_end();

    return (EXIT_SUCCESS);
}

void setTimeout(uint16_t timeout)
{
    volatile uint32_t *stimeout = bcm2835_bsc1 + BCM2835_BSC_CLKT / 4;
    bcm2835_peri_write(stimeout, timeout);
}

uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check)
{
    uint32_t data32 = ((uint32_t)msb << 16) | ((uint32_t)lsb << 8) | (uint32_t)check;
    uint32_t divisor = 0x988000;
    for (int i = 0; i < 16; i++)
    {
        if (data32 & (uint32_t)1 << (23 - i))
            data32 ^= divisor;
        divisor >>= 1;
    };
    return (uint8_t)data32;
}
 

Page 195 

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>

uint8_t getByte(int b, int buf[]);
void GetDHT22data(uint8_t pin);

int main(int argc, char **argv)
{
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(1000);
    GetDHT22data(RPI_BPLUS_GPIO_J8_07);
    return 0;
}

void GetDHT22data(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(1000);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    int i;
    for (i = 1; i < 2000; i++)
    {
        if (bcm2835_gpio_lev(pin) == 0)
            break;
    };
    uint64_t t;
    int buf[41];
    int j;
    bcm2835_delayMicroseconds(1);
    for (j = 0; j < 41; j++)
    {
        for (i = 1; i < 2000; i++)
        {
            if (bcm2835_gpio_lev(pin) == 1)
                break;
        };
        t = bcm2835_st_read();
        for (i = 1; i < 2000; i++)
        {
            if (bcm2835_gpio_lev(pin) == 0)
                break;
        }
        buf[j] = (bcm2835_st_read() - t) > 50;
    }

    int byte1 = getByte(1, buf);
    int byte2 = getByte(2, buf);
    int byte3 = getByte(3, buf);
    int byte4 = getByte(4, buf);
    int byte5 = getByte(5, buf);
    printf("Checksum %d %d \n\r", byte5, (byte1 + byte2 + byte3 + byte4) & 0xFF);
    float humidity = (float)(byte1 << 8 | byte2) / 10.0;
    printf("Humidity= %f \n\r", humidity);
    float temperature;
    int neg = byte3 & 0x80;
    byte3 = byte3 & 0x7F;
    temperature = (float)(byte3 << 8 | byte4) / 10.0;
    if (neg > 0)
        temperature = -temperature;
    printf("Temperature= %f \n\r", temperature);
    return;
}

uint8_t getByte(int b, int buf[])
{
    int i;
    uint8_t result = 0;
    b = (b - 1) * 8 + 1;
    for (i = b; i <= b + 7; i++)
    {
        result = result << 1;
        result = result | buf[i];
    }
    return result;
}
 

Page 216

 
#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>

int presence(uint8_t pin);
void writeByte(uint8_t pin, int byte);
uint8_t crc8(uint8_t *data, uint8_t len);
int readByte(uint8_t pin);
int readiButton(uint8_t pin, uint8_t *data);

int main(int argc, char **argv)
{
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);

    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);

    int i;
    uint8_t code[8];
    for (;;)
    {
        int p = readiButton(RPI_BPLUS_GPIO_J8_07, code);
        if (p == 1)
        {
            for (i = 0; i < 8; i++)
            {
                printf("%hhX ", code[i]);
            }
            printf("\n\r");
            fflush(stdout);
        }
        bcm2835_delayMicroseconds(100000);
    };
    bcm2835_close();
    return 0;
}

int presence(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(480);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(70);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(410);
    return b;
}

void writeBit(uint8_t pin, int b)
{

    int delay1, delay2;
    if (b == 1)
    {
        delay1 = 6;
        delay2 = 64;
    }
    else
    {
        delay1 = 80;
        delay2 = 10;
    }
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(delay1);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(delay2);
}

uint8_t readBit(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(6);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(9);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(55);
    return b;
}

void writeByte(uint8_t pin, int byte)
{
    int i;
    for (i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(pin, 1);
        }
        else
        {
            writeBit(pin, 0);
        }
        byte = byte >> 1;
    }
}

int readByte(uint8_t pin)
{
    int byte = 0;
    int i;
    for (i = 0; i < 8; i++)
    {
        byte = byte | readBit(pin) << i;
    };
    return byte;
}
uint8_t crc8(uint8_t *data, uint8_t len)
{

    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++)
    {
        databyte = data[i];
        for (j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;

            databyte >>= 1;
        }
    }

    return crc;
}

int readiButton(uint8_t pin, uint8_t *data)
{
    int b = presence(pin);
    if (b != 0)
        return 0;
    writeByte(pin, 0x33);
    int i;
    for (i = 0; i < 8; i++)
    {
        data[i] = readByte(pin);
    }
    uint8_t crc = crc8(data, 8);
    if (crc == 0)
        return 1;
    return 0;
}
 

 Page 227

#include <bcm2835.h>
#include <stdio.h>

int presence(uint8_t pin);
void writeBit(uint8_t pin, int b);
void writeByte(uint8_t pin, int byte);
uint8_t readBit(uint8_t pin);
int convert(uint8_t pin);
int readByte(uint8_t pin);
float getTemperature(uint8_t pin);
uint8_t crc8(uint8_t *data, uint8_t len);

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    if (presence(RPI_BPLUS_GPIO_J8_07) == 1)
    {
        printf("No device \n");
    }
    else
    {
        printf("Device present \n");
    }
    fflush(stdout);
    float t;
    for (;;)
    {
        do
        {
            t = getTemperature(RPI_BPLUS_GPIO_J8_07);
        } while (t < -999);
        printf("%f\r\n", t);
        fflush(stdout);
    };
    bcm2835_close();

    return 0;
}

int presence(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(480);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(70);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(410);
    return b;
}

void writeBit(uint8_t pin, int b)
{
    int delay1, delay2;
    if (b == 1)
    {
        delay1 = 6;
        delay2 = 64;
    }
    else
    {

        delay1 = 60;
        delay2 = 10;
    }
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(delay1);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(delay2);
}

void writeByte(uint8_t pin, int byte)
{
    int i;
    for (i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(pin, 1);
        }
        else
        {

            writeBit(pin, 0);
        }
        byte = byte >> 1;
    }
}

uint8_t readBit(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(8);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(2);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(60);
    return b;
}

int convert(uint8_t pin)
{
    int i;
    writeByte(pin, 0x44);
    for (i = 0; i < 5000; i++)
    {
        bcm2835_delayMicroseconds(100000);
        if (readBit(pin) == 1)
            break;
    }
    return i;
}

float getTemperature(uint8_t pin)
{
    if (presence(pin) == 1)
        return -1000;
    writeByte(pin, 0xCC);
    if (convert(pin) == 5000)
        return -3000;
    presence(pin);
    writeByte(pin, 0xCC);
    writeByte(pin, 0xBE);
    int i;
    uint8_t data[9];
    for (i = 0; i < 9; i++)
    {
        data[i] = readByte(pin);
    }
    uint8_t crc = crc8(data, 9);
    if (crc != 0)
        return -2000;
    int t1 = data[0];
    int t2 = data[1];
    int16_t temp1 = (t2 << 8 | t1);
    float temp = (float)temp1 / 16;
    return temp;
}

int readByte(uint8_t pin)
{
    int byte = 0;
    int i;
    for (i = 0; i < 8; i++)
    {
        byte = byte | readBit(pin) << i;
    };
    return byte;
}

uint8_t crc8(uint8_t *data, uint8_t len)
{
    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++)
    {
        databyte = data[i];
        for (j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;
            databyte >>= 1;
        }
    }
    return crc;
}
 

Page 243

function only - needs a main program to call it

int oneWireScan(uint8_t pin, uint64_t serial[])
{
    static int bitcount = 0;
    static int deviceCount = 0;

    if (bitcount > 63)
    {
        bitcount = 0;
        deviceCount++;
        return deviceCount;
    }

    if (bitcount == 0)
    {
        if (presence(pin) == 1)
        {
            bitcount = 0;
            return deviceCount;
        }
        deviceCount = 0;
        serial[deviceCount] = 0;
        writeByte(pin, 0xF0);
    };

    int b1 = readBit(pin);
    int b2 = readBit(pin);

    if (b1 == 0 && b2 == 1)
    {
        serial[deviceCount] >>= 1;
        writeBit(pin, 0);
        bitcount++;
        oneWireScan(pin, serial);
    };

    if (b1 == 1 && b2 == 0)
    {
        serial[deviceCount] >>= 1;
        serial[deviceCount] |= 0x8000000000000000LL;
        writeBit(pin, 1);
        bitcount++;
        oneWireScan(pin, serial);
    };

    if (b1 == 1 && b2 == 1)
    {
        bitcount = 0;
        return deviceCount;
    };
    if (b1 == 0 && b2 == 0)
    {
        serial[deviceCount] >>= 1;
        writeBit(pin, 0);
        int bitposition = bitcount;
        bitcount++;
        oneWireScan(pin, serial);

        bitcount = bitposition;
        if (presence(pin) == 1)
        {
            bitposition = 0;
            return 0;
        }

        writeByte(pin, 0xF0);
        uint64_t temp = serial[deviceCount - 1] | (0x1LL << (bitcount));
        int i;
        uint64_t bit;
        for (i = 0; i < bitcount + 1; i++)
        {
            bit = temp & 0x01LL;
            temp >>= 1;
            b1 = readBit(pin);
            b2 = readBit(pin);
            writeBit(pin, bit);
            serial[deviceCount] >>= 1;
            serial[deviceCount] |= (bit << 63);
        }
        bitcount++;
        oneWireScan(pin, serial);
    };

    return deviceCount;
}
 

Page 265

#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main(int argc, char **argv)
{
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    return 0;
}
 

Page 266

#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    char buf[] = "hello world";
    char buf2[11];
    int count = write(sfd, buf, 11);
    count = read(sfd, buf2, 11);
    buf2[11] = 0;
    printf("%s", buf2);
    close(sfd);
    return 0;
}

Page 275

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>

int main(int argc, char **argv)
{
    int sfd = open("/dev/ttyAMA1", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    cfmakeraw(&options);
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 1;
    tcsetattr(sfd, TCSANOW, &options);
    char buf[] = "hello world";
    char buf2[11];
    int count = write(sfd, buf, 11);
    count = read(sfd, buf2, 11);
    buf2[11] = 0;
    printf("%s", buf2);
    close(sfd);
    return 0;
}
 

Page 276

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>

int main(int argc, char **argv)
{
    system("sudo systemctl stop serial-getty@serial0 .service");
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    cfmakeraw(&options);
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 1;
    options.c_cc[VMIN] = 100;
    tcsetattr(sfd, TCSANOW, &options);
    char buf[] = "hello world";
    char buf2[100];
    int count = write(sfd, buf, strlen(buf));
    usleep(100000);
    int bytes;
    ioctl(sfd, FIONREAD, &bytes);
    if (bytes != 0)
    {
        count = read(sfd, buf2, 100);
    }
    printf("%s\n\r", buf2);
    close(sfd);
    return (EXIT_SUCCESS);
}
 

Page 278

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>

int main(int argc, char **argv)
{
    system("sudo systemctl stop serial-getty@serial0 .service");
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };

    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    cfmakeraw(&options);
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 0;
    tcsetattr(sfd, TCSANOW, &options);

    char buf[] = "hello world";
    char buf2[100];
    char c;
    int count = write(sfd, buf, strlen(buf) + 1);

    int i = 0;
    while (1)
    {
        count = read(sfd, &c, 1);
        if (count != 0)
        {
            buf2[i] = c;
            i++;
            if (c == 0)
                break;
        };
    };
    printf("%s\n\r", buf2);
    close(sfd);
    return (EXIT_SUCCESS);
}
 

Page 284

 
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <stdint.h>

int openPort(char port[]);
int presence(int sfd);
void writeBit(int sfd, int b);
uint8_t readBit(int sfd);
void writeByte(int sfd, int byte);
int readByte(int sfd);
int readByte(int sfd);
float getTemperature(int sfd);
int convert(int sfd);

uint8_t crc8(uint8_t *data, uint8_t len);

int main(int argc, char **argv)
{
    int sfd = openPort("/dev/ttyAMA1");
    if (presence(sfd) == 0)
    {
        printf("Device Present\n\r");
    }
    else
    {
        printf("No Device\n\r");
    }
    for (;;)
    {
        float temp = getTemperature(sfd);
        printf("%f \n\r", temp);

        fflush(stdout);
    }
    close(sfd);
    return 0;
}

int openPort(char port[])
{
    int sfd = open(port, O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B115200);
    cfmakeraw(&options);
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag |= PARENB;
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 1;
    tcsetattr(sfd, TCSADRAIN, &options);
    return sfd;
}

int presence(int sfd)
{
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    tcsetattr(sfd, TCSADRAIN, &options);

    char buf = 0xF0;
    int count = write(sfd, &buf, 1);
    count = read(sfd, &buf, 1);

    tcgetattr(sfd, &options);
    cfsetspeed(&options, B115200);
    tcsetattr(sfd, TCSADRAIN, &options);
    if (buf == 0xF0)
        return -1;
    return 0;
}

void writeBit(int sfd, int b)
{
    char buf;
    if (b == 0)
    {
        buf = 0x00;
    }
    else
    {
        buf = 0xFF;
    }
    int count = write(sfd, &buf, 1);
    count = read(sfd, &buf, 1);
}

uint8_t readBit(int sfd)
{
    char buf;
    buf = 0xFF;
    int count = write(sfd, &buf, 1);
    count = read(sfd, &buf, 1);
    if (buf == 0xFF)
        return 1;
    return 0;
}

void writeByte(int sfd, int byte)
{
    for (int i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(sfd, 1);
        }
        else
        {
            writeBit(sfd, 0);
        }
        byte = byte >> 1;
    }
}

int readByte(int sfd)
{
    int byte = 0;
    for (int i = 0; i < 8; i++)
    {
        byte = byte | readBit(sfd) << i;
    };
    return byte;
}

int convert(int sfd)
{
    int i;
    writeByte(sfd, 0x44);
    for (i = 0; i < 5000; i++)
    {
        usleep(100000);
        if (readBit(sfd) != 0)
            break;
    }
    return i;
}

uint8_t crc8(uint8_t *data, uint8_t len)
{
    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++)
    {
        databyte = data[i];
        for (j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;
            databyte >>= 1;
        }
    }
    return crc;
}

float getTemperature(int sfd)
{
    if (presence(sfd) == -1)
        return -1000;
    writeByte(sfd, 0xCC);
    if (convert(sfd) == 5000)
        return -3000;

    presence(sfd);
    writeByte(sfd, 0xCC);
    writeByte(sfd, 0xBE);

    uint8_t data[9];
    for (int i = 0; i < 9; i++)
    {
        data[i] = readByte(sfd);
    }

    uint8_t crc = crc8(data, 9);
    if (crc != 0)
        return -2000;
    int t1 = data[0];
    int t2 = data[1];
    int16_t temp1 = (t2 << 8 | t1);
    float temp = (float)temp1 / 16;
    return temp;
}
 

Page 299

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
    {
        return 1;
    }
    if (!bcm2835_spi_begin())
    {
        return 1;
    }

    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536);
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
    uint8_t read_data = bcm2835_spi_transfer(0xAA);
    if (read_data == 0xAA)
    {
        printf("data received correctly");
    }
    else
    {
        printf("data error");
    };
    bcm2835_spi_end();
    bcm2835_close();
    return (EXIT_SUCCESS);
}
 

 Page 308

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
    {
        return 1;
    }
    if (!bcm2835_spi_begin())
    {
        return 1;
    }
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_8192);
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);

    char buf[] = {0x01, 0x80, 0x00};
    char readBuf[3];
    bcm2835_spi_transfernb(buf, readBuf, 3);
    int data = ((int)readBuf[1] & 0x03) << 8 | (int)readBuf[2];
    float volts = (float)data * 3.3f / 1023.0f;

    printf("%f", volts);
    bcm2835_spi_end();
    bcm2835_close();
    return (EXIT_SUCCESS);
}

Page 320

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    addr.sin_addr.s_addr = 0x22d8b85d;
    if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        return -1;
    char header[] = "GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n";
    int n = write(sockfd, header, strlen(header));
    char buffer[2048];
    n = read(sockfd, buffer, 2048);
    printf("%s", buffer);
    return (EXIT_SUCCESS);
}
 

Page 322

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>

int main(int argc, char **argv)
{
    struct addrinfo hints;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    struct addrinfo *servinfo;
    int status = getaddrinfo("www.example.com", "80", &hints, &servinfo);
    int sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
    connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen);
    char header[] = "GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n";
    int n = write(sockfd, header, strlen(header));
    char buffer[2048];
    n = read(sockfd, buffer, 2048);
    printf("%s", buffer);
    return (EXIT_SUCCESS);
}
 

Page 327

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

int main(int argc, char **argv)
{
    struct addrinfo hints, *server;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    getaddrinfo(NULL, "80", &hints, &server);
    int sockfd = socket(server->ai_family, server->ai_socktype | SOCK_NONBLOCK, server->ai_protocol);
    bind(sockfd, server->ai_addr, server->ai_addrlen);
    listen(sockfd, 10);

    char buffer[2048];
    char html[] = "<html><head><title>Temperature</title></head><body><p>{\"humidity\":81%, \"airtemperature\":23.5C}</p></body></html>\r\n";

    char headers[1024] = {0};

    char Status[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\nServer:CPi\r\n";

    char Date[100];
    time_t now = time(NULL);
    struct tm *t = gmtime(&now);
    strftime(Date, sizeof(Date), "Date: %a, %d %b %Y %k:%M:%S %Z\r\n", t);

    char ContLen[100] = {0};
    snprintf(ContLen, sizeof ContLen, "Content-Length:%d \r\n", strlen(html));

    snprintf(headers, sizeof headers, "%s%s%s\r\n", Status, Date, ContLen);

    char data[2048] = {0};
    snprintf(data, sizeof data, "%s%s", headers, html);

    for (;;)
    {
        struct sockaddr_storage client_addr;
        socklen_t addr_size = sizeof client_addr;

        int client_fd = accept(sockfd, (struct sockaddr *)&client_addr, &addr_size);
        if (client_fd > 0)
        {
            int n = read(client_fd, buffer, 2048);
            printf("%s", buffer);
            fflush(stdout);
            n = write(client_fd, data, strlen(data));
            close(client_fd);
        }
    }
    return (EXIT_SUCCESS);
}
 

Page 346

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    int memfd = open("/dev/mem", O_RDWR | O_SYNC);
    uint32_t *map = (uint32_t *)mmap(
        NULL,
        4 * 1024,
        (PROT_READ | PROT_WRITE),
        MAP_SHARED,
        memfd,
        (off_t)bcm2835_peripherals_base + BCM2835_GPIO_BASE);
    if (map == MAP_FAILED)
        printf("mmap failed: %s\n", strerror(errno));
    close(memfd);
    volatile uint32_t *paddr = map;
    *paddr = 0x1000;
    volatile uint32_t *paddr1 = map + 0x1C / 4;
    volatile uint32_t *paddr2 = map + 0x28 / 4;
    for (;;)
    {
        *paddr1 = 0x10;
        *paddr2 = 0x10;
    };
    return (EXIT_SUCCESS);
}
 

Page 351

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    uint32_t *gpioBASE = bcm2835_regbase(BCM2835_REGBASE_GPIO);
    bcm2835_peri_write(gpioBASE, 0x1000);
    for (;;)
    {
        bcm2835_peri_write(gpioBASE + BCM2835_GPSET0 / 4, 0x10);
        bcm2835_peri_write(gpioBASE + BCM2835_GPCLR0 / 4, 0x10);
    }
    return 0;
}
 

Page 365

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

#define CLK_GP0_CTL 28
#define CLK_GP0_DIV 29
void bcm2835_GPIO4_set_clock_source(uint32_t, uint32_t, uint32_t);

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(4, BCM2835_GPIO_FSEL_ALT0);
    bcm2835_GPIO4_set_clock_source(6, 50, 0);
}

void bcm2835_GPIO4_set_clock_source(
    uint32_t source,
    uint32_t divisorI,
    uint32_t divisorF)
{
    divisorI &= 0xfff;
    divisorF &= 0xfff;
    source &= 0xf;

    uint8_t mask = bcm2835_peri_read(bcm2835_clk + CLK_GP0_CTL) & 0xffffffef;

    bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | mask);

    while ((bcm2835_peri_read(bcm2835_clk + CLK_GP0_CTL) & 0x80) != 0)
    {
    };

    bcm2835_peri_write(bcm2835_clk + CLK_GP0_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
    bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | source | 0x200);
    bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | 0x0210 | source);
}
 

Page 358 

#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>

#define BCM2835_SPI6_BASE 0x204C00
volatile uint32_t *bcm2835_spiOLD;

int bcm2835_spi6_begin(void)
{
    volatile uint32_t *paddr;
    bcm2835_spiOLD = bcm2835_spi0;
    bcm2835_spi0 = bcm2835_peripherals + BCM2835_SPI6_BASE / 4;

    bcm2835_gpio_fsel(27, BCM2835_GPIO_FSEL_ALT3); /* CE1 */
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT3); /* CE0 */
    bcm2835_gpio_fsel(19, BCM2835_GPIO_FSEL_ALT3); /* MISO */
    bcm2835_gpio_fsel(20, BCM2835_GPIO_FSEL_ALT3); /* MOSI */
    bcm2835_gpio_fsel(21, BCM2835_GPIO_FSEL_ALT3); /* CLK */

    paddr = bcm2835_spi0 + BCM2835_SPI0_CS / 4;
    bcm2835_peri_write(paddr, 0); /* All 0s */

    bcm2835_peri_write_nb(paddr, BCM2835_SPI0_CS_CLEAR);
    return 1;
}

void bcm2835_spi6_end(void)
{
    bcm2835_spi0 = bcm2835_spiOLD;
    /* Set all the SPI0 pins back to input */
    bcm2835_gpio_fsel(27, BCM2835_GPIO_FSEL_INPT); /* CE1 */
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_INPT); /* CE0 */
    bcm2835_gpio_fsel(19, BCM2835_GPIO_FSEL_INPT); /* MISO */
    bcm2835_gpio_fsel(20, BCM2835_GPIO_FSEL_INPT); /* MOSI */
    bcm2835_gpio_fsel(21, BCM2835_GPIO_FSEL_INPT); /* CLK */
}

int main(int argc, char **argv)
{
    if (!bcm2835_init())
    {
        return 1;
    }

    if (!bcm2835_spi6_begin())
    {
        return 1;
    }

    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_8192);
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);

    char buf[] = {0x01, 0x80, 0x00};
    char readBuf[3];
    bcm2835_spi_transfernb(buf, readBuf, 3);
    int data = ((int)readBuf[1] & 0x03) << 8 | (int)readBuf[2];
    float volts = (float)data * 3.3f / 1023.0f;

    printf("%f \n \r", volts);
    bcm2835_spi6_end();
    bcm2835_close();
    return (EXIT_SUCCESS);
}
 

Page 370

 
#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
int main(int argc, char **argv)
{
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}

Page  375

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <linux/sched.h>
#include <pthread.h>
#include <stdint.h>

struct sched_attr
{
    uint32_t size;
    uint32_t sched_policy;
    uint64_t sched_flags;
    int32_t sched_nice;
    uint32_t sched_priority;
    uint64_t sched_runtime;
    uint64_t sched_deadline;
    uint64_t sched_period;
};

int sched_setattr(pid_t pid, const struct sched_attr *attr,
                  unsigned int flags)
{
    return syscall(__NR_sched_setattr, pid, attr, flags);
}

void *threadA(void *p)
{
    struct sched_attr attr = {
        .size = sizeof(attr),
        .sched_policy = SCHED_DEADLINE,
        .sched_runtime = 10 * 1000 * 1000,
        .sched_period = 2 * 1000 * 1000 * 1000,
        .sched_deadline = 11 * 1000 * 1000};
    sched_setattr(0, &attr, 0);
    for (;;)
    {
        printf("sensor\n");
        fflush(0);
        sched_yield();
    };
}

int main(int argc, char **argv)
{
    pthread_t pthreadA;
    pthread_create(&pthreadA, NULL, threadA, NULL);
    pthread_exit(0);
    return (EXIT_SUCCESS);
}
 

Page 379

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>
#include <sched.h>
#include <unistd.h>

volatile int j;
volatile int i;

void *threadA(void *p)
{
    for (i = 0;; i++)
    {
    };
}

void *threadB(void *p)
{
    for (j = 0;; j++)
    {
    };
}

int main(int argc, char **argv)
{
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(1, &cpuset);

    pthread_t pthreadA;
    pthread_create(&pthreadA, NULL, threadA, NULL);
    pthread_setaffinity_np(pthreadA, sizeof(cpu_set_t), &cpuset);

    CPU_ZERO(&cpuset);
    CPU_SET(2, &cpuset);
    pthread_t pthreadB;
    pthread_create(&pthreadB, NULL, threadB, NULL);
    pthread_setaffinity_np(pthreadB, sizeof(cpu_set_t), &cpuset);

    sleep(5);

    printf("%d %d", i, j);
    return (EXIT_SUCCESS);
}
 

 Page 382

 
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>
#include <bcm2835.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(3, &cpuset);
    int res = sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpuset);

    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}
 

Page 386

#include <stdio.h>
#include <string.h>
 int main(int argc, char** argv) {
    int gpio = 4;
    FILE* fd = fopen("/sys/class/gpio/export", "w");
    fprintf(fd, "%d", gpio);
    fclose(fd);
    return 0;
}
 

Page 387


#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    int gpio = 4;
    char buf[100];

    FILE *fd = fopen("/sys/class/gpio/export", "w");
    fprintf(fd, "%d", gpio);
    fclose(fd);

    sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio);
    fd = fopen(buf, "w");
    fprintf(fd, "out");
    fclose(fd);

    sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
    fd = fopen(buf, "w");

    for (;;)
    {
        fd = fopen(buf, "w");
        fprintf(fd, "1");
        fclose(fd);
        fd = fopen(buf, "w");
        fprintf(fd, "0");
        fclose(fd);
    }
    return 0;
}
 

Appendix II

All files have to be stored in the .vscode folder

settings,json

 
{
    "sshUser": "root",
    "sshEndpoint": "192.168.11.151",
    "remoteDirectory": "/home/pi/Documents/${workspaceFolderBasename}",
    "std": "c99",
    "libs":"-lbcm2835",
    "header":"/usr/local/include/bcm2835.h"
}
 

launch.json

 
{
    "configurations": [
     
        {
            "name": "Remote C Debug",
            "type": "cppdbg",
            "request": "launch",
            "program": "${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${config:remoteDirectory}/${relativeFileDirname}",
            "environment": [],
            "externalConsole": false,
            "pipeTransport": {
                "debuggerPath": "/usr/bin/gdb",
                "pipeProgram": "C:/Windows/System32/OpenSSH/ssh",
                "pipeArgs": [
                    "${config:sshUser}@${config:sshEndpoint}"
                ],
                "pipeCwd": "${workspaceFolder}"
            },
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "sourceFileMap": {
                "${config:remoteDirectory}/${relativeFileDirname}": "${fileDirname}"
            },
            "preLaunchTask": "CopyBuildRemote",
        }
    ]
}
 

c_cpp_properties.json

 
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/MinGW/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard":"c99",
            "intelliSenseMode":"gcc-arm" 
                }
    ],
    "version": 4
}
 
 

tasks.json

 
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "copyToRemote",
            "type": "shell",
            "command": "scp -r ${fileDirname} ${config:sshUser}@${config:sshEndpoint}:${config:remoteDirectory}/",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": false,
                "clear": true
            }
        },
        {
            "label": "copyHeader",
            "type": "shell",
            "command": "mkdir ${workspaceFolder}/headers/ ;scp -r  ${config:sshUser}@${config:sshEndpoint}:${config:header} ${workspaceFolder}/headers/ ",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": false,
                "clear": true
            }
        },
        {
            "label": "buildRemote",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} 'gcc  -g -std=${config:std} ${config:remoteDirectory}/${relativeFileDirname}/${fileBasename} ${config:libs}  -o${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}.exe'",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": false,
                "clear": false
            }
        },
        {
            "label": "runRemote",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} '${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}.exe'",
            "problemMatcher": [
                "$gcc"
            ],
            "presentation": {
                "showReuseMessage": true,
                "clear": false
            }
        },
        {
            "label": "CopyBuildRunRemote",
            "dependsOrder": "sequence",
            "dependsOn": [
                "copyToRemote",
                "buildRemote",
                "runRemote"
            ],
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "label": "CopyBuildRemote",
            "dependsOrder": "sequence",
            "dependsOn": [
                "copyToRemote",
                "buildRemote",
            ],
            "problemMatcher": [],
        },
        {
            "label": "StopREmoteC",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} ;'pkill ${fileBasenameNoExtension}.exe'",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": true,
            }
        },
        {
            "label": "copyARMheaders",
            "type": "shell",
            "command": "mkdir ${workspaceFolder}/include/;scp -r  ${config:sshUser}@${config:sshEndpoint}:/usr/include ${workspaceFolder}/include/ ",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": true,
                "clear": true
            }
        },
    ],
}
"presentation": {
"showReuseMessage": true,
}
},
{
"label": "copyARMheaders",
"type": "shell",
"command": "mkdir ${workspaceFolder}/include/;scp -r  ${config:sshUser}@${config:sshEndpoint}:/usr/include ${workspaceFolder}/include/ ",
"problemMatcher": [],
"presentation": {
"showReuseMessage": true,
"clear": true
}
},
],
}
 
 
 
 

Programming the ESP32 in MicroPython

 esppython360

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into Thonny or Pycharm project. 

The only downside is that you have to create a project to paste the code into.

To do this follow the instructions in the book.

All of the programs below were copy and pasted from working programs in the IDE. They have been formatted using the built in formatter and hence are not identical in layout to the programs in the book. This is to make copy and pasting them easier. The programs in the book are formatted to be easy to read on the page.

If anything you consider important is missing or if you have any requests or comments  contact:

This email address is being protected from spambots. You need JavaScript enabled to view it. 

 


Page 44

from machine import Pin
import time

pin = Pin(2, Pin.OUT)
while True:
    pin.value(1)
    time.sleep(1)
    pin.value(0)
    time.sleep(1)

Page 46

from machine import Pin
import time
def toggle(pin):
    temp = pin.value()
    temp = not temp
    pin.value(temp)

pin = Pin(2,Pin.OUT)
while True:
    toggle(pin)
    time.sleep(1)

 

Page 50

from machine import  Pin
pin = Pin(6, Pin.OUT)
while True:
    pin.value(1)
    pin.value(0)
 

Page 51

from machine import  Pin
def flash():
    pin = Pin(2, Pin.OUT)
    while True:
        pin.value(1)
        pin.value(0)
flash()

Page 51

from machine import Pin

@micropython.native
def flash():
    pin = Pin(2, Pin.OUT)
    while True:
        pin.value(1)
        pin.value(0)
flash()

Page 52

from machine import Pin
import time
pin = Pin(2, Pin.OUT)
while True:
    pin.value(1)
    time.sleep(0.5)
    pin.value(0)
    time.sleep(0.5)
 

Page 53

from machine import Pin
import time
pin = Pin(2, Pin.OUT)
while True:
    pin.value(1)
    time.sleep_us(10)
    pin.value(0)
    time.sleep_us(10)

Page 53

from machine import Pin
import time
pin = Pin(2, Pin.OUT)
n = 10
while True:
    for i in range(n):
        pass
    pin.value(1)
    for i in range(n):
        pass
    pin.value(0)

Page 54

from machine import Pin
import time
pin = Pin(2, Pin.OUT)
n = 5
while True:
    t = time.ticks_add(time.ticks_us(), 1000)
    pin.value(1)
    for i in range(n):
        pass

    while time.ticks_us() < t:
        pass
    pin.value(0)

Page 56

import time
from time import sleep
import esp32
from machine import Pin
import machine
pin = Pin(2,Pin.OUT,value=0)
buf = bytearray(b"\x55\x55")
print(buf)
machine.bitstream(pin,0,(80,90,100,110),buf)
 

Page 58

import esp32
from machine import Pin
import machine
pin=Pin(2,Pin.OUT,value=0)
rmt=esp32.RMT(0,pin=pin)
rmt.write_pulses((1000,400,200,300,200,300),1)

Page 59

from machine import Pin

pin1 = Pin(2, Pin.OUT)
pin2 = Pin(4, Pin.OUT)
while True:
    pin1.value(1)
    pin2.value(0)
    pin1.value(0)
    pin2.value(1)

Page 61  

from machine import Pin
import machine

def gpio_set(value, mask):
    machine.mem32[0x3FF44004] = machine.mem32[0x3FF44004] & ~mask | value & mask

pin = Pin(2, Pin.OUT)
pin = Pin(4, Pin.OUT)
value1 = 1 << 2 | 0 << 4
value2 = 0 << 2 | 1 << 4
mask = 1 << 2 | 1 << 4
while True:
    gpio_set(value1, mask)
    gpio_set(value2, mask)

Page 83

from machine import Pin
import time
pinIn = Pin(4, Pin.IN,Pin.PULL_UP)
pinLED = Pin(2, Pin.OUT)

while True:
    if pinIn.value():
        pinLED.on()
    else:
        pinLED.off()
    time.sleep(0.5)

Page 84

from machine import Pin
import time

pinIn = Pin(4, Pin.IN,Pin.PULL_DOWN)
pinLED = Pin(2, Pin.OUT)

while True:
    while pinIn.value()==0:
        pass
    while pinIn.value()==1:
        pass
    pinLED.on()
    time.sleep_ms(1)
    pinLED.off()

Page 85

from machine import Pin
import time
pinIn = Pin(4, Pin.IN,Pin.PULL_DOWN)
pinLED = Pin(2, Pin.OUT)

while True:
    while pinIn.value() == 0:
        pass
    t = time.ticks_ms()
    time.sleep_ms(1)
    while pinIn.value() == 1:
        pass
    t = time.ticks_diff(time.ticks_ms(),t)
    if t<2000:
        pinLED.on()
        time.sleep(1)
        pinLED.off()
    else:
        for i in range(10):
            pinLED.on()
            time.sleep_ms(100)
            pinLED.off()
            time.sleep_ms(100)

Page 86

from machine import Pin
import time
pinIn = Pin(4, Pin.IN)

while True:
    while pinIn.value()==1:
        pass
    while pinIn.value()==0:
        pass

    t=time.ticks_us()
    while pinIn.value()==1:
        pass
    t=time.ticks_diff(time.ticks_us(),t)
    print(t)
    time.sleep(1)

Page 87

import time
import machine

pinIn = machine.Pin(4, machine.Pin.IN)

while True:
    t = machine.time_pulse_us(pinIn, 1)
    print(t)
    time.sleep(1)

Page 87

import time
import machine

pinIn = machine.Pin(4, machine.Pin.IN)

while True:
    while pinIn.value() == 1:
        pass
    t = machine.time_pulse_us(pinIn, 1)
    print(t)
    time.sleep(1)

Page 90

from machine import Pin
import time

pinIn = Pin(4, Pin.IN)

s = 0
count = 0
while True:
    I = pinIn.value()
    t = time.ticks_add(time.ticks_us(),1000*100)
    if s == 0:   #button not pushed
        if i:
            s = 1
            count=count+1
            print("Button Push ",count)
    elif s == 1: #button pushed
        if not i:
            s = 0
    else:
        s = 0
    while time.ticks_us()<t:
        pass

Page 92

from machine import Pin
import time
pinIn = Pin(4, Pin.IN)

s = 0
while True:
    I = pinIn.value()
    t = time.ticks_add(time.ticks_us(),1000*100)
    if s == 0:       #button not pushed
        if i:
            s = 1
        tpush = t
    elif s == 1:     #button pushed
        if not i:
            s = 0
            if time.ticks_diff(t, tpush) > 2000000:
                print("Button held \n\r")                
            else:
                print("Button pushed \n\r")
    else:
        s = 0
    while time.ticks_us()<t:
        pass

Page 93

from machine import Pin
import time
pinIn = Pin(4, Pin.IN)
pinLED1 = Pin(2, Pin.OUT)
pinLED2 = Pin(16, Pin.OUT)
pinLED3 = Pin(17, Pin.OUT)
pinLED1.on()
pinLED2.off()
pinLED3.off()
s = 0
buttonState = pinIn.value()
while True:
    buttonNow = pinIn.value()
    edge = buttonState-buttonNow
    buttonState = buttonNow
    t = time.ticks_add(time.ticks_us(), 1000*100)
    if s == 0:
        if edge == 1:
            s = 1
            pinLED1.off()
            pinLED2.on()
            pinLED3.off()

    elif s == 1:
        if edge == 1:
            s = 2
            pinLED1.off()
            pinLED2.off()
            pinLED3.on()
    elif s == 2:
        if edge == 1:
            s = 0
            pinLED1.on()
            pinLED2.off()
            pinLED3.off()
    else:
        s = 0
    while time.ticks_us() < t:
        pass

Page 100
 
def HelloIRQ1(pin):
    print("IRQ1")
   
def HelloIRQ2(pin):
    print("IRQ2")

pin1=Pin(4,Pin.IN,Pin.PULL_DOWN)
pin2=Pin(5,Pin.IN,Pin.PULL_DOWN)

pin1.irq(HelloIRQ1,Pin.IRQ_RISING)
pin2.irq(HelloIRQ2,Pin.IRQ_RISING)

Page 101

import time
from machine import Pin
t = 0
def myHandler(pin):
    global t
    temp = time.ticks_us()
    print(time.ticks_diff(temp,t))
    t = temp
    time.sleep(1.5)  
    return

pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_FALLING)

Page 101

import time
from machine import Pin
t = 0
def myHandler(pin):
    global t
    pin.irq(None, Pin.IRQ_FALLING)
    temp = time.ticks_us()
    print(time.ticks_diff(temp,t))
    t = temp
    time.sleep(1.5)
    pin.irq(myHandler, Pin.IRQ_FALLING)
    return
pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_FALLING)

Page 104

import time
from machine import Pin

data = bytearray(b'\xf0\xf1\xf2')

def myHandler(pin):
    global data
    for i in range(3):
        data[i]=0

pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_RISING)

while True:
    for i in range(3):
        data[i] = 255
    if data[0]!=data[1] or data[1]!=data[2] or data[2]!=data[0]:
        print(data)

Page 105

from machine import Pin

data=bytearray(b'\xf0\xf1\xf2')
def myHandler(pin):
    global data
    for i in range(3):
        data[i] = 0
    print(data)

pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_RISING)
while True:
    pin.irq(None, Pin.IRQ_RISING)
    for i in range(3):
        data[i] = 255

    if data[0]!=data[1] or data[1]!=data[2] or data[2]!=data[0]:
        print(data)
    pin.irq(myHandler, Pin.IRQ_RISING)

Page 106

import time

from time import sleep 

from machine import Pin
pin=Pin(4,Pin.IN,Pin.PULL_DOWN)
event=0
def rise(pin):
    global event
    event=1

def fall(pin):
    global event
    event=2

while True:
    pin.irq(rise, Pin.IRQ_RISING)
    while  not(event==1):
        pass
    t=time.ticks_us()
    pin.irq(fall, Pin.IRQ_FALLING)
    while  not(event==2):
        pass
    t=time.ticks_diff(time.ticks_us(),t)
    print(t)
    sleep(1)
 

Page 114
import esp32
from machine import Pin
import machine
pin=Pin(4,Pin.OUT,value=0)
rmt=esp32.RMT(0,pin=pin)
t=20000000 # pulse repetition in us
d=[10,20,30,40,50] #duty cycles in percent

times=[]
for p in d:
    times.append(int(t*p/100))
    times.append(int((t*(100-p)/100)))

rmt.loop(True)
rmt.write_pulses(times,1)

Page 117

from machine import Pin, PWM
import array
import math

wave = array.array('H', [0]*256)
for i in range(256):
    wave[i] = int(65535//2 +  (math.sin(i * 2.0 * 3.14159 / 256.0) * 65535//2))

pwm1 = PWM(Pin(4),freq=300000)
print(pwm1)
while(True):
    for i in range(256):
        pwm1.duty_u16(wave[i])

print(pwm_get_wrap(0))
while(True):
    for i in range(256):
        pwm16.duty_u16(wave[i])

Page 119

from machine import Pin, PWM
from time import sleep_ms
pwm1 = PWM(Pin(4),freq=2000)

while True:
    for d in range(0,65535,655):
        pwm1.duty_u16(d)
        sleep_ms(50)

Page 120

from utime import sleep_ms
from machine import Pin, PWM

pwm1 = PWM(Pin(4),freq=2000)

while True:
    for b in range(0,100):
        pwm1.duty_u16(int(65535*b*b*b/1000000))
        sleep_ms(50)

Page 131

from machine import Pin, PWM
from time import sleep
class Motor:
    def __init__(self, pinNo):
        self.pwm1 = PWM(Pin(pinNo), freq=2000, duty_u16=0)
        self.gpio = pinNo
        self._on = False
        self.speed=0
    def setSpeed(self,s):
        self._on=True
        self.speed=s
        self.pwm1.duty_u16(int(65535*s/100))
    def off(self):
        self._on=False
        self.pwm1.duty_u16(0)
    def on(self):
        self._on=True
        self.pwm1.duty_u16(int(65535*self.speed/100))

motor=Motor(4)
sleep(1)
motor.setSpeed(50)
sleep(1)
motor.off()
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.off()

Page 136

from machine import Pin, PWM
from time import sleep
class Motor:
    def __init__(self, pinNo):
        self.pwm1 = PWM(Pin(pinNo), freq=2000, duty_u16=0)
        self.gpio = pinNo
        self._on = False
        self.speed=0
    def setSpeed(self,s):
        self._on=True
        self.speed=s
        self.pwm1.duty_u16(int(65535*s/100))
    def off(self):
        self._on=False
        self.pwm1.duty_u16(0)
    def on(self):
        self._on=True
        self.pwm1.duty_u16(int(65535*self.speed/100))

class BiMotor(Motor):
    def __init__(self, pinNo1,pinNo2):
        super().__init__(pinNo1)
        self.forward = True
        self.pwm2 = PWM(Pin(pinNo2),freq=2000,duty_u16=0)

    def setForward(self, forward):
        if self.forward == forward:
            return
        self.pwm1.duty_u16(0)
        self.pwm1, self.pwm2 = self.pwm2, self.pwm1
        self.forward = forward
        self.pwm1.duty_u16(int(65535 * self.speed / 100))


motor = BiMotor(16,17)
sleep(1)
motor.setSpeed(50)
sleep(1)
motor.setForward(False)
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.setForward(True)
motor.off()

Page 139

from machine import Pin, PWM
from time import sleep
class Servo:
    def __init__(self, pinNo):
        self.pwm = PWM(Pin(pinNo),freq=50,duty_u16= int(65535*2.5/100))
    def setPosition(self, p):
        self.position = p
        self.pwm.duty_u16(int(65535*p/1000 + 65535*2.5/100))
    def off(self):
        self.pwm.deinit()
servo=Servo(4)
sleep(1)
servo.setPosition(100.0)
sleep(1)
servo.setPosition(50.0)
sleep(1)
servo.setPosition(0)
sleep(1)
servo.off()

Page 146

from machine import Pin, mem32
from time import sleep_ms
class StepperBi4():
    def __init__(self, pinA):
        self.phase = 0
        self.pinA = pinA
        self.gpios = tuple([Pin(pinA, Pin.OUT),
                            Pin(pinA + 1, Pin.OUT),
                            Pin(pinA + 2, Pin.OUT),
                            Pin(pinA + 3, Pin.OUT)])
        self.gpios[0].on()
        self.gpioMask = 0xF << self.pinA
        self.halfstepSeq = [0x1, 0x3, 0x2, 0x6, 0x4, 0xC, 0x8, 0x9]

    #   [
    #             [0,0,0,1],
    #             [0,0,1,1],
    #             [0,0,1,0],
    #             [0,1,1,0],
    #             [0,1,0,0],
    #             [1,1,0,0],
    #             [1,0,0,0],
    #             [1,0,0,1]
    #    ]

    def _gpio_set(self,value, mask):
        mem32[0x3FF44004] = mem32[0x3FF44004] & ~mask | value & mask

    def setPhase(self, phase):
        value = self.halfstepSeq[phase] << self.pinA
        self._gpio_set(value, self.gpioMask)
        self.phase = phase

    def stepForward(self):
        self.phase = (self.phase + 1) % 8
        self.setPhase(self.phase)

    def stepReverse(self):
        self.phase = (self.phase - 1) % 8
        self.setPhase(self.phase)

step = StepperBi4(16)
step.setPhase(0)

while True:
    step.stepForward()
    sleep_ms(1)

Page 151

from machine import Pin, mem32, Timer
from time import sleep_ms
class StepperBi4():
    def __init__(self, pinA):
        self.phase = 0
        self.pinA = pinA
        self.gpios = tuple([Pin(pinA, Pin.OUT),
                            Pin(pinA + 1, Pin.OUT),
                            Pin(pinA + 2, Pin.OUT),
                            Pin(pinA + 3, Pin.OUT)])
        self.gpios[0].on()
        self.gpioMask = 0xF << self.pinA
        self.halfstepSeq = [0x1, 0x3, 0x2, 0x6, 0x4, 0xC, 0x8, 0x9]
        self.timer = None
        self.forward = True
    #   [
    #             [0,0,0,1],
    #             [0,0,1,1],
    #             [0,0,1,0],
    #             [0,1,1,0],
    #             [0,1,0,0],
    #             [1,1,0,0],
    #             [1,0,0,0],
    #             [1,0,0,1]
    #    ]

    def _gpio_set(self,value, mask):
        mem32[0x3FF44004] = mem32[0x3FF44004] & ~mask | value & mask

    def setPhase(self, phase):
        value = self.halfstepSeq[phase] << self.pinA
        self._gpio_set(value, self.gpioMask)
        self.phase = phase


    def stepForward(self):
        self.phase = (self.phase + 1) % 8
        self.setPhase(self.phase)


    def stepReverse(self):
        self.phase = (self.phase - 1) % 8
        self.setPhase(self.phase)

    def doRotate(self, timer):
        if self.forward:
            self.stepForward()
        else:
            self.stepReverse()

    def rotate(self, forward, speed):
        self.forward = forward
        self.speed = speed
        if speed == 0:
            self.timer.deinit()
            self.timer = None
            return
        if self.timer == None:
            self.timer = Timer(0)
        self.timer.init(freq = speed, mode = Timer.PERIODIC, callback = self.doRotate)


step=StepperBi4(16)
step.setPhase(0)
while True:
    step.rotate(True,100)
    sleep_ms(500)
    step.rotate(True,0)
    sleep_ms(500)
 

Page 160

from machine import Pin, SPI
spi=SPI(1,sck=Pin(14),miso=Pin(12),mosi=Pin(13))
spi.init(baudrate=500_000,bits=8, polarity=0,phase=0,firstbit=SPI.MSB )
read = bytearray(3)
write = bytearray([0xAA,0xAA,0xAA])
spi.write_readinto(write,read)
print(read,write)
spi.deinit()

Page 168

from utime import sleep_ms
from machine import Pin, SPI

spi=SPI(1,sck=Pin(14),miso=Pin(12),mosi=Pin(13))
spi.init(baudrate=500_000, bits=8, polarity=0, phase=0,firstbit=SPI.MSB)
CS = Pin(15, Pin.OUT)
CS.on()
sleep_ms(1)
CS.off()
write=bytearray([0x01, 0x80, 0x00])
read=bytearray(3)
spi.write_readinto(write,read)
CS.on()
data =  (read[1] & 0x03) << 8 |  read[2]
volts =  data * 3.3 / 1023.0
print(volts)
spi.deinit()

Page 169

from utime import sleep_ms
from machine import Pin, SPI
class spiADC:
    def __init__(self,spi,sckNo,misoNo,mosiNo,CSNo):
        self.spi = SPI(spi, sck=Pin(sckNo), miso=Pin(misoNo), mosi=Pin(mosiNo))
        self.spi.init(baudrate=500_000, bits=8, polarity=0,phase=0, firstbit=SPI.MSB)
        self.CS = Pin(CSNo, Pin.OUT)
        self.CS.on()
        sleep_ms(1)

    def read(self,chan):
        write=bytearray([0x01, (0x08 | chan) << 4 , 0x00])
        self.CS.off()
        read=bytearray(3)
        self.spi.write_readinto(write,read)
        self.CS.on()
        data =  (read[1] & 0x03) << 8 |  read[2]
        volts =  data * 3.3 / 1023.0
        return volts

adc=spiADC(1,14,12,13,15)
volts=adc.read(1)
print(volts)

 


Page 173

from machine import mem32
def getVCal():
    VC=(mem32[0x3FF5_A010]>>8)& 0x1F
    if(VC & 0x10 ):
        VC=-(VC & 0x0F)
    return 1100+VC*7

print(getVCal())

Page 177

from machine import ADC,Pin
import time
adc = ADC(Pin(32),atten=ADC.ATTN_11DB)

t = time.ticks_us()
for i in range(10000):
    pass
print(time.ticks_diff(time.ticks_us(), t)/10000)

t = time.ticks_us()
for i in range(10000):
    m=adc.read()
print(time.ticks_diff(time.ticks_us(), t)/10000)

t = time.ticks_us()
for i in range(10000):
    m=adc.read_u16()
print(time.ticks_diff(time.ticks_us(), t)/10000)

t = time.ticks_us()
for i in range(10000):
    m=adc.read_uv()
print(time.ticks_diff(time.ticks_us(), t)/10000)

Page 178

import esp32
import time
while(True):
    m = esp32.hall_sensor()+esp32.hall_sensor()+esp32.hall_sensor()+esp32.hall_sensor()
    m = m/4
    print(m)
    time.sleep(0.5)

Page 181

from machine import Pin, DAC
import math
dac1 = DAC(Pin(26))
wave = []
for i in range(0,255):
    wave.append(int(127*math.sin(2*math.pi/256*i))+128)
while(True):
     for i in range(0,255):
         dac1.write(wave[i])

Page 181

from machine import Pin, DAC, mem32
from time import sleep

def _gpio_get(adr):
    return mem32[adr]

def _gpio_set( adr,value, mask):
    mem32[adr] = mem32[adr] & ~mask | value & mask


def enableSin(chan,f):
    if chan<1 or chan>2:
        return
    setFreq(chan, f)
    setPhase(chan,0x2)
    #enable tone
    _gpio_set(0x3FF48898, 0x10000, 0x10000)
    #select channel
    if chan==1:
        _gpio_set(0x3FF4889c, 1<<24,0x1<<24)
    else:
        _gpio_set(0x3FF4889c, 1<<25, 0x1 <<25)
    #set pad
    pad=0x3FF48484+4*(chan-1)
    _gpio_set(pad, 0x20200, 0x23A00)

def setFreq(chan,f):
    if chan<1 or chan>2:
        return
    step=int(f*65536/8000000) & 0xFFFF
    _gpio_set(0x3FF48898, step, 0x000FF)
def setPhase(chan,p):
    _gpio_set(0x3FF4889c, p << (20 + 2 * (chan – 1)),0x03 << (20 + 2 * (chan - 1)))

def setScale(chan,s):
    _gpio_set(0x3FF4889c, s << (16 + 2 * (chan – 1)),0x03 << (16 + 2 * (chan - 1)))

def setOff(chan,off):
    _gpio_set(0x3FF4889c, off << (8 * (chan – 1)), 0xFF << (8 * (chan - 1)))

dac1 = DAC(Pin(26))

enableSin(2,30000)
setScale(2,0x0)
setOff(2,0x0)
while(True):
    sleep(0.001)
    setPhase(2,0x3)
    sleep(.001)
    setPhase(2, 0x2)

 

Page 197

from machine import Pin,I2C

i2c0 = I2C(0,scl=Pin(18),sda=Pin(19),freq=100000)

buf = bytearray([0xE7])
i2c0.writeto( 0x40, buf, True)
read= i2c0.readfrom(0x40, 1, True)
print("User Register =",read)

Page 199

from machine import Pin,I2C
i2c0 = I2C(0,scl=Pin(18),sda=Pin(19),freq=100000)
buf = bytearray([0xE3])
i2c0.writeto( 0x40, buf, True)
read = i2c0.readfrom(0x40, 3, True)
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)

Page 200

from machine import Pin,SoftI2C
i2c0 = SoftI2C(scl=Pin(18),sda=Pin(19),freq=100000)
buf = bytearray([0xE3])
i2c0.writeto( 0x40, buf, False)
read= i2c0.readfrom(0x40, 3, True)
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)

Page 201

from machine import Pin,I2C

i2c0=I2C(0,scl=Pin(18),sda=Pin(19),freq=100000)

buf = bytearray([0xF3])
i2c0.writeto( 0x40, buf, True)

while True:
    try:
        read= i2c0.readfrom(0x40, 3, False)
        break
    except:
        continue

msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)

Page 202

from machine import Pin,SoftI2C
from time import sleep_ms

i2c0 = SoftI2C(scl=Pin(18),sda=Pin(19),freq=100000)

buf = bytearray([0xF3])
i2c0.writeto( 0x40, buf, False)

while True:
    sleep_ms(5)
    try:
        read = i2c0.readfrom(0x40, 3, True)
        break
    except:
        continue

msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)

Page 206

from machine import Pin,I2C

def crcCheck(msb, lsb,check):
    data32 = (msb << 16)|(lsb <<8)| check
    divisor = 0x988000
    for i in range(16):
        if data32 & 1<<(23 - i):
             data32 ^= divisor
        divisor>>= 1
    return data32

i2c0=I2C(0,scl=Pin(18),sda=Pin(19),freq=100000)
buf = bytearray([0xF3])
i2c0.writeto( 0x40, buf, False)
while True:
    try:
        read= i2c0.readfrom(0x40, 3, True)
        break
    except:
        continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
data16= (msb << 8) |  (lsb & 0xFC)
temp = (-46.85 +(175.72 * data16 /(1<<16)))
print("Temperature C ", temp)
print("Checksum=",crcCheck(msb,lsb,check))

buf = bytearray([0xF5])
i2c0.writeto( 0x40, buf, True)
read=bytearray(3)
while True:
    try:
        i2c0.readfrom_into(0x40,read, True)
        break
    except:
        continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
data16 = (msb << 8) | (lsb & 0xFC)
hum = -6 + (125.0 * data16) / 65536
print("Humidity ", hum)
print("Checksum=",crcCheck(msb,lsb,check))

 

Page 212

import dht
from machine import Pin
from time import sleep

dht = dht.DHT22(Pin(23))
while True:
    dht.measure()
    temp = dht.temperature()
    print(temp,"C")
    hum = dht.humidity()
    print(hum,"%")
    sleep(1)

Page 213

from machine import Pin
from utime import sleep_ms
DHT = Pin(23,mode=Pin.OUT,value=1)
sleep_ms(1)
DHT.off()
sleep_ms(1)
DHT.init(mode=Pin.IN)

Page 217

from machine import Pin,time_pulse_us
from utime import sleep_ms

class DHT22():
    def __init__(self,gpio):
        self.pin = Pin(gpio, mode=Pin.IN)
        self.checksum = 0
        self.temperature = 0
        self.humidity=0
        sleep_ms(1)
       
    @micropython.native
    def getReading(self):
        data = 0
        checksum = 0
        DHT=self.pin  
        DHT.init(mode=Pin.OUT,value=0)
        sleep_ms(1)
        DHT.init(mode=Pin.IN)
        t = time_pulse_us(DHT, 0, 1000)
        t = time_pulse_us(DHT, 1, 1000)        
             
        for i in range(32):
            t = time_pulse_us(DHT, 1, 1000)
            data = data << 1
            data = data | (t > 50)          
       
        for i in range(8):
            t = time_pulse_us(DHT, 1, 1000)
            checksum = checksum << 1
            checksum = checksum |(t > 50)
 
        byte1 = (data >> 24 & 0xFF)
        byte2 = (data >> 16 & 0xFF)
        byte3 = (data >> 8 & 0xFF)
        byte4 = (data & 0xFF)
        self.checksum =(checksum ==(byte1+byte2+byte3+byte4)&0xFF)
        self.humidity = ((byte1 <<8)| byte2) / 10.0
        neg = byte3 & 0x80
        byte3 = byte3 & 0x7F
        self.temperature = (byte3 << 8 | byte4) / 10.0
        if neg > 0:
            self.temperature = -self.temperature

dht = DHT22(23)
dht.getReading()
print("Checksum",dht.checksum)
print("Humidity= ", dht.humidity)
print("Temperature=", dht.temperature)

Page 223

from machine import Pin
import onewire,ds18x20

ow = onewire.OneWire(Pin(23))
presence=ow.reset()
if presence:
    print("Device present")
else:
    print("No device")
   
ds = ds18x20.DS18X20(ow)    
roms = ds.scan()
t = ds.read_temp(roms[0])
print(t)

Page 230

from machine import Pin
import onewire

class DS18B20:
    def __init__(self,pin):
        self.ow = onewire.OneWire(Pin(pin))    
       
    def __convert(self):
        self.ow.write([0xCC,0x44])
        for i in range(500):
            sleep_ms(10)
            if self.ow.readbit() == 1:
                j = i
                break
        return j
   
    def getTemp(self):
        if not self.ow.reset:
            return -1000
        if self.__convert()==500:
            return -3000
        self.ow.reset()
        self.ow.write([0xCC,0xBE])
        data = bytearray(9)
        self.ow.readinto(data)
        if self.ow.crc8(data)!=0:
            return -2000
        t1 = data[0]
        t2 = data[1]
        temp1 = (t2 << 8 | t1)
        if t2 & 0x80:
            temp1=temp1 | 0xFFFF0000
        return temp1/16

dS18B20=DS18B20(23)
print(dS18B20.getTemp())

 

Page 239

from machine import UART,Pin
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=23,tx=22)
SendData = bytearray("Hello World \n","utf-8")
uart.write(SendData)
RecData = uart.read()
print(RecData)

Page 242

from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=23,tx=22,txbuf=256,rxbuf=16*1024)
test="A"*252
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)

Page 242

from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None, rx=23,tx=22, txbuf=16*1024,rxbuf=512)
test="A"*1000
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
sleep_ms(4000)
RecData = uart.read()
print(RecData)

Page 243

from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=23,tx=22, txbuf=4*1024,rxbuf=512)
test = ""
for i in range(280):
   test=test + str(i)+","
print(test)
print(len(test))
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
sleep_ms(4000)
RecData = uart.read()
print(RecData)
print(len(RecData))

Page 247

from machine import UART,Pin
from utime import sleep_ms, time_ns

uart = UART(1,baudrate=9600,bits=8,parity=None, rx=23,tx=22,rts=21,cts=19, timeout=0,timeout_char=0,txbuf=2000,rxbuf=256,flow=UART.RTS|UART.CTS)

test = "A"*1000
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)

RecData = bytes()
while len(RecData)<1000:
    sleep_ms(500)
    if uart.any():
            RecData = RecData + uart.read()
            print(RecData)
            print(len(RecData))

 


Page 257

import network
from machine import Pin, Timer
from time import sleep_ms
def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

Page 261

from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def sendResponse(self, cmd):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(b'This is a '+bytes(cmd, 'utf-8')+ b' request. ')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, world!')


    def do_HEAD(self):
        self.send_response(200)
        self.end_headers()

   
    def do_POST(self):
        self.sendResponse("POST")

    def do_PUT(self):
        self.sendResponse("PUT")

    def do_DELETE(self):
        self.sendResponse("DELETE")

    def do_PATCH(self):
        self.sendResponse("PATCH")


httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()

Page 264

import network
from machine import Pin, Timer
from time import sleep_ms
import urequests

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi
   
wifi=setup(country, ssid, key)
print("Connected")
r = urequests.get("https://www.example.com")
print(r.content)
r.close()

Page 265

   
import network
from machine import Pin, Timer
from time import sleep_ms
import urequests

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi


wifi=setup(country, ssid, key)
print("Connected")

url="http://192.168.253.72:8080"
r = urequests.get(url)
print(r.content)
r.close()

buf= b'Hello World'
r=urequests.post(url,data=buf)
print(r.content)
r.close()

r=urequests.put(url,data=buf)
print(r.content)
r.close()

r=urequests.patch(url,data=buf)
print(r.content)
r.close()

r=urequests.head(url)
print(r.content)
print(r.headers)
r.close()

r=urequests.delete(url,data=buf)
print(r.content)
r.close()

Page 266

import network
from machine import Pin, Timer
from time import sleep_ms
import urequests
import onewire
import ds18x20

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi=setup(country, ssid, key)
print("Connected")
url = "http://192.168.253.72:8080"
ow = onewire.OneWire(Pin(22))
presence = ow.reset()
if presence:
    print("Device present")
else:
    print("No device")

DS = ds18x20.DS18X20(ow)
roms = DS.scan()

while True:
    DS.convert_temp()
    temp = DS.read_temp(roms[0])
    buf = str(temp).encode("utf-8")
    try:
        r = urequests.put(url, data=buf)
        r.close()
    except:
        print("Server Not Online")
    sleep_ms(500)

Page 267

from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
     
    def log_message(self,*args, **kwargs):
        pass

    def do_PUT(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        bodyString= body.decode(encoding="utf-8")
        temp=float(bodyString)
        print(temp)
        self.send_response(200)
        self.end_headers()

httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()

 

Page 276

import network
import socket
from machine import Pin, Timer
from time import sleep_ms

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi=setup(country, ssid, key)
print("Connected")
url = "http://192.168.253.72:8080"
ai = socket.getaddrinfo("www.example.com", 80,socket.AF_INET)
addr = ai[0][-1]
s = socket.socket(socket.AF_INET)
s.connect(addr)

request = b"GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n"
s.send(request)
print(s.recv(512))

Page 277

import network
import socket
import ssl
from machine import Pin, Timer
from time import sleep_ms

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi=setup(country, ssid, key)
print("Connected")

ai = socket.getaddrinfo("example.com", 443,socket.AF_INET)
addr = ai[0][-1]
s = socket.socket(socket.AF_INET)
s.connect(addr)
sslSock=ssl.wrap_socket(s)
request = b"GET / HTTP/1.1\r\nHost:example.com\r\n\r\n"
sslSock.write(request)
print(sslSock.read(1024))

Page 281

import network
import socket
from time import sleep_ms
from machine import Pin, Timer
import onewire
import ds18x20

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi = setup("country", "ssid", "key")
ow = onewire.OneWire(Pin(22))
presence = ow.reset()
if presence:
    print("Device present")
else:
    print("No device")
DS = ds18x20.DS18X20(ow)
roms = DS.scan()
template = """<!DOCTYPE html>
<html>
<head> <title>Temperature</title> </head>
<body> <h1>Current Temperature</h1>
Hello ESP32 Server World <br/>
The Temperature is: <!--#temp--><br/>
</body>
</html>
"""
addr = socket.getaddrinfo('192.168.253.24', 8080)[0][-1]
print(addr)
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(0)
while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    print(cl.recv(512))
    DS.convert_temp()
    temp = DS.read_temp(roms[0])
    html=template.replace("<!--#temp-->",str(temp))
    headers = ("HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html; charset=UTF-8\r\n"
            "Server:ESP32\r\n"
            f"Content-Length:{len(html)}\r\n\r\n"
            )
    buf = headers.encode("utf-8")+html.encode("utf-8")    
    cl.send(buf)  
    cl.close()
s.close()

Page 283

import binascii

with open("iopress.key", 'rb') as f:
    lines = f.readlines()
lines = b"".join(lines[1:-1])
key = binascii.a2b_base64(lines)
print("key=", key)

with open("iopress.crt", 'rb') as f:
    lines = f.readlines()
lines = b"".join(lines[1:-1])
cert = binascii.a2b_base64(lines)
print()
print("cert=", cert)

Page 284

import network
import socket
from time import sleep_ms
from machine import Pin, Timer
import onewire
import ds18x20
import ssl


def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())

key=b'0\x82\x04\xbf\ . . .xabp\xd1'
 
cert=b'0\x82\x03k0\ . . .\x98\x8a'

ow = onewire.OneWire(Pin(22))
presence = ow.reset()
if presence:
 print("Device present")
else:
 print("No device")


DS = ds18x20.DS18X20(ow)
roms = DS.scan()

template = """<!DOCTYPE html>
<html>
<head> <title>Temperature</title> </head>
<body> <h1>Current Temperature</h1>
Hello ESP32 Server World <br/>
The Temperature is: <!--#temp--><br/>
</body>
</html>
"""

addr = socket.getaddrinfo('0.0.0.0', 443)[0][-1]

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)

while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    client_s =None
   
    try:
        client_s = ssl.wrap_socket(cl, server_side=True,
                                          key=key, cert=cert)

        while True:
            h = client_s.readline()
            if h == b"" or h == b"\r\n":
                    break
            print(h.decode(), end="")

        DS.convert_temp()
        temp = DS.read_temp(roms[0])
        html=template.replace("<!--#temp-->",str(temp))
        headers = ("HTTP/1.1 200 OK\r\n"
                "Content-Type: text/html; charset=UTF-8\r\n"
                "Server:ESP32\r\n"
                f"Content-Length:{len(html)}\r\n\r\n"
                )
        buf = headers.encode("utf-8")+html.encode("utf-8")

        client_s.write(buf)
        client_s.close()
    except Exception as e:
       print("exception ",e)
s.close()

 

Page 304

import uasyncio
from machine import Pin

async def blink(led, period_ms):
    while True:
        led.on()
        await uasyncio.sleep_ms(5)
        led.off()
        await uasyncio.sleep_ms(period_ms)

async def main(led1, led2):
    uasyncio.create_task(blink(led1, 700))
    uasyncio.create_task(blink(led2, 400))
    await uasyncio.sleep_ms(10_000)

uasyncio.run(main(Pin(22,Pin.OUT), Pin(23,Pin.OUT)))

Page 305

import uasyncio
from machine import Pin
from time import sleep_ms
async def blink(led, period_ms):
    while True:
        led.on()
        await uasyncio.sleep_ms(5)
        led.off()
        await uasyncio.sleep_ms(period_ms)

async def timewaste():
    while True:
        sleep_ms(10)
        await uasyncio.sleep_ms(0)


async def main(led1, led2):
    uasyncio.create_task(blink(led1, 700))
    uasyncio.create_task(blink(led2, 400))
    uasyncio.create_task(timewaste())
    await uasyncio.sleep_ms(10_000)

uasyncio.run(main(Pin(22,Pin.OUT), Pin(23,Pin.OUT)))

Page 307

import uasyncio
from time import sleep_ms
from machine import Pin, Timer
import network

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

async def main():
    reader,writer= await uasyncio.open_connection("www.example.com",80)
    request = b"GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n"
    writer.write(request)
    await writer.drain()
    print(await reader.read(512))
    reader.close()
wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())
uasyncio.run(main())

Page 310



import uasyncio
import network
from machine import Pin, Timer
from time import sleep_ms
import onewire
import ds18x20

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())

ow = onewire.OneWire(Pin(22))
presence = ow.reset()
if presence:
    print("Device present")
else:
    print("No device")

DS = ds18x20.DS18X20(ow)
roms = DS.scan()

template = """<!DOCTYPE html>
<html>
<head> <title>Temperature</title> </head>
<body> <h1>Current Temperature</h1>
Hello ESP32 Server World <br/>
The Temperature is: <!--#temp--><br/>
</body>
</html>
"""
async def serve_client(reader,writer):
    print("client")
    print(await reader.read(512))
    DS.convert_temp()
    temp = DS.read_temp(roms[0])
    html=template.replace("<!--#temp-->",str(temp))
    headers = ("HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html; charset=UTF-8\r\n"
            "Server:ESP32\r\n"
            f"Content-Length:{len(html)}\r\n\r\n"
            )
    buf = headers.encode("utf-8")+html.encode("utf-8")
    writer.write(buf)
    await writer.drain()
    writer.close()
    await writer.wait_closed()

async def main():
    await uasyncio.start_server(serve_client, '192.168.253.24', 80,backlog=5)
    while True:
        print("heartbeat")
        await uasyncio.sleep(1)

uasyncio.run(main())

 

Page 315

from machine import mem32,Pin
from time import sleep_ms

led = Pin(2,mode=Pin.OUT)
GPIOSet = 0x3FF44008
GPIOClear = 0x3FF4400C
mask = 1<<2
while True:
    mem32[GPIOSet] = mask
    sleep_ms(500)
    mem32[GPIOClear] = mask
    sleep_ms(500)

Page 315

from machine import mem32,Pin
from time import sleep_ms

@micropython.native
def blink():
    GPIOSet = 0x3FF44008
    GPIOClear = 0x3FF4400C
    mask = 1<<2
    while True:
        mem32[GPIOSet] = mask
        mem32[GPIOClear] = mask

led = Pin(2,mode=Pin.OUT)
blink()

Page 318

from machine import Pin
import machine

def gpio_setgroup(value, mask):
    machine.mem32[0x3FF44004] = machine.mem32[0x3FF44004] & ~mask | value & mask

pin = Pin(2, Pin.OUT)
pin = Pin(4, Pin.OUT)
value1 = 1 << 2 | 0 << 4
value2 = 0 << 2 | 1 << 4
mask = 1 << 2 | 1 << 4
while True:
    gpio_setgroup(value1, mask)
    gpio_setgroup(value2, mask)

Page 323

from machine import Pin, DAC, mem32
from time import sleep

def _reg_get(adr):
    return mem32[adr]

def _reg_set( adr,value, mask):
    mem32[adr] = mem32[adr] & ~mask | value & mask

def enableSin(chan,f):
    if chan<1 or chan>2:
        return
    setFreq(chan, f)
    setPhase(chan,0x2)
    #enable tone
    _reg_set(0x3FF48898, 0x10000, 0x10000)
    #select caannel
    if chan==1:
        _reg_set(0x3FF4889c, 1<<24,0x1<<24)
    else:
        _reg_set(0x3FF4889c, 1<<25, 0x1 <<25)


def setFreq(chan,f):
    if chan<1 or chan>2:
        return
    step = int(f*65536/8000000) & 0xFFFF
    _reg_set(0x3FF48898, step, 0x000FF)

def setPhase(chan,p):
    _reg_set(0x3FF4889c, p << (20 + 2 * (chan – 1)), 0x03 << (20 + 2 * (chan - 1)))


def setScale(chan,s):
    _reg_set(0x3FF4889c, s << (16 + 2 * (chan - 1)),0x03 << (16 + 2 * (chan - 1)))

def setOff(chan,off):
    _reg_set(0x3FF4889c, off << (8 * (chan - 1)),0xFF << (8 * (chan - 1)))

dac1 = DAC(Pin(26))

enableSin(2,30000)
setScale(2,0x0)
setOff(2,0x0)
while(True):
    sleep(0.001)
    setPhase(2,0x3)
    sleep(.001)
    setPhase(2, 0x2)

Page 324

import ntptime
from machine import RTC
import network
from machine import Pin, Timer
from time import sleep_ms

def setup(country, ssid, key):
    network.country(country)
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    LED = Pin(2, Pin.OUT)
    LED.on()
    timeout = 20000
    wifi.connect(ssid,key)
    timer = Timer(1)
    timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))    
    s = network.STAT_IDLE
    while timeout>0:
        print("connecting",s)
        s = wifi.status()
        if s != network.STAT_CONNECTING:
            break
        sleep_ms(100)
        timeout = timeout-100    
    if(s==network.STAT_GOT_IP):
         timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))        
    else:
        timer.deinit()
        LED.on()
    return wifi

wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())

ntptime.host="pool.ntp.org"
ntptime.timeout=1000
try:
    ntptime.settime()
except Exception:
    print("NTP server not available")
    pass
rtc = RTC()
print(rtc.datetime())

Page 326

from machine import lightsleep
from time import sleep
for i in range(10):
    print("starting sleep",i)
    lightsleep(1000)
    print ("back from sleep",i)

Page 327

from machine import deepsleep
from time import sleep
for i in range(10):
    print("starting sleep",i)
sleep(2)
print('I am going to sleep')
deepsleep(1000)

Page 327

from machine import deepsleep, RTC
from time import sleep
sleep(3)
rtc = RTC()
if len(rtc.memory())==0:
    start=0
else:
    start = int.from_bytes(rtc.memory(),"big")
for i in range(start,start+10):
    print(i)
print("starting sleep")
rtc.memory((i+1).to_bytes(4,"big"))
deepsleep(1000)

Page 329

from machine import lightsleep,Pin
import esp32

wakePin = Pin(2,Pin.IN,pull=None)
esp32.wake_on_ext0(wakePin,esp32.WAKEUP_ANY_HIGH)
for i in range(10):
    print("starting sleep",i)
    lightsleep()
    print ("back from sleep",i)

Page 331

from machine import WDT
from time import sleep
sleep(4)
print("starting")
wdt = WDT(timeout=4000)
wdt.feed()
while True:
    sleep(0.1)
    print("still running")
    pass

Page 336

from machine import deepsleep
from time import sleep
from esp32 import NVS
sleep(3)
start = 0
nvsState = NVS("state")
try:
    start = nvsState.get_i32("start")
except OSError:
    pass
for i in range(start,start+10):
    print(i)
print("starting sleep")
nvsState.set_i32("start",i+1)
nvsState.commit()
deepsleep(1000)

 

Programs

Raspberry Pi IoT in C Third Edition

 

piciot3e360

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into a VS Code project.  

Note: The VS Code task listings are in Appendix II.

The only downside is that you have to create a project to paste the code into.

To do this follow the instructions in the book - in particular remember to add the bcm2835 library and also any library references that may be needed. The majority of the programs also need to be run with root permissions.

All of the programs below were copy and pasted from working programs in the IDE.

If anything you consider important is missing or if you have any requests or comments  contact me

This email address is being protected from spambots. You need JavaScript enabled to view it.


Chapter  2

Page 28

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
    printf("Hello C World");
    int test = 42;
    printf("%d\n", test);
    return (EXIT_SUCCESS);
}
 

Chapter  3

Page 47

#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_delay(500);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
        bcm2835_delay(500);
    }
    bcm2835_close();
    return 0;
}

Chapter  4

Page 50

#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    for (;;)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}
 

Page 62

#define _DEFAULT_SOURCE
#include <bcm2835.h>
#include <stdio.h>
#include <time.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    volatile int i;
    struct timespec delay = {0, 10 * 1000};
    for (;;)
    {
        bcm2835_gpio_set(RPI_BPLUS_GPIO_J8_07);
        nanosleep(&delay, NULL);
        bcm2835_gpio_clr(RPI_BPLUS_GPIO_J8_07);
        nanosleep(&delay, NULL);
    }
    bcm2835_close();
    return 0;
}
 

Page 64

#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    volatile int i;
    int n = 10;
    for (;;)
    {
        for (i = 0; i < n; i++)
        {
        };
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        for (i = 0; i < n; i++)
        {
        };
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}
 

Page 65

 
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <time.h> 

#define BILLION 1000000000L 

int main(int argc, char** argv) {
    struct timespec btime, etime;

    volatile int i;
    clock_gettime(CLOCK_REALTIME, &btime);
    for (i = 0; i < 10000000; i++) {
    };
    clock_gettime(CLOCK_REALTIME, &etime);
    double nseconds =  (double) ((etime.tv_sec - btime.tv_sec)* BILLION)+(double) (etime.tv_nsec - btime.tv_nsec);
    int n = (int) 10 /nseconds * BILLION + 0.5;
    printf("time = %f (s)  \n \r",nseconds / BILLION);
    printf("n= %d \n\r", n);
    return (EXIT_SUCCESS);
}

Page 66

 
#include <bcm2835.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07,
                      BCM2835_GPIO_FSEL_OUTP);
    for (;;)
    {
        bcm2835_gpio_set(RPI_BPLUS_GPIO_J8_07);
        bcm2835_delayMicroseconds(1);
        bcm2835_gpio_clr(RPI_BPLUS_GPIO_J8_07);
        bcm2835_delayMicroseconds(1);
    }
    bcm2835_close();
    return 0;
}
 

Page 67

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07,BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11,BCM2835_GPIO_FSEL_OUTP);
    volatile int i;
    for (;;)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
    }
    return (EXIT_SUCCESS);
}
 

Page 68

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    uint32_t mask = (1 << RPI_BPLUS_GPIO_J8_07) | (1 << RPI_BPLUS_GPIO_J8_11);
    for (;;)
    {
        bcm2835_gpio_set_multi(mask);
        bcm2835_gpio_clr_multi(mask);
    }

    return (EXIT_SUCCESS);
}
 

Chapter 6

 Page 89

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);

    while (1)
    {
        if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
        {
            printf("Line Low \n\r");
            fflush(stdout);
        };
    }
    return 0;
}
 

Page 90

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);

    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07));
        bcm2835_delayMicroseconds(1000);
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07));
        bcm2835_delayMicroseconds(1000);
        printf("Button Push \n\r");
        fflush(stdout);
    }
    return 0;
}
 

Page 91

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    uint64_t t;
    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07)) ;
        t = bcm2835_st_read();
        bcm2835_delayMicroseconds(1000);
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07)) ;
        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000);
        if (t > 5000000)
        {
            printf("Putton held \n\r");
        }
        else
        {
            printf("Button Push \n\r");
        }
        fflush(stdout);
    }
    return 0;
}
 

Page 92

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{

    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);

    volatile int i;
    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07)) ;
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07)) ;
        for (i = 0; i < 5000; i++)
        {
            if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        printf("%d\n\r", i);
        fflush(stdout);
    }
    return (EXIT_SUCCESS);
}
 

Page 93

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    volatile int i;
    uint64_t t;
    while (1)
    {
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07)) ;
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07)) ;
        t = bcm2835_st_read();
        for (i = 0; i < 5000; i++)
        {
            if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        t = bcm2835_st_read() - t;
        printf("%d,%llu\n\r", i, t);
        fflush(stdout);
    }
    return (EXIT_SUCCESS);
}
 

Page 94

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);

    uint64_t t;
    while (1)
    {
        while (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07));
        t = bcm2835_st_read();
        while (1 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07));
        t = bcm2835_st_read() - t;
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
    }
    return (EXIT_SUCCESS);
}
 

 Page 97 

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    uint64_t t;
    int s = 0;
    int i;
    while (1)
    {
        t = bcm2835_st_read();
        i = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);
        switch (s)
        {
        case 0: //Button not pushed
            if (!i)
            {
                s = 1;
                printf("Button Push \n\r");
                fflush(stdout);
            }
            break;
        case 1: //Button pushed
            if (i)
            {
                s = 0;
            }
            break;
        default:
            s = 0;
        }
        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000 - t);
    }
    return 0;
}

Page 99

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    uint64_t t, tpush = 0;
    int s = 0, i;
    while (1)
    {
        t = bcm2835_st_read();
        i = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);
        switch (s)
        {
        case 0: //Button not pushed
            if (!i)
            {
                s = 1;
                tpush = t;
            }
            break;
        case 1: //Button pushed
            if (i)
            {
                s = 0;
                if ((t - tpush) > 5000000)
                {
                    printf("Button held \n\r");
                }
                else
                {
                    printf("Button pushed \n\r");
                }
                fflush(stdout);
            }
            break;
        default:
            s = 0;
        }
        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000 - t);
    }
    return 0;
}
 

Page 100

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_13, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_15, BCM2835_GPIO_FSEL_OUTP);

    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, LOW);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, LOW);

    uint64_t t;
    int buttonState = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);

    int state = 0;
    while (1)
    {
        t = bcm2835_st_read();
        int buttonNow = bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07);
        int edge = buttonState - buttonNow;
        buttonState = buttonNow;

        switch (state)
        {
        case 0:
            if (edge)
            {
                state = 1;
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, HIGH);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, LOW);
            }
            break;
        case 1:
            if (edge)
            {
                state = 2;
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, HIGH);
            }
            break;
        case 2:
            if (edge)
            {
                state = 0;
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_13, LOW);
                bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_15, LOW);
            }
            break;
        }

        t = bcm2835_st_read() - t;
        bcm2835_delayMicroseconds(1000 - t);
    }
    return 0;
}
 

Chapter 7

 

Page 111

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd;
    struct gpiochip_info info;

    fd = open("/dev/gpiochip0", O_RDONLY);

    int ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &info);
    close(fd);
    printf("label: %s\n name: %s\n number of lines: %u\n", info.label, info.name, info.lines);
    return 0;
}
 

Page 114

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd, ret;

    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    req.lineoffsets[1] = 17;
    req.flags = GPIOHANDLE_REQUEST_OUTPUT;
    req.default_values[0] = 0;
    req.default_values[1] = 0;
    strcpy(req.consumer_label, "Output test");
    req.lines = 2;

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    close(fd);

    struct gpiohandle_data data;
    data.values[0] = 0;
    data.values[1] = 1;
    while (1)
    {
        data.values[0] = !data.values[0];
        data.values[1] = !data.values[1];
        ret = ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
    }
    return 0;
}
 

Page 116

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>

int main(int argc, char **argv)
{
    int fd, ret;

    struct gpiohandle_request req;
    req.lineoffsets[0] = 4;
    req.lineoffsets[1] = 17;
    req.flags = GPIOHANDLE_REQUEST_INPUT;
    strcpy(req.consumer_label, "Input test");
    req.lines = 2;

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    close(fd);

    struct gpiohandle_data data;
    ret = ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
    printf("%hhu , %hhu", data.values[0], data.values[1]);
    close(req.fd);
    return 0;
}

Chapter 8

Page 122

Not a full program just a function definition
 
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void checkIRQ()
{
    FILE *fp = popen("sudo dtparam -l", "r");
    if (fp == NULL)
    {
        printf("Failed to run command\n\r");
        exit(1);
    }
    char output[1024];
    int txfound = 0;
    while (fgets(output, sizeof(output), fp) != NULL)
    {
        printf("%s\n\r", output);
        fflush(stdout);
        if (strstr(output, "gpio-no-irq") != NULL)
        {
            txfound = 1;
        }
    }
    pclose(fp);

    if (txfound == 0)
    {
        fp = popen("sudo dtoverlay gpio-no-irq", "r");
        if (fp == NULL)
        {
            printf("Failed to run command\n\r");
            exit(1);
        }
        pclose(fp);
    }
}
 

Page 126

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_ren(RPI_BPLUS_GPIO_J8_07);

    volatile int i;
    uint64_t t;
    while (1)
    {
        bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
        while (0 == bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07)) ;
        t = bcm2835_st_read();
        bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
        for (i = 0; i < 5000; i++)
        {
            if (1 == bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        t = bcm2835_st_read() - t;
        printf("%d,%llu\n\r", i, t);
        fflush(stdout);
    }
    return (EXIT_SUCCESS);
}
 

Page 127

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_clr_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_11, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);

    uint64_t t;
    while (1)
    {
        bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
        t = bcm2835_st_read();
        for (;;)
        {
            if (1 == bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
                break;
        }
        t = bcm2835_st_read() - t;
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_11, LOW);
    }
    return (EXIT_SUCCESS);
}
 

 Page 128

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    printf("Press button \n\r");
    fflush(stdout);
    sleep(20);
    if (0 == bcm2835_gpio_lev(RPI_BPLUS_GPIO_J8_07))
    {
        printf("Button pressed \n\r");
    }
    else
    {
        printf("No Button press\n\r");
    };
    return 0;
}
 

Page 129

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_PUD_UP);
    bcm2835_gpio_fen(RPI_BPLUS_GPIO_J8_07);
    bcm2835_gpio_set_eds(RPI_BPLUS_GPIO_J8_07);
    printf("Press button \n\r");
    fflush(stdout);
    sleep(20);
    if (bcm2835_gpio_eds(RPI_BPLUS_GPIO_J8_07))
    {
        printf("Button pressed \n\r");
    }
    else
    {
        printf("No Button press\n\r");
    };
    return 0;
}
 

 Page 132

 
#include <string.h>
#include <stdio.h> 
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
#include <sys/epoll.h>

int main(int argc, char **argv) {
    int fd, ret;

    struct gpioevent_request req;
    req.lineoffset = 4;
    req.handleflags = GPIOHANDLE_REQUEST_INPUT;
    req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE;
    strcpy(req.consumer_label, "Event test");

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &req);
    close(fd);

    static struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = req.fd;
    int epfd = epoll_create(1);
    int res = epoll_ctl(epfd, EPOLL_CTL_ADD, req.fd, &ev);

    int nfds = epoll_wait(epfd, &ev, 1, 20000);
    if (nfds != 0) {
        struct gpioevent_data edata;
        read(req.fd, &edata, sizeof edata);
        printf("%u,%llu", edata.id, edata.timestamp);
    }
}
 

Page 137 

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/gpio.h>
#include <sys/epoll.h>

#include <pthread.h>
uint64_t t[20];
typedef void (*eventHandler)(int);

typedef struct
{
    int epfd;
    int fd;
    eventHandler func;
} intVec;

void myHandler(int fd)
{
    struct gpioevent_data edata;
    read(fd, &edata, sizeof edata);
    printf("%u,%llu \n\r", edata.id, edata.timestamp);
    fflush(stdout);
}
void *waitInterrupt(void *arg)
{
    intVec *intData = (intVec *)arg;
    struct epoll_event ev;
    for (;;)
    {
        int nfds = epoll_wait(intData->epfd, &ev, 1, 20000);

        if (nfds != 0)
        {
            intData->func(intData->fd);
        }
    }
}
int main(int argc, char **argv)
{
    int fd, ret;
    struct gpioevent_request req;
    req.lineoffset = 4;
    req.handleflags = GPIOHANDLE_REQUEST_INPUT;
    req.eventflags = GPIOEVENT_REQUEST_RISING_EDGE;
    strcpy(req.consumer_label, "Event test");

    fd = open("/dev/gpiochip0", O_RDONLY);
    ret = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, &req);
    close(fd);
    static struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = req.fd;
    int epfd = epoll_create(1);
    int res = epoll_ctl(epfd, EPOLL_CTL_ADD, req.fd, &ev);
    intVec intData;
    intData.epfd = epfd;
    intData.fd = req.fd;
    intData.func = &myHandler;
    pthread_t intThread;
    if (pthread_create(&intThread, NULL, waitInterrupt,
                       (void *)&intData))
    {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    for (;;)
    {
        printf("Working\n\r");
        fflush(stdout);
        sleep(2);
    }
}
 

page 140

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <bcm2835.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>

#define BUFFER_MAX 50

typedef void (*eventHandler)();

int openGPIO(int pin, int direction);
int writeGPIO(int gpio, int value);
int readGPIO(int gpio);
int setEdgeGPIO(int gpio, char *edge);
void *waitInterrupt(void *arg);
int attachGPIO(int gpio, char *edge, eventHandler func);

int fd[32] = {0};
typedef struct
{
    int fd;
    int gpio;
    eventHandler func;
} intVec;

intVec intData;
static int count;

void myIntHandler()
{
    count++;
};
int main(int argc, char **argv)
{
    attachGPIO(4, "both", myIntHandler);
    for (;;)
    {
        printf("Interrupt %d\n\r", count);
        fflush(stdout);
    };
    return 0;
}

int openGPIO(int gpio, int direction)
{
    if (gpio < 0 || gpio > 31)
        return -1;
    if (direction < 0 || direction > 1)
        return -2;
    int len;
    char buf[BUFFER_MAX];
    if (fd[gpio] != 0)
    {
        close(fd[gpio]);
        fd[gpio] = open("/sys/class/gpio/unexport", O_WRONLY);
        len = snprintf(buf, BUFFER_MAX, "%d", gpio);
        write(fd[gpio], buf, len);
        close(fd[gpio]);
        fd[gpio] = 0;
    }

    fd[gpio] = open("/sys/class/gpio/export", O_WRONLY);
    len = snprintf(buf, BUFFER_MAX, "%d", gpio);
    write(fd[gpio], buf, len);
    close(fd[gpio]);
    len = snprintf(buf, BUFFER_MAX,
                   "/sys/class/gpio/gpio%d/direction", gpio);
    fd[gpio] = open(buf, O_WRONLY);
    if (direction == 1)
    {
        write(fd[gpio], "out", 4);
        close(fd[gpio]);
        len = snprintf(buf, BUFFER_MAX,
                       "/sys/class/gpio/gpio%d/value", gpio);
        fd[gpio] = open(buf, O_WRONLY);
    }
    else
    {
        write(fd[gpio], "in", 3);
        close(fd[gpio]);
        len = snprintf(buf, BUFFER_MAX,
                       "/sys/class/gpio/gpio%d/value", gpio);
        fd[gpio] = open(buf, O_RDONLY);
    }
    return 0;
}

int writeGPIO(int gpio, int b)
{
    if (b == 0)
    {
        write(fd[gpio], "0", 1);
    }
    else
    {
        write(fd[gpio], "1", 1);
    }

    lseek(fd[gpio], 0, SEEK_SET);
    return 0;
}

int readGPIO(int gpio)
{
    char value_str[3];
    int c = read(fd[gpio], value_str, 3);
    lseek(fd[gpio], 0, SEEK_SET);

    if (value_str[0] == '0')
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

int setEdgeGPIO(int gpio, char *edge)
{
    char buf[BUFFER_MAX];
    int len = snprintf(buf, BUFFER_MAX,
                       "/sys/class/gpio/gpio%d/edge", gpio);
    int fd = open(buf, O_WRONLY);
    write(fd, edge, strlen(edge) + 1);
    close(fd);
    return 0;
}

int attachGPIO(int gpio, char *edge, eventHandler func)
{
    openGPIO(gpio, 0);
    setEdgeGPIO(gpio, edge);
    readGPIO(gpio);
    intData.fd = fd[gpio];
    intData.gpio = gpio;
    intData.func = func;
    pthread_t intThread;
    if (pthread_create(&intThread,
                       NULL, waitInterrupt, (void *)&intData))
    {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }
    return 0;
}
void *waitInterrupt(void *arg)
{

    intVec *intData = (intVec *)arg;
    int gpio = intData->gpio;
    struct pollfd fdset[1];
    fdset[0].fd = intData->fd;
    fdset[0].events = POLLPRI;
    fdset[0].revents = 0;
    for (;;)
    {
        int rc = poll(fdset, 1, -1);
        if (fdset[0].revents & POLLPRI)
        {
            intData->func();
            lseek(fdset[0].fd, 0, SEEK_SET);
            readGPIO(gpio);
        }
    }
    pthread_exit(0);
}

Chapter 9

Page 151

#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 2);
    bcm2835_pwm_set_data(0, 1);
    return (0);
}
 

Page 152

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_gpio_fsel(13, BCM2835_GPIO_FSEL_ALT0);
    bcm2835_pwm_set_clock(2);

    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 2);
    bcm2835_pwm_set_data(0, 1);

    bcm2835_pwm_set_mode(1, 1, 1);
    bcm2835_pwm_set_range(1, 8);
    bcm2835_pwm_set_data(1, 2);
    return (EXIT_SUCCESS);
}
 

Page 153

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 256);
    for (;;)
    {
        bcm2835_pwm_set_data(0, 16);
        bcm2835_delayMicroseconds((int)26.666 * 8);
        bcm2835_pwm_set_data(0, 128);
        bcm2835_delayMicroseconds((int)26.666 * 8);
    }
    return (EXIT_SUCCESS);
}
 

Page 155

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char** argv) {
    if (!bcm2835_init())
        return 1;


    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 256);
    for (;;) {
        for (int i = 0; i < 256; i = i + 10) {
            bcm2835_pwm_set_data(0, i);
            bcm2835_delayMicroseconds(100);
        }
    }
    return (EXIT_SUCCESS);
}
 

Page 156

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    int C = 34091;
    bcm2835_pwm_set_range(0, C);
    bcm2835_pwm_set_data(0, C / 2);
    return (EXIT_SUCCESS);
}

Page 158

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv){
    if (!bcm2835_init())
            return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);
    int w = 1;
    int inc = 1;
    for (;;)
    {
        bcm2835_pwm_set_data(0, w);
        w = w + inc;
        if (w > 1024 || w <= 0)
            inc = -inc;
        bcm2835_delayMicroseconds(5000);
    }
    return (EXIT_SUCCESS);
}
    bcm2835_delayMicroseconds(5000);
    }
    return (EXIT_SUCCESS);
}
 

Page 159

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);
    int w = 0;
    int inc = 1;
    for (;;)
    {
        bcm2835_pwm_set_data(0, w * w * w);
        w = w + inc;
        if (w > 10 || w <= 0)
            inc = -inc;
        bcm2835_delayMicroseconds(50000);
    }
    return (EXIT_SUCCESS);
}
 

Page 160

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(2);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);
    int w = 0;
    int inc = 1;

    for (;;)
    {
        bcm2835_pwm_set_data(0, (w * w * w) >> 3);
        w = w + inc;
        if (w > 20 || w <= 0)
            inc = -inc;
        bcm2835_delayMicroseconds(50000);
    }
    return (EXIT_SUCCESS);
}
 

Page 163 

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(375);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);

    for (;;)
    {
        bcm2835_pwm_set_data(0, 25);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 50);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 128);
        bcm2835_delayMicroseconds(2000000);
    }
    return (EXIT_SUCCESS);
}
 

Page 164 

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock(375);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 1024);

    for (;;)
    {
        bcm2835_pwm_set_data(0, 52 * 0 / 180 + 920);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 52 * 90 / 180 + 920);
        bcm2835_delayMicroseconds(2000000);
        bcm2835_pwm_set_data(0, 52 * 180 / 180 + 920);
        bcm2835_delayMicroseconds(2000000);
    }
    return (EXIT_SUCCESS);
}

Page 166

Function only - needs to run as root.
 
void bcm2835_pwm_set_clock_source(
    uint32_t source,
    uint32_t divisorI,
    uint32_t divisorF)
{
    divisorI &= 0xfff;
    divisorF &= 0xfff;
    source &= 0xf;
    uint8_t mask = bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0xffffffef;
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | mask);
    while ((bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0x80) != 0)
    {
    };
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | source | 0x200);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | 0x210 | source);
}
 

Page 168

 This needs to be run as root.
 
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <bcm2835.h>

void bcm2835_pwm_set_clock_source(uint32_t source,uint32_t divisorI,uint32_t divisorF)
{
    divisorI &= 0xfff;
    divisorF &= 0xfff;
    source &= 0xf;
    uint8_t mask = bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) &  0xffffffef;
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL,  BCM2835_PWM_PASSWRD | mask);
    while ((bcm2835_peri_read(bcm2835_clk + BCM2835_PWMCLK_CNTL) & 0x80) != 0)
    {
    };
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | source | 0x200);
    bcm2835_peri_write(bcm2835_clk + BCM2835_PWMCLK_CNTL, BCM2835_PWM_PASSWRD | 0x210 | source);
}

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT5);
    bcm2835_pwm_set_clock_source(6, 2, 0);
    bcm2835_pwm_set_mode(0, 1, 1);
    bcm2835_pwm_set_range(0, 256);
    int i;
    for (;;)
    {
        for (i = 0; i < 256; i = i + 10)
        {
            bcm2835_pwm_set_data(0, i);
            bcm2835_delayMicroseconds(2);
        }
    }
    return (EXIT_SUCCESS);
}
 

Chapter 10

Page 184 

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    char buf[] = {0xE7};
    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_148);
    bcm2835_i2c_setSlaveAddress(0x40);
    bcm2835_i2c_write(buf, 1);
    bcm2835_i2c_read(buf, 1);
    printf("User Register = %X \r\n", buf[0]);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}
 

 Page 186

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

void setTimeout(uint32_t timeout) {
    volatile uint32_t* stimeout = bcm2835_bsc1 + BCM2835_BSC_CLKT / 4;
    bcm2835_peri_write(stimeout, timeout);
}

int main(int argc, char** argv) {
    if (!bcm2835_init())
        return 1;

    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_150);
    setTimeout(0);
    char buf[4] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n\r lsb %d \n\r checksum %d \n\r", msb, lsb, check);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}
 

Page 188 

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

void setTimeout(uint32_t timeout)
{
    volatile uint32_t *stimeout = bcm2835_bsc1 + BCM2835_BSC_CLKT / 4;
    bcm2835_peri_write(stimeout, timeout);
}

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_2500);
    setTimeout(20000);
    char buf[3] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n\r lsb %d \n\r checksum %d \n\r", msb, lsb, check);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}
 

Page 192

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

void setTimeout(uint16_t timeout);
uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check);
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;

    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_2500);
    setTimeout(20000);
    char buf[4] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];

    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    unsigned int data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float temp = (float)(-46.85 + (175.72 * data16 / (float)65536));
    printf("Temperature %f C \n\r", temp);

    buf[0] = 0xF5;
    bcm2835_i2c_write(buf, 1);
    while (bcm2835_i2c_read(buf, 3) == BCM2835_I2C_REASON_ERROR_NACK)
    {
        bcm2835_delayMicroseconds(500);
    };
    msb = buf[0];
    lsb = buf[1];
    check = buf[2];
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float hum = -6 + (125.0 * (float)data16) / 65536;
    printf("Humidity %f %% \n\r", hum);
    bcm2835_i2c_end();

    return (EXIT_SUCCESS);
}

void setTimeout(uint16_t timeout)
{
    volatile uint32_t *stimeout = bcm2835_bsc1 + BCM2835_BSC_CLKT / 4;
    bcm2835_peri_write(stimeout, timeout);
}

uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check)
{
    uint32_t data32 = ((uint32_t)msb << 16) | ((uint32_t)lsb << 8) | (uint32_t)check;
    uint32_t divisor = 0x988000;
    for (int i = 0; i < 16; i++)
    {
        if (data32 & (uint32_t)1 << (23 - i))
            data32 ^= divisor;
        divisor >>= 1;
    };
    return (uint8_t)data32;
}
 

Chapter 11

Page 203 

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>

uint8_t getByte(int b, int buf[]);
void GetDHT22data(uint8_t pin);

int main(int argc, char **argv)
{
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(1000);
    GetDHT22data(RPI_BPLUS_GPIO_J8_07);
    return 0;
}

void GetDHT22data(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(1000);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    int i;
    for (i = 1; i < 2000; i++)
    {
        if (bcm2835_gpio_lev(pin) == 0)
            break;
    };
    uint64_t t;
    int buf[41];
    int j;
    bcm2835_delayMicroseconds(1);
    for (j = 0; j < 41; j++)
    {
        for (i = 1; i < 2000; i++)
        {
            if (bcm2835_gpio_lev(pin) == 1)
                break;
        };
        t = bcm2835_st_read();
        for (i = 1; i < 2000; i++)
        {
            if (bcm2835_gpio_lev(pin) == 0)
                break;
        }
        buf[j] = (bcm2835_st_read() - t) > 50;
    }

    int byte1 = getByte(1, buf);
    int byte2 = getByte(2, buf);
    int byte3 = getByte(3, buf);
    int byte4 = getByte(4, buf);
    int byte5 = getByte(5, buf);
    printf("Checksum %d %d \n\r", byte5, (byte1 + byte2 + byte3 + byte4) & 0xFF);
    float humidity = (float)(byte1 << 8 | byte2) / 10.0;
    printf("Humidity= %f \n\r", humidity);
    float temperature;
    int neg = byte3 & 0x80;
    byte3 = byte3 & 0x7F;
    temperature = (float)(byte3 << 8 | byte4) / 10.0;
    if (neg > 0)
        temperature = -temperature;
    printf("Temperature= %f \n\r", temperature);
    return;
}

uint8_t getByte(int b, int buf[])
{
    int i;
    uint8_t result = 0;
    b = (b - 1) * 8 + 1;
    for (i = b; i <= b + 7; i++)
    {
        result = result << 1;
        result = result | buf[i];
    }
    return result;
}

Chapter 13 

Page 223

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>

int presence(uint8_t pin);
void writeByte(uint8_t pin, int byte);
uint8_t crc8(uint8_t *data, uint8_t len);
int readByte(uint8_t pin);
int readiButton(uint8_t pin, uint8_t *data);

int main(int argc, char **argv)
{
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);

    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_INPT);

    int i;
    uint8_t code[8];
    for (;;)
    {
        int p = readiButton(RPI_BPLUS_GPIO_J8_07, code);
        if (p == 1)
        {
            for (i = 0; i < 8; i++)
            {
                printf("%hhX ", code[i]);
            }
            printf("\n\r");
            fflush(stdout);
        }
        bcm2835_delayMicroseconds(100000);
    };
    bcm2835_close();
    return 0;
}

int presence(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(480);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(70);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(410);
    return b;
}

void writeBit(uint8_t pin, int b)
{

    int delay1, delay2;
    if (b == 1)
    {
        delay1 = 6;
        delay2 = 64;
    }
    else
    {
        delay1 = 80;
        delay2 = 10;
    }
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(delay1);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(delay2);
}

uint8_t readBit(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(6);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(9);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(55);
    return b;
}

void writeByte(uint8_t pin, int byte)
{
    int i;
    for (i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(pin, 1);
        }
        else
        {
            writeBit(pin, 0);
        }
        byte = byte >> 1;
    }
}

int readByte(uint8_t pin)
{
    int byte = 0;
    int i;
    for (i = 0; i < 8; i++)
    {
        byte = byte | readBit(pin) << i;
    };
    return byte;
}
uint8_t crc8(uint8_t *data, uint8_t len)
{

    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++)
    {
        databyte = data[i];
        for (j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;

            databyte >>= 1;
        }
    }

    return crc;
}

int readiButton(uint8_t pin, uint8_t *data)
{
    int b = presence(pin);
    if (b != 0)
        return 0;
    writeByte(pin, 0x33);
    int i;
    for (i = 0; i < 8; i++)
    {
        data[i] = readByte(pin);
    }
    uint8_t crc = crc8(data, 8);
    if (crc == 0)
        return 1;
    return 0;
}

Chapter 14

 Page 233

#include <bcm2835.h>
#include <stdio.h>

int presence(uint8_t pin);
void writeBit(uint8_t pin, int b);
void writeByte(uint8_t pin, int byte);
uint8_t readBit(uint8_t pin);
int convert(uint8_t pin);
int readByte(uint8_t pin);
float getTemperature(uint8_t pin);
uint8_t crc8(uint8_t *data, uint8_t len);

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    if (presence(RPI_BPLUS_GPIO_J8_07) == 1)
    {
        printf("No device \n");
    }
    else
    {
        printf("Device present \n");
    }
    fflush(stdout);
    float t;
    for (;;)
    {
        do
        {
            t = getTemperature(RPI_BPLUS_GPIO_J8_07);
        } while (t < -999);
        printf("%f\r\n", t);
        fflush(stdout);
    };
    bcm2835_close();

    return 0;
}

int presence(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(480);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(70);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(410);
    return b;
}

void writeBit(uint8_t pin, int b)
{
    int delay1, delay2;
    if (b == 1)
    {
        delay1 = 6;
        delay2 = 64;
    }
    else
    {

        delay1 = 60;
        delay2 = 10;
    }
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(delay1);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(delay2);
}

void writeByte(uint8_t pin, int byte)
{
    int i;
    for (i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(pin, 1);
        }
        else
        {

            writeBit(pin, 0);
        }
        byte = byte >> 1;
    }
}

uint8_t readBit(uint8_t pin)
{
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(8);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(2);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(60);
    return b;
}

int convert(uint8_t pin)
{
    int i;
    writeByte(pin, 0x44);
    for (i = 0; i < 5000; i++)
    {
        bcm2835_delayMicroseconds(100000);
        if (readBit(pin) == 1)
            break;
    }
    return i;
}

float getTemperature(uint8_t pin)
{
    if (presence(pin) == 1)
        return -1000;
    writeByte(pin, 0xCC);
    if (convert(pin) == 5000)
        return -3000;
    presence(pin);
    writeByte(pin, 0xCC);
    writeByte(pin, 0xBE);
    int i;
    uint8_t data[9];
    for (i = 0; i < 9; i++)
    {
        data[i] = readByte(pin);
    }
    uint8_t crc = crc8(data, 9);
    if (crc != 0)
        return -2000;
    int t1 = data[0];
    int t2 = data[1];
    int16_t temp1 = (t2 << 8 | t1);
    float temp = (float)temp1 / 16;
    return temp;
}

int readByte(uint8_t pin)
{
    int byte = 0;
    int i;
    for (i = 0; i < 8; i++)
    {
        byte = byte | readBit(pin) << i;
    };
    return byte;
}

uint8_t crc8(uint8_t *data, uint8_t len)
{
    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++)
    {
        databyte = data[i];
        for (j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;
            databyte >>= 1;
        }
    }
    return crc;
}

Chapter 15

Page 246

function only - needs a main program to call it

int oneWireScan(uint8_t pin, uint64_t serial[])
{
    static int bitcount = 0;
    static int deviceCount = 0;

    if (bitcount > 63)
    {
        bitcount = 0;
        deviceCount++;
        return deviceCount;
    }

    if (bitcount == 0)
    {
        if (presence(pin) == 1)
        {
            bitcount = 0;
            return deviceCount;
        }
        deviceCount = 0;
        serial[deviceCount] = 0;
        writeByte(pin, 0xF0);
    };

    int b1 = readBit(pin);
    int b2 = readBit(pin);

    if (b1 == 0 && b2 == 1)
    {
        serial[deviceCount] >>= 1;
        writeBit(pin, 0);
        bitcount++;
        oneWireScan(pin, serial);
    };

    if (b1 == 1 && b2 == 0)
    {
        serial[deviceCount] >>= 1;
        serial[deviceCount] |= 0x8000000000000000LL;
        writeBit(pin, 1);
        bitcount++;
        oneWireScan(pin, serial);
    };

    if (b1 == 1 && b2 == 1)
    {
        bitcount = 0;
        return deviceCount;
    };
    if (b1 == 0 && b2 == 0)
    {
        serial[deviceCount] >>= 1;
        writeBit(pin, 0);
        int bitposition = bitcount;
        bitcount++;
        oneWireScan(pin, serial);

        bitcount = bitposition;
        if (presence(pin) == 1)
        {
            bitposition = 0;
            return 0;
        }

        writeByte(pin, 0xF0);
        uint64_t temp = serial[deviceCount - 1] | (0x1LL << (bitcount));
        int i;
        uint64_t bit;
        for (i = 0; i < bitcount + 1; i++)
        {
            bit = temp & 0x01LL;
            temp >>= 1;
            b1 = readBit(pin);
            b2 = readBit(pin);
            writeBit(pin, bit);
            serial[deviceCount] >>= 1;
            serial[deviceCount] |= (bit << 63);
        }
        bitcount++;
        oneWireScan(pin, serial);
    };

    return deviceCount;
}

Chapter 16

Page 268

On a Pi 5 serial0 opens the debug port. If you want to use GPIO14 and 15 use /dev/ttyAMA0 or any UART you have enabled.

#include <unistd.h>

#include <fcntl.h>

#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main(int argc, char **argv)
{
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    return 0;
}
 

Page 268

On a Pi 5 serial0 opens the debug port. If you want to use GPIO14 and 15 use /dev/ttyAMA0 or any UART you have enabled.

This loopback most likely wont work unless the serial port is already configured - see next program.

 

#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    char buf[] = "hello world";
    char buf2[11];
    int count = write(sfd, buf, 11);
    count = read(sfd, buf2, 11);
    buf2[11] = 0;
    printf("%s", buf2);
    close(sfd);
    return 0;
}

Page 278

On a Pi 5 serial0 opens the debug port. If you want to use GPIO14 and 15 use /dev/ttyAMA0 or any UART you have enabled.

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>

int main(int argc, char **argv)
{
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    cfmakeraw(&options);
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 1;
    tcsetattr(sfd, TCSANOW, &options);
    char buf[] = "hello world";
    char buf2[11];
    int count = write(sfd, buf, 11);
    count = read(sfd, buf2, 11);
    buf2[11] = 0;
    printf("%s", buf2);
    close(sfd);
    return 0;
}
 

Page 279

On a Pi 5 serial0 opens the debug port. If you want to use GPIO14 and 15 use /dev/ttyAMA0 or any UART you have enabled.

 
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>

int main(int argc, char **argv)
{
    system("sudo systemctl stop serial-getty@serial0 .service");
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    cfmakeraw(&options);
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 1;
    options.c_cc[VMIN] = 100;
    tcsetattr(sfd, TCSANOW, &options);
    char buf[] = "hello world";
    char buf2[100];
    int count = write(sfd, buf, strlen(buf));
    usleep(100000);
    int bytes;
    ioctl(sfd, FIONREAD, &bytes);
    if (bytes != 0)
    {
        count = read(sfd, buf2, 100);
    }
    printf("%s\n\r", buf2);
    close(sfd);
    return (EXIT_SUCCESS);
}
 

Page 281

On a Pi 5 serial0 opens the debug port. If you want to use GPIO14 and 15 use /dev/ttyAMA0 or any UART you have enabled.

 
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>

int main(int argc, char **argv)
{
    system("sudo systemctl stop serial-getty@serial0 .service");
    int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };

    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    cfmakeraw(&options);
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 0;
    tcsetattr(sfd, TCSANOW, &options);

    char buf[] = "hello world";
    char buf2[100];
    char c;
    int count = write(sfd, buf, strlen(buf) + 1);

    int i = 0;
    while (1)
    {
        count = read(sfd, &c, 1);
        if (count != 0)
        {
            buf2[i] = c;
            i++;
            if (c == 0)
                break;
        };
    };
    printf("%s\n\r", buf2);
    close(sfd);
    return (EXIT_SUCCESS);
}
 

Page 287

 

On a Pi 5 serial0 opens the debug port. If you want to use GPIO14 and 15 use /dev/ttyAMA0 or any UART you have enabled.

 
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <stdint.h>

int openPort(char port[]);
int presence(int sfd);
void writeBit(int sfd, int b);
uint8_t readBit(int sfd);
void writeByte(int sfd, int byte);
int readByte(int sfd);
int readByte(int sfd);
float getTemperature(int sfd);
int convert(int sfd);

uint8_t crc8(uint8_t *data, uint8_t len);

int main(int argc, char **argv)
{
    int sfd = openPort("/dev/ttyAMA1");
    if (presence(sfd) == 0)
    {
        printf("Device Present\n\r");
    }
    else
    {
        printf("No Device\n\r");
    }
    for (;;)
    {
        float temp = getTemperature(sfd);
        printf("%f \n\r", temp);

        fflush(stdout);
    }
    close(sfd);
    return 0;
}

int openPort(char port[])
{
    int sfd = open(port, O_RDWR | O_NOCTTY);
    if (sfd == -1)
    {
        printf("Error no is : %d\n", errno);
        printf("Error description is : %s\n", strerror(errno));
        return (-1);
    };
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B115200);
    cfmakeraw(&options);
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag |= PARENB;
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag |= CLOCAL;
    options.c_cflag |= CREAD;
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 1;
    tcsetattr(sfd, TCSADRAIN, &options);
    return sfd;
}

int presence(int sfd)
{
    struct termios options;
    tcgetattr(sfd, &options);
    cfsetspeed(&options, B9600);
    tcsetattr(sfd, TCSADRAIN, &options);

    char buf = 0xF0;
    int count = write(sfd, &buf, 1);
    count = read(sfd, &buf, 1);

    tcgetattr(sfd, &options);
    cfsetspeed(&options, B115200);
    tcsetattr(sfd, TCSADRAIN, &options);
    if (buf == 0xF0)
        return -1;
    return 0;
}

void writeBit(int sfd, int b)
{
    char buf;
    if (b == 0)
    {
        buf = 0x00;
    }
    else
    {
        buf = 0xFF;
    }
    int count = write(sfd, &buf, 1);
    count = read(sfd, &buf, 1);
}

uint8_t readBit(int sfd)
{
    char buf;
    buf = 0xFF;
    int count = write(sfd, &buf, 1);
    count = read(sfd, &buf, 1);
    if (buf == 0xFF)
        return 1;
    return 0;
}

void writeByte(int sfd, int byte)
{
    for (int i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(sfd, 1);
        }
        else
        {
            writeBit(sfd, 0);
        }
        byte = byte >> 1;
    }
}

int readByte(int sfd)
{
    int byte = 0;
    for (int i = 0; i < 8; i++)
    {
        byte = byte | readBit(sfd) << i;
    };
    return byte;
}

int convert(int sfd)
{
    int i;
    writeByte(sfd, 0x44);
    for (i = 0; i < 5000; i++)
    {
        usleep(100000);
        if (readBit(sfd) != 0)
            break;
    }
    return i;
}

uint8_t crc8(uint8_t *data, uint8_t len)
{
    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++)
    {
        databyte = data[i];
        for (j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;
            databyte >>= 1;
        }
    }
    return crc;
}

float getTemperature(int sfd)
{
    if (presence(sfd) == -1)
        return -1000;
    writeByte(sfd, 0xCC);
    if (convert(sfd) == 5000)
        return -3000;

    presence(sfd);
    writeByte(sfd, 0xCC);
    writeByte(sfd, 0xBE);

    uint8_t data[9];
    for (int i = 0; i < 9; i++)
    {
        data[i] = readByte(sfd);
    }

    uint8_t crc = crc8(data, 9);
    if (crc != 0)
        return -2000;
    int t1 = data[0];
    int t2 = data[1];
    int16_t temp1 = (t2 << 8 | t1);
    float temp = (float)temp1 / 16;
    return temp;
}

Chapter 17

Page 303 

#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
    {
        return 1;
    }
    if (!bcm2835_spi_begin())
    {
        return 1;
    }

    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536);
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
    uint8_t read_data = bcm2835_spi_transfer(0xAA);
    if (read_data == 0xAA)
    {
        printf("data received correctly");
    }
    else
    {
        printf("data error");
    };
    bcm2835_spi_end();
    bcm2835_close();
    return (EXIT_SUCCESS);
}

Chapter 18

 Page 312

 
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (!bcm2835_init())
    {
        return 1;
    }
    if (!bcm2835_spi_begin())
    {
        return 1;
    }
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_8192);
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);

    char buf[] = {0x01, 0x80, 0x00};
    char readBuf[3];
    bcm2835_spi_transfernb(buf, readBuf, 3);
    int data = ((int)readBuf[1] & 0x03) << 8 | (int)readBuf[2];
    float volts = (float)data * 3.3f / 1023.0f;

    printf("%f", volts);
    bcm2835_spi_end();
    bcm2835_close();
    return (EXIT_SUCCESS);
}

 

Chapter 19

Page 324

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    addr.sin_addr.s_addr = 0x22d8b85d;
    if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        return -1;
    char header[] = "GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n";
    int n = write(sockfd, header, strlen(header));
    char buffer[2048];
    n = read(sockfd, buffer, 2048);
    printf("%s", buffer);
    return (EXIT_SUCCESS);
}
 

Page 326

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>

int main(int argc, char **argv)
{
    struct addrinfo hints;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    struct addrinfo *servinfo;
    int status = getaddrinfo("www.example.com", "80", &hints, &servinfo);
    int sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
    connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen);
    char header[] = "GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n";
    int n = write(sockfd, header, strlen(header));
    char buffer[2048];
    n = read(sockfd, buffer, 2048);
    printf("%s", buffer);
    return (EXIT_SUCCESS);
}
 

Page 331

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

int main(int argc, char **argv)
{
    struct addrinfo hints, *server;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    getaddrinfo(NULL, "80", &hints, &server);
    int sockfd = socket(server->ai_family, server->ai_socktype | SOCK_NONBLOCK, server->ai_protocol);
    bind(sockfd, server->ai_addr, server->ai_addrlen);
    listen(sockfd, 10);

    char buffer[2048];
    char html[] = "<html><head><title>Temperature</title></head><body><p>{\"humidity\":81%, \"airtemperature\":23.5C}</p></body></html>\r\n";

    char headers[1024] = {0};

    char Status[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\nServer:CPi\r\n";

    char Date[100];
    time_t now = time(NULL);
    struct tm *t = gmtime(&now);
    strftime(Date, sizeof(Date), "Date: %a, %d %b %Y %k:%M:%S %Z\r\n", t);

    char ContLen[100] = {0};
    snprintf(ContLen, sizeof ContLen, "Content-Length:%d \r\n", strlen(html));

    snprintf(headers, sizeof headers, "%s%s%s\r\n", Status, Date, ContLen);

    char data[2048] = {0};
    snprintf(data, sizeof data, "%s%s", headers, html);

    for (;;)
    {
        struct sockaddr_storage client_addr;
        socklen_t addr_size = sizeof client_addr;

        int client_fd = accept(sockfd, (struct sockaddr *)&client_addr, &addr_size);
        if (client_fd > 0)
        {
            int n = read(client_fd, buffer, 2048);
            printf("%s", buffer);
            fflush(stdout);
            n = write(client_fd, data, strlen(data));
            close(client_fd);
        }
    }
    return (EXIT_SUCCESS);
}

Chapter 20

Page 350

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    int memfd = open("/dev/mem", O_RDWR | O_SYNC);
    uint32_t *map = (uint32_t *)mmap(
        NULL,
        4 * 1024,
        (PROT_READ | PROT_WRITE),
        MAP_SHARED,
        memfd,
        (off_t)bcm2835_peripherals_base + BCM2835_GPIO_BASE);
    if (map == MAP_FAILED)
        printf("mmap failed: %s\n", strerror(errno));
    close(memfd);
    volatile uint32_t *paddr = map;
    *paddr = 0x1000;
    volatile uint32_t *paddr1 = map + 0x1C / 4;
    volatile uint32_t *paddr2 = map + 0x28 / 4;
    for (;;)
    {
        *paddr1 = 0x10;
        *paddr2 = 0x10;
    };
    return (EXIT_SUCCESS);
}
 

Page 355

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    uint32_t *gpioBASE = bcm2835_regbase(BCM2835_REGBASE_GPIO);
    bcm2835_peri_write(gpioBASE, 0x1000);
    for (;;)
    {
        bcm2835_peri_write(gpioBASE + BCM2835_GPSET0 / 4, 0x10);
        bcm2835_peri_write(gpioBASE + BCM2835_GPCLR0 / 4, 0x10);
    }
    return 0;
}
 

Page 360

 
#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

#define CLK_GP0_CTL 28
#define CLK_GP0_DIV 29
void bcm2835_GPIO4_set_clock_source(uint32_t, uint32_t, uint32_t);

int main(int argc, char **argv)
{
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(4, BCM2835_GPIO_FSEL_ALT0);
    bcm2835_GPIO4_set_clock_source(6, 50, 0);
}

void bcm2835_GPIO4_set_clock_source(
    uint32_t source,
    uint32_t divisorI,
    uint32_t divisorF)
{
    divisorI &= 0xfff;
    divisorF &= 0xfff;
    source &= 0xf;

    uint8_t mask = bcm2835_peri_read(bcm2835_clk + CLK_GP0_CTL) & 0xffffffef;

    bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | mask);

    while ((bcm2835_peri_read(bcm2835_clk + CLK_GP0_CTL) & 0x80) != 0)
    {
    };

    bcm2835_peri_write(bcm2835_clk + CLK_GP0_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
    bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | source | 0x200);
    bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | 0x0210 | source);
}
 

Page 362 

#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>

#define BCM2835_SPI6_BASE 0x204C00
volatile uint32_t *bcm2835_spiOLD;

int bcm2835_spi6_begin(void)
{
    volatile uint32_t *paddr;
    bcm2835_spiOLD = bcm2835_spi0;
    bcm2835_spi0 = bcm2835_peripherals + BCM2835_SPI6_BASE / 4;

    bcm2835_gpio_fsel(27, BCM2835_GPIO_FSEL_ALT3); /* CE1 */
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_ALT3); /* CE0 */
    bcm2835_gpio_fsel(19, BCM2835_GPIO_FSEL_ALT3); /* MISO */
    bcm2835_gpio_fsel(20, BCM2835_GPIO_FSEL_ALT3); /* MOSI */
    bcm2835_gpio_fsel(21, BCM2835_GPIO_FSEL_ALT3); /* CLK */

    paddr = bcm2835_spi0 + BCM2835_SPI0_CS / 4;
    bcm2835_peri_write(paddr, 0); /* All 0s */

    bcm2835_peri_write_nb(paddr, BCM2835_SPI0_CS_CLEAR);
    return 1;
}

void bcm2835_spi6_end(void)
{
    bcm2835_spi0 = bcm2835_spiOLD;
    /* Set all the SPI0 pins back to input */
    bcm2835_gpio_fsel(27, BCM2835_GPIO_FSEL_INPT); /* CE1 */
    bcm2835_gpio_fsel(18, BCM2835_GPIO_FSEL_INPT); /* CE0 */
    bcm2835_gpio_fsel(19, BCM2835_GPIO_FSEL_INPT); /* MISO */
    bcm2835_gpio_fsel(20, BCM2835_GPIO_FSEL_INPT); /* MOSI */
    bcm2835_gpio_fsel(21, BCM2835_GPIO_FSEL_INPT); /* CLK */
}

int main(int argc, char **argv)
{
    if (!bcm2835_init())
    {
        return 1;
    }

    if (!bcm2835_spi6_begin())
    {
        return 1;
    }

    bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_8192);
    bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
    bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);

    char buf[] = {0x01, 0x80, 0x00};
    char readBuf[3];
    bcm2835_spi_transfernb(buf, readBuf, 3);
    int data = ((int)readBuf[1] & 0x03) << 8 | (int)readBuf[2];
    float volts = (float)data * 3.3f / 1023.0f;

    printf("%f \n \r", volts);
    bcm2835_spi6_end();
    bcm2835_close();
    return (EXIT_SUCCESS);
}
 

Page 370

 
#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
int main(int argc, char **argv)
{
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}

Chapter 21

Page  372

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>

typedef struct{
    uint32_t status;
    uint32_t ctrl;
}GPIOregs;

#define GPIO ((GPIOregs*)GPIOBase)

typedef struct
{
    uint32_t Out;
    uint32_t OE;
    uint32_t In;
    uint32_t InSync;
} rioregs;

#define rio ((rioregs *)RIOBase)
#define rioXOR ((rioregs *)(RIOBase + 0x1000 / 4))
#define rioSET ((rioregs *)(RIOBase + 0x2000 / 4))
#define rioCLR ((rioregs *)(RIOBase + 0x3000 / 4))


int main(int argc, char **argv)
{
    int memfd = open("/dev/mem", O_RDWR | O_SYNC);
    uint32_t *map = (uint32_t *)mmap(
        NULL,
        64 * 1024 * 1024,
        (PROT_READ | PROT_WRITE),
        MAP_SHARED,
        memfd,
        0x1f00000000
    );
    if (map == MAP_FAILED)
    {
        printf("mmap failed: %s\n", strerror(errno));
        return (-1);
    };
    close(memfd);

    uint32_t *PERIBase = map;
    uint32_t *GPIOBase = PERIBase + 0xD0000 / 4;
    uint32_t *RIOBase = PERIBase + 0xe0000 / 4;
    uint32_t *PADBase = PERIBase + 0xf0000 / 4;
    uint32_t *pad = PADBase + 1;  
   
    uint32_t pin = 2;
    uint32_t fn = 5;

    GPIO[pin].ctrl=fn;
    pad[pin] = 0x10;
    rioSET->OE = 0x01<<pin;
    rioSET->Out = 0x01<<pin;
   
    for (;;)
    {
        rioXOR->Out = 0x04;
    }
    return (EXIT_SUCCESS);
}
 

Page  378

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>

typedef struct
{
    uint32_t status;
    uint32_t ctrl;
} GPIOregs;

#define GPIO ((GPIOregs *)GPIOBase)

typedef struct{
    uint32_t Ctrl;
    uint32_t Range;
    uint32_t Phase;
    uint32_t Duty;
} PWMregs;

#define PWM ((PWMregs *) (PWMBase+0x14/4))

typedef struct
{
    uint32_t Out;
    uint32_t OE;
    uint32_t In;
    uint32_t InSync;
} rioregs;

#define rio ((rioregs *)RIOBase)
#define rioXOR ((rioregs *)(RIOBase + 0x1000 / 4))
#define rioSET ((rioregs *)(RIOBase + 0x2000 / 4))
#define rioCLR ((rioregs *)(RIOBase + 0x3000 / 4))

uint32_t *PERIBase;
uint32_t *GPIOBase;
uint32_t *RIOBase;
uint32_t *PADBase;
uint32_t *pad;
uint32_t *PWMBase;


int rp1_Init()
{
    int memfd = open("/dev/mem", O_RDWR | O_SYNC);
    uint32_t *map = (uint32_t *)mmap(
        NULL,
        64 * 1024 * 1024,
        (PROT_READ | PROT_WRITE),
        MAP_SHARED,
        memfd,
        0x1f00000000);
    if (map == MAP_FAILED)
    {

        return (-1);
    };
    close(memfd);
    PERIBase = map;
    GPIOBase = PERIBase + 0xD0000 / 4;
    RIOBase = PERIBase + 0xe0000 / 4;
    PADBase = PERIBase + 0xf0000 / 4;
    PWMBase = PERIBase + 0x98000 / 4;
    pad = PADBase + 1;
    return 0;
};


int main(int argc, char **argv)
{
    if (rp1_Init())
        return (1);
    GPIO[12].ctrl = 0x0;
    pad[12] = 0x10;
    PWM[0].Ctrl=0x1;
    PWM[0].Range=0xFFFFF;
    PWM[0].Duty=0x8FFFF;
    PWM[0].Phase=0x0;
    *PWMBase=0x80000001;
    return (EXIT_SUCCESS);
}

Chapter 22

Page  395

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <linux/sched.h>
#include <pthread.h>
#include <stdint.h>

struct sched_attr
{
    uint32_t size;
    uint32_t sched_policy;
    uint64_t sched_flags;
    int32_t sched_nice;
    uint32_t sched_priority;
    uint64_t sched_runtime;
    uint64_t sched_deadline;
    uint64_t sched_period;
};

int sched_setattr(pid_t pid, const struct sched_attr *attr,
                  unsigned int flags)
{
    return syscall(__NR_sched_setattr, pid, attr, flags);
}

void *threadA(void *p)
{
    struct sched_attr attr = {
        .size = sizeof(attr),
        .sched_policy = SCHED_DEADLINE,
        .sched_runtime = 10 * 1000 * 1000,
        .sched_period = 2 * 1000 * 1000 * 1000,
        .sched_deadline = 11 * 1000 * 1000};
    sched_setattr(0, &attr, 0);
    for (;;)
    {
        printf("sensor\n");
        fflush(0);
        sched_yield();
    };
}

int main(int argc, char **argv)
{
    pthread_t pthreadA;
    pthread_create(&pthreadA, NULL, threadA, NULL);
    pthread_exit(0);
    return (EXIT_SUCCESS);
}
 

Page 399

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>
#include <sched.h>
#include <unistd.h>

volatile int j;
volatile int i;

void *threadA(void *p)
{
    for (i = 0;; i++)
    {
    };
}

void *threadB(void *p)
{
    for (j = 0;; j++)
    {
    };
}

int main(int argc, char **argv)
{
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(1, &cpuset);

    pthread_t pthreadA;
    pthread_create(&pthreadA, NULL, threadA, NULL);
    pthread_setaffinity_np(pthreadA, sizeof(cpu_set_t), &cpuset);

    CPU_ZERO(&cpuset);
    CPU_SET(2, &cpuset);
    pthread_t pthreadB;
    pthread_create(&pthreadB, NULL, threadB, NULL);
    pthread_setaffinity_np(pthreadB, sizeof(cpu_set_t), &cpuset);

    sleep(5);

    printf("%d %d", i, j);
    return (EXIT_SUCCESS);
}
 

 Page 402

 
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <unistd.h>
#include <bcm2835.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(3, &cpuset);
    int res = sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpuset);

    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_BPLUS_GPIO_J8_07, BCM2835_GPIO_FSEL_OUTP);
    while (1)
    {
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, HIGH);
        bcm2835_gpio_write(RPI_BPLUS_GPIO_J8_07, LOW);
    }
    bcm2835_close();
    return 0;
}

Appendix I

 

Page 406

#include <stdio.h>
#include <string.h>
 int main(int argc, char** argv) {
    int gpio = 4;
    FILE* fd = fopen("/sys/class/gpio/export", "w");
    fprintf(fd, "%d", gpio);
    fclose(fd);
    return 0;
}
 

Page 407


#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    int gpio = 4;
    char buf[100];

    FILE *fd = fopen("/sys/class/gpio/export", "w");
    fprintf(fd, "%d", gpio);
    fclose(fd);

    sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio);
    fd = fopen(buf, "w");
    fprintf(fd, "out");
    fclose(fd);

    sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
    fd = fopen(buf, "w");

    for (;;)
    {
        fd = fopen(buf, "w");
        fprintf(fd, "1");
        fclose(fd);
        fd = fopen(buf, "w");
        fprintf(fd, "0");
        fclose(fd);
    }
    return 0;
}

Appendix II

All files have to be stored in the .vscode folder

settings,json (typical) 

{
    "sshUser": "root",
    "sshEndpoint": "192.168.11.151",
    "remoteDirectory": "/home/pi/Documents/${workspaceFolderBasename}",
    "std": "c99",
    "libs":"-lbcm2835",
    "header":"/usr/local/include/bcm2835.h"
}
 

launch.json 

{
    "configurations": [
     
        {
            "name": "Remote C Debug",
            "type": "cppdbg",
            "request": "launch",
            "program": "${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${config:remoteDirectory}/${relativeFileDirname}",
            "environment": [],
            "externalConsole": false,
            "pipeTransport": {
                "debuggerPath": "/usr/bin/gdb",
                "pipeProgram": "C:/Windows/System32/OpenSSH/ssh",
                "pipeArgs": [
                    "${config:sshUser}@${config:sshEndpoint}"
                ],
                "pipeCwd": "${workspaceFolder}"
            },
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "sourceFileMap": {
                "${config:remoteDirectory}/${relativeFileDirname}": "${fileDirname}"
            },
            "preLaunchTask": "CopyBuildRemote",
        }
    ]
}
 

c_cpp_properties.json for Mingw

 
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/MinGW/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard":"c99",
            "intelliSenseMode":"gcc-arm" 
                }
    ],
    "version": 4
}
 
 

tasks.json

 
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "copyToRemote",
            "type": "shell",
            "command": "scp -r ${fileDirname} ${config:sshUser}@${config:sshEndpoint}:${config:remoteDirectory}/",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": false,
                "clear": true
            }
        },
        {
            "label": "copyHeader",
            "type": "shell",
            "command": "mkdir ${workspaceFolder}/headers/ ;scp -r  ${config:sshUser}@${config:sshEndpoint}:${config:header} ${workspaceFolder}/headers/ ",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": false,
                "clear": true
            }
        },
        {
            "label": "buildRemote",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} 'gcc  -g -std=${config:std} ${config:remoteDirectory}/${relativeFileDirname}/${fileBasename} ${config:libs}  -o${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}.exe'",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": false,
                "clear": false
            }
        },
        {
            "label": "runRemote",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} '${config:remoteDirectory}/${relativeFileDirname}/${fileBasenameNoExtension}'",
            "problemMatcher": [
                "$gcc"
            ],
            "presentation": {
                "showReuseMessage": true,
                "clear": false
            }
        },
        {
            "label": "CopyBuildRunRemote",
            "dependsOrder": "sequence",
            "dependsOn": [
                "copyToRemote",
                "buildRemote",
                "runRemote"
            ],
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "label": "CopyBuildRemote",
            "dependsOrder": "sequence",
            "dependsOn": [
                "copyToRemote",
                "buildRemote",
            ],
            "problemMatcher": [],
        },
        {
            "label": "StopREmoteC",
            "type": "shell",
            "command": "ssh ${config:sshUser}@${config:sshEndpoint} ;'pkill ${fileBasenameNoExtension}'",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": true,
            }
        },
        {
            "label": "copyARMheaders",
            "type": "shell",
            "command": "mkdir ${workspaceFolder}/include/;scp -r  ${config:sshUser}@${config:sshEndpoint}:/usr/include ${workspaceFolder}/include/ ",
            "problemMatcher": [],
            "presentation": {
                "showReuseMessage": true,
                "clear": true
            }
        },
    ],
}
"presentation": {
"showReuseMessage": true,
}
},
{
"label": "copyARMheaders",
"type": "shell",
"command": "mkdir ${workspaceFolder}/include/;scp -r  ${config:sshUser}@${config:sshEndpoint}:/usr/include ${workspaceFolder}/include/ ",
"problemMatcher": [],
"presentation": {
"showReuseMessage": true,
"clear": true
}
},
],
}
 
 
 
 

 

Programming The ESP32 In C
Using The Espressif IDF

ESP32Cebook180

 

 We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into a VS Code project.  

The only downside is that you have to create a project to paste the code into.

To do this follow the instruction in the book.

All of the programs below were copy and pasted from working programs in the IDE. They have been formatted using the built in formatter and hence are not identical in layout to the programs in the book. This is to make copy and pasting them easier. The programs in the book are formatted to be easy to read on the page. Some of the programs are presented complete even though they were presented in the book as fragments. 

If anything you consider important is missing or if you have any requests or comments  contact:

This email address is being protected from spambots. You need JavaScript enabled to view it. 


Page 50

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void app_main(void)
{
     gpio_reset_pin(2);
     gpio_set_direction(2, GPIO_MODE_OUTPUT);
    while (1) {
        gpio_set_level(2, 0);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        gpio_set_level(2, 1);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}
 

Page 53

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void gpio_toggle(gpio_num_t gpio_num)
{
    gpio_set_level(gpio_num, !gpio_get_level(gpio_num));
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);
    while (1)
    {
        gpio_toggle(2);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

 


Page 56

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    while (1)
    {
        gpio_set_level(2, 0);
        gpio_set_level(2, 1);
    }
}
 

Page 57

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void app_main(void)
{
     gpio_reset_pin(2);
     gpio_set_direction(2, GPIO_MODE_OUTPUT);
     volatile int waste = 0;
    while (1) {
        gpio_set_level(2, 0);
        waste++;
        gpio_set_level(2, 1);
    }
}
 

Page 59

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    while (1)
    {
        gpio_set_level(2, 0);
        delay_us(1);
        gpio_set_level(2, 1);
        delay_us(1);
    }
}
 
 

Page 59

#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void app_main(void)
{
     gpio_reset_pin(2);
     gpio_set_direction(2, GPIO_MODE_OUTPUT);
     volatile int i=0;
     int n=1;
     while (1) {
        gpio_set_level(2, 0);
        for(i=0;i<n;i++){}
        gpio_set_level(2, 1);
        for(i=0;i<n;i++){}
    }
}
 

Page 62

 
#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include <sys/time.h>

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec + offset;
}

void delay_until(int64_t t)
{
    static struct timeval tv_now;
    do
    {
        gettimeofday(&tv_now, NULL);
    } while (t > (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec);
}

void app_main(void)
{
    int pin = 2;
    gpio_reset_pin(pin);
    gpio_set_direction(pin, GPIO_MODE_OUTPUT);
    volatile int i = 0;
    int n = 100;
    int64_t t = 0;
    int64_t width = 1000;

    while (1)
    {
        t = tick_us(width);
        gpio_set_level(pin, 1);
        for (i = 0; i < n; i++)
        {
        }
        delay_until(t);

        t = tick_us(width);
        gpio_set_level(pin, 0);
        for (i = 0; i < n; i++)
        {
        }
        delay_until(t);
    }
}
 

Page 64

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"

void app_main(void)
{
   
     gpio_reset_pin(2);
     gpio_set_direction(2, GPIO_MODE_OUTPUT);
   
     gpio_reset_pin(4);
     gpio_set_direction(4, GPIO_MODE_OUTPUT);

     while (1) {          
      gpio_set_level(2, 1);
      gpio_set_level(4, 0);
      gpio_set_level(2, 0);
      gpio_set_level(4, 1);
    }
}

Page 66

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"

#include "soc/gpio_reg.h"

void gpio_set(int32_t value, int32_t mask)
{
    int32_t *OutAdd = (int32_t *)GPIO_OUT_REG;
    *OutAdd = (*OutAdd & ~mask) | (value & mask);
}

void app_main(void)
{

    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_OUTPUT);

    int32_t mask = 1 << 2 | 1 << 4;
    int32_t value1 = 0 << 2 | 1 << 4;
    int32_t value2 = 1 << 2 | 0 << 4;

    while (1)
    {
        gpio_set(value1, mask);
        gpio_set(value2, mask);
    }
}
 

Page 92

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void delay_ms(int t)
{
    vTaskDelay(t / portTICK_PERIOD_MS);
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_pullup_en(4);
    while (1)
    {
        if (gpio_get_level(4))
        {
            gpio_set_level(2, 1);
        }
        else
        {
            gpio_set_level(2, 0);
            delay_ms(500);
        }
    }
}
 

Page 94

 
#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void delay_ms(int t)
{
    vTaskDelay(t / portTICK_PERIOD_MS);
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_pulldown_en(4);
    while (1)
    {
        while (gpio_get_level(4) == 0)
        {
        };
        delay_ms(10);
        while (gpio_get_level(4) == 1)
        {
        };
        gpio_set_level(2, 1);
        delay_ms(1000);
        gpio_set_level(2, 0);
    }
}

Page 95

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>

void delay_ms(int t)
{
    vTaskDelay(t / portTICK_PERIOD_MS);
}

int64_t tick_ms(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000L +
           (int64_t)tv_now.tv_usec / 1000L + offset;
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_pulldown_en(4);

    gpio_set_level(2, 0);

    uint64_t t;

    while (1)
    {
        while (gpio_get_level(4) == 0)
        {
        };
        t = tick_ms(2000);
        delay_ms(10);

        while (gpio_get_level(4) == 1)
        {
        }

        if (tick_ms(0) < t)
        {
            gpio_set_level(2, 1);
            delay_ms(1000);
            gpio_set_level(2, 0);
        }
        else
        {
            for (int i = 0; i < 10; i++)
            {
                gpio_set_level(2, 1);
                delay_ms(1000);
                gpio_set_level(2, 0);
                delay_ms(1000);
            }
        }
    }
}
 

Page  97

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>



int64_t tick_us(int64_t offset) {
  static struct timeval tv_now;
  gettimeofday(&tv_now, NULL);
  return (int64_t)tv_now.tv_sec * 1000000L +
                           (int64_t)tv_now.tv_usec + offset;
}

void delay_ms(int t) {
  vTaskDelay(t / portTICK_PERIOD_MS);
}

void app_main(void)
{
  gpio_reset_pin(4);
  gpio_set_direction(4, GPIO_MODE_INPUT);

  uint64_t t;

  while (1) {
    while (gpio_get_level(4) == 1) {};
    while (gpio_get_level(4) == 0) {};
    t = tick_us(0);
    while (gpio_get_level(4) == 1) {};
    t = tick_us(0) - t;
    printf("%llu\n", t);
    fflush(stdout);
    delay_ms(1000);
  }
}
 
 

Page 98

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L +
           (int64_t)tv_now.tv_usec + offset;
}

void delay_ms(int t)
{
    vTaskDelay(t / portTICK_PERIOD_MS);
}

void app_main(void)
{

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);

    uint64_t t;

    while (1)
    {
        while (gpio_get_level(4) == 1)
        {
        };
        while (gpio_get_level(4) == 0)
        {
        };
        t = 0;
        while (gpio_get_level(4) == 1)
        {
            t++;
        };
        printf("%llu\n", t);
        fflush(stdout);
        delay_ms(1000);
    }

 

Page 101

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L +
           (int64_t)tv_now.tv_usec + offset;
}

void delay_until(int64_t t)
{
    static struct timeval tv_now;
    do
    {
        gettimeofday(&tv_now, NULL);
    } while (t > (int64_t)tv_now.tv_sec * 1000000L +
                     (int64_t)tv_now.tv_usec);
}

void app_main(void)
{

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_pulldown_en(4);

    uint64_t t;
    int s = 0;
    int i;
    int count = 0;
    while (true)
    {
        i = gpio_get_level(4);
        t = tick_us(100 * 1000);
        switch (s)
        {
        case 0: // button not pushed
            if (i)
            {
                s = 1;
                count++;
                printf("Button Push %d \n\r", count);
            }
            break;
        case 1: // Button pushed
            if (!i)
            {
                s = 0;
            }
            break;
        default:
            s = 0;
        }
        delay_until(t);
    }
}

 

Page 103

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec + offset;
}

void delay_until(int64_t t)
{
    static struct timeval tv_now;
    do
    {
        gettimeofday(&tv_now, NULL);
    } while (t > (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec);
}

void app_main(void)
{
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_pulldown_en(4);

    uint64_t t;
    uint64_t tpush, twait;
    int s = 0, i;
    while (true)
    {
        i = gpio_get_level(4);
        t = tick_us(0);
        switch (s)
        {
        case 0: // button not pushed
            if (i)
            {
                s = 1;
                tpush = t;
            }
            break;
        case 1: // Button pushed
            if (!i)
            {
                s = 0;
                if ((t - tpush) > 2000000)
                {
                    printf("Button held \n\r");
                }
                else
                {
                    printf("Button pushed \n\r");
                }
                fflush(stdout);
            }
            break;
        default:
            s = 0;
        }
        delay_until(t + 100 * 10000);
    }
}

 

Page 105

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec + offset;
}

void delay_until(int64_t t)
{
    static struct timeval tv_now;
    do
    {
        gettimeofday(&tv_now, NULL);
    } while (t > (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec);
}

void app_main(void)
{

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_pulldown_en(4);

    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_reset_pin(16);
    gpio_set_direction(16, GPIO_MODE_OUTPUT);
    gpio_reset_pin(17);
    gpio_set_direction(17, GPIO_MODE_OUTPUT);

    uint64_t t;
    int edge;
    int buttonNow;
    int s = 0;

    int buttonState = gpio_get_level(4);
    gpio_set_level(2, 0);
    gpio_set_level(16, 1);
    gpio_set_level(17, 0);

    while (true)
    {
        t = tick_us(0);
        buttonNow = gpio_get_level(4);
        edge = buttonState - buttonNow;
        buttonState = buttonNow;
        switch (s)
        {
        case 0:
            if (edge == 1)
            {
                s = 1;
                gpio_set_level(2, 0);
                gpio_set_level(16, 1);
                gpio_set_level(17, 0);
            }
            break;
        case 1:
            if (edge == 1)
            {
                s = 2;
                gpio_set_level(2, 0);
                gpio_set_level(16, 0);
                gpio_set_level(17, 1);
            }
            break;
        case 2:
            if (edge == 1)
            {
                s = 0;
                gpio_set_level(2, 1);
                gpio_set_level(16, 0);
                gpio_set_level(17, 0);
            }
            break;

        default:
            s = 0;
        }
        delay_until(t + 100 * 10000);
    }
}

Page 113

 

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void ISR(void *arg)
{
    gpio_intr_disable(4);
    gpio_set_level(2, !gpio_get_level(2));
    gpio_intr_enable(4);
}

void app_main(void)
{
    gpio_isr_register(ISR, NULL, ESP_INTR_FLAG_LOWMED, NULL);
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_intr_disable(4);
    gpio_set_intr_type(4, GPIO_INTR_ANYEDGE);

    gpio_intr_enable(4);
}

 

Page 114

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void ISR(void *arg)
{
    gpio_intr_disable(16);
    gpio_intr_disable(4);
    gpio_set_level(2, !gpio_get_level(2));
    gpio_intr_enable(16);
    gpio_intr_enable(4);
}

void app_main(void)
{
    gpio_isr_register(ISR, NULL, ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_EDGE, NULL);
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_intr_disable(4);
    gpio_set_intr_type(4, GPIO_INTR_ANYEDGE);

    gpio_reset_pin(16);
    gpio_set_direction(16, GPIO_MODE_INPUT);
    gpio_intr_disable(16);
    gpio_set_intr_type(16, GPIO_INTR_ANYEDGE);

    gpio_intr_enable(4);
    gpio_intr_enable(16);
}

 

Page 115

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

#include "soc/gpio_reg.h"

int32_t getIRQStatus()
{
    return *(int *)GPIO_STATUS_REG;
}

void ISR(void *arg)
{
    int32_t intStatus = getIRQStatus();
    gpio_intr_disable(16);
    gpio_intr_disable(4);
    int32_t mask = 1 << 16;
    if (intStatus & mask)
        gpio_set_level(2, !gpio_get_level(2));
    gpio_intr_enable(16);
    gpio_intr_enable(4);
}

void app_main(void)
{
    gpio_isr_register(ISR, NULL, ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_EDGE, NULL);
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_intr_disable(4);
    gpio_set_intr_type(4, GPIO_INTR_ANYEDGE);

    gpio_reset_pin(16);
    gpio_set_direction(16, GPIO_MODE_INPUT);
    gpio_intr_disable(16);
    gpio_set_intr_type(16, GPIO_INTR_ANYEDGE);

    gpio_intr_enable(4);
    gpio_intr_enable(16);
}

 

 Page 118

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L +
           (int64_t)tv_now.tv_usec + offset;
}

void delay_ms(int t) {
  vTaskDelay(t / portTICK_PERIOD_MS);
}

int64_t t = 0;
int state = 0;

void ISR(void *arg)
{
    gpio_intr_disable(4);
    t = tick_us(-t);
    state++;
    gpio_set_level(2, !gpio_get_level(2));
    gpio_intr_enable(4);
}

void app_main(void)
{
    gpio_isr_register(ISR, NULL, ESP_INTR_FLAG_LOWMED, NULL);

    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_intr_disable(4);

    gpio_set_intr_type(4, GPIO_INTR_ANYEDGE);
    gpio_intr_enable(4);

    while (true)
    {
        while (state != 2)
        {
        };
        gpio_intr_disable(4);
        printf("time = %lld, %d\n", t, state);
        fflush(stdout);
        state = 0;
        t = 0;
        delay_ms(1000);
        gpio_intr_enable(4);
    }
}

 

Page 120

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

char data[3];

void ISR(void *arg)
{
    gpio_intr_disable(4);
    for (int i = 0; i < 3; i++)
        data[i] = 0;
    gpio_intr_enable(4);
}

void app_main(void)
{
    gpio_isr_register(ISR, NULL, ESP_INTR_FLAG_LOWMED, NULL);

    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_intr_disable(4);

    gpio_set_intr_type(4, GPIO_INTR_ANYEDGE);
    gpio_intr_enable(4);
    while (true)
    {
        for (int i = 0; i < 3; i++)
            data[i] = 0xFF;
        if (data[0] != data[1] || data[1] != data[2] || data[2] != data[0])
            break;
    }
    printf("%d %d %d\n", data[0], data[1], data[2]);
}

 

 Page 122

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include <sys/time.h>

int64_t tick_us(int64_t offset)
{
    static struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    return (int64_t)tv_now.tv_sec * 1000000L +
           (int64_t)tv_now.tv_usec + offset;
}

int64_t t = 0;
static QueueHandle_t gpio_evt_queue = NULL;

void ISR(void *arg)
{
    gpio_intr_disable(4);
    t = tick_us(0);
    xQueueSendToBackFromISR(gpio_evt_queue, &t, NULL);
    gpio_intr_enable(4);
}

void app_main(void)
{
    gpio_evt_queue = xQueueCreate(10, sizeof(int32_t));

    gpio_isr_register(ISR, NULL, ESP_INTR_FLAG_LOWMED, NULL);
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_INPUT);
    gpio_intr_disable(4);
    gpio_set_intr_type(4, GPIO_INTR_ANYEDGE);
    gpio_intr_enable(4);

    int64_t time;
    while (true)
    {
        if (xQueueReceive(gpio_evt_queue, &time, portMAX_DELAY))
        {
            printf("time = %lld\n", time);
            fflush(stdout);
        }
    }
}

 

 Page 125

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "driver/gptimer.h"
void app_main(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1221,
    };
    gptimer_handle_t gptimer = NULL;
    gptimer_new_timer(&timer_config, &gptimer);
    gptimer_enable(gptimer);
    gptimer_start(gptimer);
    uint64_t count = 0;
    do
    {
        gptimer_get_raw_count(gptimer, &count);
    } while (count < 1000);
    printf("Time up %lld\n", count);
    gptimer_stop(gptimer);
    gptimer_disable(gptimer);
    gptimer_del_timer(gptimer);
}

 

Page 126

 

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "driver/gptimer.h"

gptimer_handle_t tick_us_start(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_handle_t gptimer_us = NULL;
    gptimer_new_timer(&timer_config, &gptimer_us);
    gptimer_enable(gptimer_us);
    gptimer_start(gptimer_us);
    return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset)
{
    uint64_t count;
    gptimer_get_raw_count(gptimer_us, &count);
    return count + offset;
}

void app_main(void)
{
    gptimer_handle_t gptimer_us = tick_us_start();
    int64_t tick = tick_us(gptimer_us, 1000000);
    while (tick_us(gptimer_us, 0) < tick)
    {
    };
    printf("time up %lld\n", tick_us(gptimer_us, 0));
}

 

Page 127

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

#include "driver/gptimer.h"

bool ISR(gptimer_handle_t gptimer,
         const gptimer_alarm_event_data_t *edata,
         void *user_data)
{
    gpio_set_level(2, !gpio_get_level(2));
    return true;
}

void app_main(void)
{

    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);

    gptimer_handle_t gptimer = NULL;
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1221,
    };

    gptimer_new_timer(&timer_config, &gptimer);

    gptimer_alarm_config_t alarm_config = {
        .flags.auto_reload_on_alarm = true,
        .alarm_count = 1000,
        .reload_count = 0};

    gptimer_set_alarm_action(gptimer, &alarm_config);

    gptimer_event_callbacks_t cbs = {
        .on_alarm = ISR,
    };
    gptimer_register_event_callbacks(gptimer, &cbs, NULL);

    gptimer_enable(gptimer);
    gptimer_start(gptimer);

    while (true)
    {
    };
}

 


Page 140

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "driver/ledc.h"

void app_main(void)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .timer_num = 0,
        .duty_resolution = LEDC_TIMER_13_BIT,
        .freq_hz = 4000,
        .clk_cfg = LEDC_APB_CLK};

    ledc_timer_config(&ledc_timer);

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .channel = 0,
        .timer_sel = 0,
        .intr_type = LEDC_INTR_DISABLE,
        .gpio_num = 2,
        .duty = 4096,
        .hpoint = 0};

    ledc_channel_config(&ledc_channel);
}

 

Page 143

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include "driver/ledc.h"
#include <unistd.h>
void delay_us(int t)
{
    usleep(t);
}
void PWMconfigLow(int gpio, int chan, int timer, int res,
                  int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

void changeDutyLow(int chan, int res, float duty)
{
    ledc_set_duty(LEDC_LOW_SPEED_MODE, chan,
                  ((float)(2 << (res - 1))) * duty);
    ledc_update_duty(LEDC_LOW_SPEED_MODE, chan);
}

void app_main(void)
{
    PWMconfigLow(2, 0, 3, 13, 4000, 0.25);
    while (true)
    {
        delay_us(1000);
        changeDutyLow(0, 13, 0.5);
        delay_us(1000);
        changeDutyLow(0, 13, 0.25);
    }
}

 

Page 146

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include <sys/time.h>
#include "driver/ledc.h"
#include "math.h"
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

uint8_t wave[256];
void app_main(void)
{
    for (int i = 0; i < 256; i++)
    {
        wave[i] = (uint8_t)((128.0 +
                             sinf((float)i * 2.0 * 3.14159 / 255.0) * 128.0));
    }
    int f = 60000;
    int t = (1 * 1000 * 1000) / f;
    PWMconfigLow(2, 0, 0, 8, f, 0.25);
    fflush(stdout);
    while (true)
    {
        for (int i = 0; i < 256; i++)
        {
            ledc_set_duty(LEDC_LOW_SPEED_MODE, 0, wave[i]);
            ledc_update_duty(LEDC_LOW_SPEED_MODE, 0);
            delay_us(t);
        }
    }
}

 

 Page 148

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include <sys/time.h>
#include "driver/ledc.h"

void delay_ms(int t)
{
    vTaskDelay(t / portTICK_PERIOD_MS);
}

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

void app_main(void)
{
    while (true)
    {
        PWMconfigLow(2, 0, 0, 8, 2000, 0.5);
        for (int d = 0; d <= 256; d++)
        {
            ledc_set_duty(LEDC_LOW_SPEED_MODE, 0, d);
            ledc_update_duty(LEDC_LOW_SPEED_MODE, 0);
            delay_ms(10);
        }
    }
}

 

Page 150 complete program to do cubic dimming

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include <sys/time.h>
#include "driver/ledc.h"

void delay_ms(int t)
{
    vTaskDelay(t / portTICK_PERIOD_MS);
}

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

void app_main(void)
{
    while (true)
    {
        PWMconfigLow(2, 0, 0, 8, 2000, 0.5);
        for (int d = 0; d <= 256; d++)
        {
            ledc_set_duty(LEDC_LOW_SPEED_MODE, 0, d * d * d / 255 / 255);
            ledc_update_duty(LEDC_LOW_SPEED_MODE, 0);
            delay_ms(10);
        }
    }
}

 

 Page 154 

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/ledc.h"

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;
    ledc_timer.deconfigure = false;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

void app_main(void)
{

    PWMconfigLow(2, 0, 0, 8, 2550, 0);
    ledc_fade_func_install(LEDC_INTR_DISABLE);
    while (true)
    {
        ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE, 0, 255, 1000);
        ledc_fade_start(LEDC_LOW_SPEED_MODE, 0, LEDC_FADE_WAIT_DONE);
        ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE, 0, 0, 1000);
        ledc_fade_start(LEDC_LOW_SPEED_MODE, 0, LEDC_FADE_WAIT_DONE);
    }
}

 

Page 155 complete program from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/ledc.h"

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;
    ledc_timer.deconfigure = false;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}
void app_main(void)
{

    PWMconfigLow(2, 0, 0, 8, 2550, 0);
    ledc_fade_func_install(LEDC_INTR_DISABLE);
    while (true)
    {
        ledc_set_fade_with_step(LEDC_LOW_SPEED_MODE, 0, 255, 1, 10);
        ledc_fade_start(LEDC_LOW_SPEED_MODE, 0, LEDC_FADE_WAIT_DONE);
        ledc_set_fade_with_step(LEDC_LOW_SPEED_MODE, 0, 0, 1, 10);
        ledc_fade_start(LEDC_LOW_SPEED_MODE, 0, LEDC_FADE_WAIT_DONE);
    }
}

 

 Page 156

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/ledc.h"

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;
    ledc_timer.deconfigure = false;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

void changeDutyPhaseLow(int chan, int res, float duty, float phase)
{
    ledc_set_duty_with_hpoint(LEDC_LOW_SPEED_MODE, chan,
                              ((float)(2 << (res - 1))) * duty,
                              ((float)(2 << (res - 1))) * phase);
    ledc_update_duty(LEDC_LOW_SPEED_MODE, chan);
}

void app_main(void)
{
    PWMconfigLow(2, 0, 0, 8, 2550, 0.5);
    PWMconfigLow(4, 1, 0, 8, 2550, 0.5);
    changeDutyPhaseLow(1, 8, 0.5, 0.25);
}

 


 

 Page 165

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"

void app_main(void)
{
  mcpwm_timer_handle_t timer = NULL;
  mcpwm_timer_config_t timer_config = {
      .group_id = 0,
      .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT,
      .resolution_hz = 1000000,
      .period_ticks = 20000,
      .count_mode = MCPWM_TIMER_COUNT_MODE_UP,
  };

  mcpwm_new_timer(&timer_config, &timer);

  mcpwm_oper_handle_t oper = NULL;
  mcpwm_operator_config_t operator_config = {
      .group_id = 0,
  };
  mcpwm_new_operator(&operator_config, &oper);

  mcpwm_operator_connect_timer(oper, timer);

  mcpwm_gen_handle_t generator = NULL;
  mcpwm_generator_config_t generator_config = {
      .gen_gpio_num = 2,
  };

  mcpwm_new_generator(oper, &generator_config, &generator);

  mcpwm_generator_set_action_on_timer_event(generator,
        MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                MCPWM_TIMER_EVENT_FULL, MCPWM_GEN_ACTION_TOGGLE));

  mcpwm_timer_enable(timer);
  mcpwm_timer_start_stop(timer, MCPWM_TIMER_START_NO_STOP);
}

 

Page 167 complete program from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"

void app_main(void)
{
  mcpwm_timer_handle_t timer = NULL;
  mcpwm_timer_config_t timer_config = {
      .group_id = 0,
      .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT,
      .resolution_hz = 1000000,
      .period_ticks = 20000,
      .count_mode = MCPWM_TIMER_COUNT_MODE_UP,
  };

  mcpwm_new_timer(&timer_config, &timer);

  mcpwm_oper_handle_t oper = NULL;
  mcpwm_operator_config_t operator_config = {
      .group_id = 0,
  };
  mcpwm_new_operator(&operator_config, &oper);

  mcpwm_operator_connect_timer(oper, timer);

  mcpwm_gen_handle_t generator = NULL;
  mcpwm_generator_config_t generator_config = {
      .gen_gpio_num = 2,
  };

  mcpwm_new_generator(oper, &generator_config, &generator);
 
  mcpwm_cmpr_handle_t comparator = NULL;
  mcpwm_comparator_config_t comparator_config = {
       .flags.update_cmp_on_tez = true,
   };
  mcpwm_new_comparator(oper, &comparator_config, &comparator);

  mcpwm_comparator_set_compare_value(comparator,10000);
  mcpwm_generator_set_action_on_timer_event(generator,
        MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
          MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generator,
          MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                       comparator, MCPWM_GEN_ACTION_LOW));
  mcpwm_timer_enable(timer);
  mcpwm_timer_start_stop(timer, MCPWM_TIMER_START_NO_STOP);
}

 

Page 169 complete program from fragment

 

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"

void app_main(void)
{
  mcpwm_timer_handle_t timer = NULL;
  mcpwm_timer_config_t timer_config = {
      .group_id = 0,
      .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT,
      .resolution_hz = 1000000,
      .period_ticks = 20000,
      .count_mode = MCPWM_TIMER_COUNT_MODE_UP,
  };

  mcpwm_new_timer(&timer_config, &timer);

  mcpwm_oper_handle_t oper = NULL;
  mcpwm_operator_config_t operator_config = {
      .group_id = 0,
  };
  mcpwm_new_operator(&operator_config, &oper);

  mcpwm_operator_connect_timer(oper, timer);

  mcpwm_generator_config_t generator_config = {
      .gen_gpio_num = 2,
  };
  mcpwm_gen_handle_t generatorA = NULL;
  mcpwm_new_generator(oper, &generator_config, &generatorA);
  generator_config.gen_gpio_num = 4;
  mcpwm_gen_handle_t generatorB = NULL;
  mcpwm_new_generator(oper, &generator_config, &generatorB);
 
  mcpwm_comparator_config_t comparator_config = {
       .flags.update_cmp_on_tez = true,
   };
  mcpwm_cmpr_handle_t comparatorA = NULL;
  mcpwm_new_comparator(oper, &comparator_config, &comparatorA);
  mcpwm_cmpr_handle_t comparatorB = NULL;
  mcpwm_new_comparator(oper, &comparator_config, &comparatorB);
  mcpwm_comparator_set_compare_value(comparatorA, 10000);
  mcpwm_comparator_set_compare_value(comparatorB, 5000);
 
  mcpwm_generator_set_action_on_timer_event(generatorA,
          MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                 MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generatorA,
          MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                              comparatorA, MCPWM_GEN_ACTION_LOW));

  mcpwm_generator_set_action_on_timer_event(generatorB,
          MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                  MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generatorB,
           MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                              comparatorB, MCPWM_GEN_ACTION_LOW));

  mcpwm_timer_enable(timer);
  mcpwm_timer_start_stop(timer, MCPWM_TIMER_START_NO_STOP);
}

 

Page 171 complete program from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"

void app_main(void)
{
  mcpwm_timer_handle_t timer = NULL;
  mcpwm_timer_config_t timer_config = {
      .group_id = 0,
      .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT,
      .resolution_hz = 1000000,
      .period_ticks = 20000,
      .count_mode = MCPWM_TIMER_COUNT_MODE_UP_DOWN,
  };

  mcpwm_new_timer(&timer_config, &timer);

  mcpwm_oper_handle_t oper = NULL;
  mcpwm_operator_config_t operator_config = {
      .group_id = 0,
  };
  mcpwm_new_operator(&operator_config, &oper);

  mcpwm_operator_connect_timer(oper, timer);

  mcpwm_generator_config_t generator_config = {
      .gen_gpio_num = 2,
  };
  mcpwm_gen_handle_t generatorA = NULL;
  mcpwm_new_generator(oper, &generator_config, &generatorA);
  generator_config.gen_gpio_num = 4;
  mcpwm_gen_handle_t generatorB = NULL;
  mcpwm_new_generator(oper, &generator_config, &generatorB);
 
  mcpwm_comparator_config_t comparator_config = {
       .flags.update_cmp_on_tez = true,
   };
  mcpwm_cmpr_handle_t comparatorA = NULL;
  mcpwm_new_comparator(oper, &comparator_config, &comparatorA);
  mcpwm_cmpr_handle_t comparatorB = NULL;
  mcpwm_new_comparator(oper, &comparator_config, &comparatorB);
  mcpwm_comparator_set_compare_value(comparatorA, 10000);
  mcpwm_comparator_set_compare_value(comparatorB, 5000);
 
  mcpwm_comparator_set_compare_value(comparatorA, 5000);
  mcpwm_comparator_set_compare_value(comparatorB, 9000);

  mcpwm_generator_set_action_on_compare_event(generatorA,
   MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                       comparatorA, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generatorA,
   MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN,
                       comparatorA, MCPWM_GEN_ACTION_LOW));

  mcpwm_generator_set_action_on_compare_event(generatorB,
   MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,  
                       comparatorB, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generatorB,
   MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_DOWN,
                          comparatorB, MCPWM_GEN_ACTION_LOW));

  mcpwm_timer_enable(timer);
  mcpwm_timer_start_stop(timer, MCPWM_TIMER_START_NO_STOP);
}
 

Page 174 MCPWM.h

#include "driver/mcpwm_prelude.h"

mcpwm_timer_handle_t makeTimer(uint32_t res, uint32_t periodTicks)
{
    mcpwm_timer_handle_t timer = NULL;
    mcpwm_timer_config_t timer_config = {
        .group_id = 0,
        .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT,
        .resolution_hz = res,
        .period_ticks = periodTicks,
        .count_mode = MCPWM_TIMER_COUNT_MODE_UP,
    };
    mcpwm_new_timer(&timer_config, &timer);
    return timer;
}

mcpwm_oper_handle_t makeOper()
{
    mcpwm_oper_handle_t oper = NULL;
    mcpwm_operator_config_t operator_config = {
        .group_id = 0,
    };
    mcpwm_new_operator(&operator_config, &oper);
    return oper;
}

mcpwm_gen_handle_t makeGen(mcpwm_oper_handle_t oper, int gpio)
{
    mcpwm_generator_config_t generator_config = {
        .gen_gpio_num = gpio};
    mcpwm_gen_handle_t generator = NULL;
    mcpwm_new_generator(oper, &generator_config, &generator);
    return generator;
}

mcpwm_cmpr_handle_t makeComp(mcpwm_oper_handle_t oper)
{
    mcpwm_comparator_config_t comparator_config = {
        .flags.update_cmp_on_tez = true,
    };

    mcpwm_cmpr_handle_t comparator = NULL;
    mcpwm_new_comparator(oper, &comparator_config, &comparator);
    return comparator;
}

void setPhaseTep(mcpwm_timer_handle_t SourceTimer, mcpwm_timer_handle_t PhasedTimer, uint32_t phaseticks)
{
    mcpwm_timer_sync_src_config_t syncconfig = {
        .timer_event = MCPWM_TIMER_EVENT_EMPTY,
    };

    mcpwm_sync_handle_t sync = NULL;
    mcpwm_new_timer_sync_src(SourceTimer, &syncconfig, &sync);

    mcpwm_timer_sync_phase_config_t phase = {
        .count_value = phaseticks,
        .direction = MCPWM_TIMER_DIRECTION_UP,
        .sync_src = sync};
    mcpwm_timer_set_phase_on_sync(PhasedTimer, &phase);
}

 

Page  176 Uses previous header

 

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"
#include "MCPWM.h"

void app_main(void)
{
  mcpwm_timer_handle_t timer1 = makeTimer(1000000, 20000);
  mcpwm_timer_handle_t timer2 = makeTimer(1000000, 20000);

  mcpwm_oper_handle_t oper1 = makeOper();
  mcpwm_oper_handle_t oper2 = makeOper();

  mcpwm_operator_connect_timer(oper1, timer1);
  mcpwm_operator_connect_timer(oper2, timer2);

  mcpwm_gen_handle_t generator1 = makeGen(oper1, 2);
  mcpwm_gen_handle_t generator2 = makeGen(oper2, 4);


  mcpwm_cmpr_handle_t comparator1 = makeComp(oper1);
  mcpwm_cmpr_handle_t comparator2 = makeComp(oper2);

  mcpwm_comparator_set_compare_value(comparator1, 9000);
  mcpwm_comparator_set_compare_value(comparator2, 9000);

  setPhaseTep(timer1, timer2, 4000);

  mcpwm_generator_set_action_on_timer_event(generator1,
          MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                 MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generator1,
          MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                     comparator1, MCPWM_GEN_ACTION_LOW));

  mcpwm_generator_set_action_on_timer_event(generator2,
            MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                  MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(generator2,
          MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                     comparator2, MCPWM_GEN_ACTION_LOW));

  mcpwm_timer_enable(timer1);
  mcpwm_timer_start_stop(timer1, MCPWM_TIMER_START_NO_STOP);
  mcpwm_timer_enable(timer2);
  mcpwm_timer_start_stop(timer2, MCPWM_TIMER_START_NO_STOP);
}

 


Page 184 -186 uses MCPWM.h given earlier

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"
#include "MCPWM.h"


typedef struct{
  mcpwm_timer_handle_t timer;
  mcpwm_oper_handle_t oper;
  mcpwm_gen_handle_t generator1;
  mcpwm_cmpr_handle_t comparator1;
}PWM;

PWM makePWM(int gpio, uint32_t res, uint32_t ticksperiod,
                                               uint32_t duty) {
  PWM pwm;
  pwm.timer = makeTimer(res, ticksperiod);
  pwm.oper = makeOper();
  mcpwm_operator_connect_timer(pwm.oper, pwm.timer);
  pwm.generator1 = makeGen(pwm.oper, gpio);
  pwm.comparator1 = makeComp(pwm.oper);
  mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
  mcpwm_generator_set_action_on_timer_event(pwm.generator1,
     MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
           MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(pwm.generator1,
     MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                 pwm.comparator1, MCPWM_GEN_ACTION_LOW));
  mcpwm_timer_enable(pwm.timer);
  mcpwm_timer_start_stop(pwm.timer, MCPWM_TIMER_START_NO_STOP);
  return pwm;
}

typedef struct
{
  PWM pwm;
  uint32_t gpio;
  uint32_t duty;
  uint32_t freq;
  uint32_t resolution;
  float speed;
} Motor;

Motor makeUniMotor(int32_t gpio) {
  int32_t res = 1000000;
  int32_t freq = 500;
  Motor motor;
  motor.gpio = gpio;
  motor.pwm = makePWM(gpio, res, freq, 0);
  motor.freq = freq;
  motor.speed = 0;
  motor.duty = 0;
  return motor;
}

void setUniMotorSpeed(Motor motor, float speed) {
  motor.speed = speed;
  motor.duty = speed * (float)(motor.freq);
  mcpwm_comparator_set_compare_value(motor.pwm.comparator1,
                                                  motor.duty);
}

void app_main(void)
{
  Motor motor = makeUniMotor(2);
  setUniMotorSpeed(motor, 0.1);
}

 

Page 191-192 uses MCPWM.h given earlier

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"
#include "MCPWM.h"


typedef struct{
  mcpwm_timer_handle_t timer;
  mcpwm_oper_handle_t oper;
  mcpwm_gen_handle_t generator1;
  mcpwm_cmpr_handle_t comparator1;
}PWM;

PWM makePWM(int gpio, uint32_t res, uint32_t ticksperiod,
                                               uint32_t duty) {
  PWM pwm;
  pwm.timer = makeTimer(res, ticksperiod);
  pwm.oper = makeOper();
  mcpwm_operator_connect_timer(pwm.oper, pwm.timer);
  pwm.generator1 = makeGen(pwm.oper, gpio);
  pwm.comparator1 = makeComp(pwm.oper);
  mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
  mcpwm_generator_set_action_on_timer_event(pwm.generator1,
     MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
           MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(pwm.generator1,
     MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                 pwm.comparator1, MCPWM_GEN_ACTION_LOW));
  mcpwm_timer_enable(pwm.timer);
  mcpwm_timer_start_stop(pwm.timer, MCPWM_TIMER_START_NO_STOP);
  return pwm;
}

typedef struct
{
  PWM pwm;
  PWM pwm2;
  uint32_t gpio;
  uint32_t gpio2;
  uint32_t duty;
  uint32_t freq;
  uint32_t resolution;
  float speed;
  bool forward;
} Motor;

Motor makeBiMotor(int32_t gpio1,int32_t gpio2) {
  int32_t res = 1000000;
  int32_t freq = 500;
  Motor motor;
  motor.gpio = gpio1;
  motor.gpio2 = gpio2;
  motor.pwm = makePWM(gpio1, res, freq, 0);
  motor.pwm2 = makePWM(gpio2, res, freq, 0);
  motor.freq = freq;
  motor.speed = 0;
  motor.duty = 0;
  motor.forward=true;
  return motor;
}

void setBiMotorSpeedDirection(Motor motor, float speed,
                                           bool forward) {
  motor.speed = speed;
  motor.duty = speed * (float)(motor.freq);
  motor.forward=forward;
  if(forward){
      mcpwm_comparator_set_compare_value(motor.pwm2.comparator1,0);      
      mcpwm_comparator_set_compare_value(motor.pwm.comparator1,
                                                    motor.duty);
     
  }else{
      mcpwm_comparator_set_compare_value(motor.pwm.comparator1, 0);
      mcpwm_comparator_set_compare_value(motor.pwm2.comparator1,
                                                    motor.duty);

  }
}

void app_main(void)
{
  Motor motor = makeBiMotor(2,4);
  setBiMotorSpeedDirection(motor, 0.1,false);  
}

 

Page 194 -195 uses MCPWM.h given earlier and only partially listed on page

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"
#include "MCPWM.h"

typedef struct
{
    mcpwm_timer_handle_t timer;
    mcpwm_oper_handle_t oper;
    mcpwm_gen_handle_t generator1;
    mcpwm_gen_handle_t generator2;
    mcpwm_cmpr_handle_t comparator1;
} PWM;

PWM makePWM(int gpio, uint32_t res, uint32_t ticksperiod,
            uint32_t duty)
{
    PWM pwm;
    pwm.timer = makeTimer(res, ticksperiod);
    pwm.oper = makeOper();
    mcpwm_operator_connect_timer(pwm.oper, pwm.timer);
    pwm.generator1 = makeGen(pwm.oper, gpio);
    pwm.comparator1 = makeComp(pwm.oper);
    mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
    mcpwm_generator_set_action_on_timer_event(pwm.generator1,
                                              MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                                                                           MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
    mcpwm_generator_set_action_on_compare_event(pwm.generator1,
                                                MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
                                                                               pwm.comparator1, MCPWM_GEN_ACTION_LOW));
    mcpwm_timer_enable(pwm.timer);
    mcpwm_timer_start_stop(pwm.timer, MCPWM_TIMER_START_NO_STOP);
    return pwm;
}
 


void makeDCAC(int32_t gpio1, int32_t gpio2)
{
    int32_t res = 1000000;
    int32_t freq = 20000;
    PWM pwm = makePWM(gpio1, res, freq, 10000);
    pwm.generator2 = makeGen(pwm.oper, gpio2);
    int deadtime = 200;
    mcpwm_dead_time_config_t dtconfig = {
        .posedge_delay_ticks = deadtime,
        .negedge_delay_ticks = 0,
        .flags.invert_output = false};
    mcpwm_generator_set_dead_time(pwm.generator1,
                                  pwm.generator1, &dtconfig);
    dtconfig.posedge_delay_ticks = 0;
    dtconfig.negedge_delay_ticks = deadtime;
    dtconfig.flags.invert_output = true;
    mcpwm_generator_set_dead_time(pwm.generator1, pwm.generator2,
                                  &dtconfig);
}

    void app_main(void)
    {
        makeDCAC(2,4);
    }

 

 

Page 197-198 uses MCPWM.h given earlier  

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"
#include "MCPWM.h"

void delay_ms(int t) {
  vTaskDelay(t / portTICK_PERIOD_MS);
}

typedef struct {
  mcpwm_timer_handle_t timer;
  mcpwm_oper_handle_t oper;
  mcpwm_gen_handle_t generator1;
  mcpwm_gen_handle_t generator2;
  mcpwm_cmpr_handle_t comparator1;
  int32_t freq;
}PWM;

PWM makePWM(int gpio, uint32_t res, uint32_t ticksperiod,
                                           uint32_t duty) {
  PWM pwm;
  pwm.timer = makeTimer(res, ticksperiod);
  pwm.oper = makeOper();
  mcpwm_operator_connect_timer(pwm.oper, pwm.timer);
  pwm.generator1 = makeGen(pwm.oper, gpio);
  pwm.comparator1 = makeComp(pwm.oper);
  mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
  mcpwm_generator_set_action_on_timer_event(pwm.generator1,
        MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
           MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(pwm.generator1,
        MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
           pwm.comparator1, MCPWM_GEN_ACTION_LOW));
  mcpwm_timer_enable(pwm.timer);
  mcpwm_timer_start_stop(pwm.timer, MCPWM_TIMER_START_NO_STOP);
  return pwm;
}

PWM makeServo(int gpio) {

  int32_t res = 1000000;
  int32_t freq = 20000;
  return  makePWM(gpio, res, freq, 500);
}
void setAngle(PWM pwm, float angle) {

  int32_t max = 2500;
  int32_t min = 500;
  int32_t  duty = (float)(max - min) * angle + min;
  mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
}

void app_main(void)
{
  PWM pwm = makeServo(2);
  setAngle(pwm, 1.0);
  delay_ms(100);
  fflush(stdout);
  setAngle(pwm, 0.5);
  delay_ms(100);
  setAngle(pwm, 0.0);
}

 

Page199  uses MCPWM.h given earlier and only partially listed on page

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/mcpwm_prelude.h"
#include "MCPWM.h"

void delay_ms(int t) {
  vTaskDelay(t / portTICK_PERIOD_MS);
}

typedef struct {
  mcpwm_timer_handle_t timer;
  mcpwm_oper_handle_t oper;
  mcpwm_gen_handle_t generator1;
  mcpwm_gen_handle_t generator2;
  mcpwm_cmpr_handle_t comparator1;
  int32_t freq;
}PWM;

PWM makePWM(int gpio, uint32_t res, uint32_t ticksperiod,
                                           uint32_t duty) {
  PWM pwm;
  pwm.timer = makeTimer(res, ticksperiod);
  pwm.oper = makeOper();
  mcpwm_operator_connect_timer(pwm.oper, pwm.timer);
  pwm.generator1 = makeGen(pwm.oper, gpio);
  pwm.comparator1 = makeComp(pwm.oper);
  mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
  mcpwm_generator_set_action_on_timer_event(pwm.generator1,
        MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
           MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH));
  mcpwm_generator_set_action_on_compare_event(pwm.generator1,
        MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP,
           pwm.comparator1, MCPWM_GEN_ACTION_LOW));
  mcpwm_timer_enable(pwm.timer);
  mcpwm_timer_start_stop(pwm.timer, MCPWM_TIMER_START_NO_STOP);
  return pwm;
}

PWM makeServo(int gpio) {

  int32_t res = 1000000;
  int32_t freq = 20000;
  return  makePWM(gpio, res, freq, 500);
}
void setAngle(PWM pwm, float angle) {
  int32_t max = 2500;
  int32_t min = 500;
  int32_t  duty = (float)(max - min) * angle + min;
  mcpwm_comparator_set_compare_value(pwm.comparator1, duty);
}

void app_main(void)
{
  PWM pwm = makeServo(2);
  setAngle(pwm, 1.0);
  delay_ms(100);
  fflush(stdout);
  setAngle(pwm, 0.5);
  delay_ms(100);
  setAngle(pwm, 0.0);
}

 

Page 208

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include "soc/gpio_reg.h"
#include <unistd.h>

void gpio_set(int32_t value, int32_t mask) {
  int32_t* OutAdd = (int32_t*)GPIO_OUT_REG;
  *OutAdd = (*OutAdd & ~mask) | (value & mask);;
}

void delay_us(int t) {
  usleep(t);
}

typedef struct
{
  int gpio;
  int speed;
  bool forward;
  uint32_t gpiomask;
  int phase;
} StepperBi;

uint32_t stepTable[8] = (uint32_t[8]){ 0x8, 0xC, 0x4, 0x6, 0x2, 0x3, 0x1, 0x9 };
/*
    {1, 0, 0, 0},
    {1, 1, 0, 0},
    {0, 1, 0, 0},
    {0, 1, 1, 0},
    {0, 0, 1, 0},
    {0, 0, 1, 1},
    {0, 0, 0, 1},
    {1, 0, 0, 1}
*/
void StepperBiInit(StepperBi* s, int gpio)
{
  s->gpio = gpio;
  for (int i = 0; i < 4; i++) {
    gpio_reset_pin((s->gpio) + i);
    gpio_set_direction((s->gpio) + i, GPIO_MODE_OUTPUT);
  }
  s->gpiomask = 0x0F << gpio;
  volatile uint32_t mask = stepTable[0] << gpio;
  gpio_set(mask, s->gpiomask);
  s->phase = 0;
  s->speed = 0;
  s->forward = true;
}

void setPhase(StepperBi* s, int p)
{
  uint32_t mask = stepTable[p] << (s->gpio);
  gpio_set(mask, s->gpiomask);
}
void stepForward(StepperBi* s)
{
  s->phase = (s->phase + 1) % 8;
  setPhase(s, s->phase);
}
void stepReverse(StepperBi* s)
{
  s->phase = (s->phase - 1) % 8;
  setPhase(s, s->phase);
}
void rotate(StepperBi* s, bool dir, int speed)
{
  s->forward = dir;
  s->speed = speed;
}


void app_main(void)
{

  StepperBi s1;
  StepperBiInit(&s1, 15);
  while (true)
  {
    stepForward(&s1);
    delay_us(1000);
  }
}

 

Page 213

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include "soc/gpio_reg.h"
#include <unistd.h>
#include "driver/gptimer.h"

void gpio_set(int32_t value, int32_t mask) {
  int32_t* OutAdd = (int32_t*)GPIO_OUT_REG;
  *OutAdd = (*OutAdd & ~mask) | (value & mask);;
}

void delay_ms(int t) {
  vTaskDelay(t / portTICK_PERIOD_MS);
}
void delay_us(int t) {
  usleep(t);
}

typedef struct
{
  int gpio;
  int speed;
  bool forward;
  uint32_t gpiomask;
  int phase;
} StepperBi;

uint32_t stepTable[8] = (uint32_t[8]){ 0x8, 0xC, 0x4, 0x6, 0x2, 0x3, 0x1, 0x9 };
/*
    {1, 0, 0, 0},
    {1, 1, 0, 0},
    {0, 1, 0, 0},
    {0, 1, 1, 0},
    {0, 0, 1, 0},
    {0, 0, 1, 1},
    {0, 0, 0, 1},
    {1, 0, 0, 1}
*/
void StepperBiInit(StepperBi* s, int gpio)
{
  s->gpio = gpio;
  for (int i = 0; i < 4; i++) {
    gpio_reset_pin((s->gpio) + i);
    gpio_set_direction((s->gpio) + i, GPIO_MODE_OUTPUT);
  }
  s->gpiomask = 0x0F << gpio;
  volatile uint32_t mask = stepTable[0] << gpio;
  gpio_set(mask, s->gpiomask);
  s->phase = 0;
  s->speed = 0;
  s->forward = true;
}

void setPhase(StepperBi* s, int p)
{
  uint32_t mask = stepTable[p] << (s->gpio);
  gpio_set(mask, s->gpiomask);
}
void stepForward(StepperBi* s)
{
  s->phase = (s->phase + 1) % 8;
  setPhase(s, s->phase);
}
void stepReverse(StepperBi* s)
{
  s->phase = (s->phase - 1) % 8;
  setPhase(s, s->phase);
}

bool step(gptimer_handle_t gptimer, const gptimer_alarm_event_data_t* edata, void* user_data)
{

  StepperBi* s = (StepperBi*)(user_data);
  if (s->forward)
  {
    stepForward(s);
  }
  else
  {
    stepReverse(s);
  }
  return false;
}


void rotate(StepperBi* s, bool dir, int speed)
{
  static gptimer_handle_t  gptimer = NULL;
  if (gptimer == NULL) {
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_new_timer(&timer_config, &gptimer);
    gptimer_alarm_config_t alarm_config = {
       .flags.auto_reload_on_alarm = true,
       .alarm_count = 1000,
        .reload_count = 0 };
    gptimer_set_alarm_action(gptimer, &alarm_config);
    gptimer_event_callbacks_t cbs = {
          .on_alarm = step,
    };
    gptimer_register_event_callbacks(gptimer, &cbs, (void*)s);
    gptimer_enable(gptimer);
    gptimer_start(gptimer);
  };
  s->forward = dir;
  if (speed == 0)
  {
    gptimer_stop(gptimer);
    gptimer_disable(gptimer);
    gptimer_del_timer(gptimer);
    gptimer = NULL;
    s->speed = 0;
    return;
  }

  gptimer_alarm_config_t alarm_config = {
     .flags.auto_reload_on_alarm = true,
     .alarm_count = 2000,
      .reload_count = 0 };
  alarm_config.alarm_count = speed / 150.0 * 1000.0;
  s->speed = speed;
  gptimer_set_alarm_action(gptimer, &alarm_config);
}

void app_main(void)
{

  StepperBi s1;
  StepperBiInit(&s1, 15);
  while (true)
  {
    rotate(&s1, true, 150);
    delay_ms(100);
    rotate(&s1, true, 00);
    delay_ms(100);
  }
}

 


Page 229

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/spi_common.h"
#include "driver/spi_master.h"

void app_main(void)
{
    spi_bus_config_t busConfig = {
        .sclk_io_num = 14,
        .mosi_io_num = 13,
        .miso_io_num = 12,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
    };
    spi_bus_initialize(SPI2_HOST, &busConfig, SPI_DMA_DISABLED);

    spi_device_interface_config_t masterConfig = {
        .command_bits = 0,
        .address_bits = 0,
        .dummy_bits = 0,
        .mode = 0,
        .queue_size = 10,
        .clock_speed_hz = SPI_MASTER_FREQ_8M,
        .spics_io_num = 15,
    };
    spi_device_handle_t SPI = NULL;
    spi_bus_add_device(SPI2_HOST, &masterConfig, &SPI);

    spi_transaction_t transConfig = {
        .length = 8 * 4,
        .flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA,
        .tx_data = {0xAA, 0xAA, 0xAA, 0xAA},
    };
    spi_device_polling_transmit(SPI, &transConfig);

    printf("received %X %X %X %X\n", transConfig.rx_data[0],
           transConfig.rx_data[1], transConfig.rx_data[2],
           transConfig.rx_data[3]);
}

 

Page 235

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/spi_common.h"
#include "driver/spi_master.h"

void app_main(void)
{
    spi_bus_config_t busConfig = {
        .sclk_io_num = 14,
        .mosi_io_num = 13,
        .miso_io_num = 12,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
    };
    spi_bus_initialize(SPI2_HOST, &busConfig, SPI_DMA_DISABLED);

    spi_device_interface_config_t masterConfig = {
        .command_bits = 0,
        .address_bits = 0,
        .dummy_bits = 0,
        .mode = 0,
        .queue_size = 10,
        .clock_speed_hz = 500000,
        .spics_io_num = 15,
    };
    spi_device_handle_t SPI = NULL;
    spi_bus_add_device(SPI2_HOST, &masterConfig, &SPI);

    spi_transaction_t transConfig = {
        .flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA,
    };
    transConfig.tx_data[0] = 0x01;
    transConfig.tx_data[1] = 0x80;
    transConfig.tx_data[2] = 0x00;
    transConfig.length = 8 * 3;
    while (true)
    {
        spi_device_polling_transmit(SPI, &transConfig);
        printf("received %X %X %X %X\n", transConfig.rx_data[0],
               transConfig.rx_data[1], transConfig.rx_data[2],
               transConfig.rx_data[3]);
        int data = (transConfig.rx_data[1] & 0x03) << 8 |
                   transConfig.rx_data[2];
        float volts = data * 3.3 / 1023.0;
        printf("%f\n", volts);
        fflush(stdout);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

 

Page 236-237 from fragments

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/spi_common.h"
#include "driver/spi_master.h"

spi_device_handle_t SPI_init()
{
  spi_bus_config_t busConfig = {
    .sclk_io_num = 14,
    .mosi_io_num = 13,
    .miso_io_num = 12,
    .quadwp_io_num = -1,
    .quadhd_io_num = -1,
  };
  spi_bus_initialize(SPI2_HOST, &busConfig, SPI_DMA_DISABLED);

  spi_device_interface_config_t masterConfig = {
   .command_bits = 0,
   .address_bits = 0,
   .dummy_bits = 0,
   .mode = 0,
   .queue_size = 10,
   .clock_speed_hz = 500000,
   .spics_io_num = 15,
  };
  spi_device_handle_t SPI = NULL;
  spi_bus_add_device(SPI2_HOST, &masterConfig, &SPI);
  return SPI;
}

float readADC(spi_device_handle_t SPI, uint8_t chan)
{
  spi_transaction_t transConfig = {
     .flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA,
  };
  transConfig.tx_data[0] = 0x01;
  transConfig.tx_data[1] = (0x08 | chan) << 4;
  transConfig.tx_data[2] = 0x00;
  transConfig.length = 8 * 3;
  spi_device_polling_transmit(SPI, &transConfig);
  int data = (transConfig.rx_data[1] & 0x03) << 8 |
                                  transConfig.rx_data[2];
  float volts = data * 3.3 / 1023.0;
  return volts;
}

void app_main(void)
{
  spi_device_handle_t SPI = SPI_init();
  while (true) {
    float volts = readADC(SPI, 0);
    printf("%f\n", volts);
    fflush(stdout);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}

Page 247

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "hal/adc_types.h"
#include "esp_adc/adc_oneshot.h"

void app_main(void)
{
    adc_oneshot_unit_handle_t adc1_handle;
    adc_oneshot_unit_init_cfg_t init_config1 = {
        .unit_id = ADC_UNIT_1,
        .ulp_mode = ADC_ULP_MODE_DISABLE,
    };
    adc_oneshot_new_unit(&init_config1, &adc1_handle);

    adc_oneshot_chan_cfg_t config = {
        .bitwidth = ADC_BITWIDTH_DEFAULT,
    };
    adc_oneshot_config_channel(adc1_handle, ADC_CHANNEL_6, &config);

    int data;
    while (true)
    {
        adc_oneshot_read(adc1_handle, ADC_CHANNEL_6, &data);
        printf("%d\n", data);
        fflush(stdout);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

 

Page 248

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "hal/adc_types.h"
#include "esp_adc/adc_oneshot.h"

#include "esp_adc/adc_cali.h"
#include "esp_adc/adc_cali_scheme.h"

void app_main(void)
{
    adc_cali_scheme_ver_t scheme_mask;
    adc_cali_check_scheme(&scheme_mask);
    if (scheme_mask & ADC_CALI_SCHEME_VER_CURVE_FITTING)
    {
        printf("Curve Fit %d\n", scheme_mask);
    }
    else
    {
        if (scheme_mask & ADC_CALI_SCHEME_VER_LINE_FITTING)
        {
            printf("Line Fit %d\n", scheme_mask);
        }
    }
}

 

 

Page 249

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "hal/adc_types.h"
#include "esp_adc/adc_oneshot.h"

#include "esp_adc/adc_cali.h"
#include "esp_adc/adc_cali_scheme.h"

void app_main(void)
{
    adc_oneshot_unit_handle_t adc1_handle;
    adc_oneshot_unit_init_cfg_t init_config1 = {
        .unit_id = ADC_UNIT_1,
        .ulp_mode = ADC_ULP_MODE_DISABLE,
    };
    adc_oneshot_new_unit(&init_config1, &adc1_handle);

    adc_oneshot_chan_cfg_t config = {
        .bitwidth = ADC_BITWIDTH_12,
        .atten = ADC_ATTEN_DB_0};
    adc_oneshot_config_channel(adc1_handle, ADC_CHANNEL_6, &config);

    /* adc_cali_line_fitting_config_t calfit = {
       .unit_id = ADC_UNIT_1,
        .atten = ADC_ATTEN_DB_0,
        .bitwidth = ADC_BITWIDTH_12
    }; */

    adc_cali_curve_fitting_config_t calfit = {
        .unit_id = ADC_UNIT_1,
        .atten = ADC_ATTEN_DB_0,
        .bitwidth = ADC_BITWIDTH_12};

    adc_cali_handle_t cali_handle;
    // adc_cali_create_scheme_line_fitting(&calfit, &cali_handle);
    adc_cali_create_scheme_curve_fitting(&calfit, &cali_handle);

    int data;
    while (true)
    {
        adc_oneshot_get_calibrated_result(adc1_handle, cali_handle,
                                          ADC_CHANNEL_6, &data);
        printf("data cal %d  mV\n", data);
        fflush(stdout);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

 

Page 251 From fragement 

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "hal/adc_types.h"
#include "esp_adc/adc_oneshot.h"

#include "esp_adc/adc_cali.h"
#include "esp_adc/adc_cali_scheme.h"
#include "driver/gptimer.h"

gptimer_handle_t tick_us_start(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_handle_t gptimer_us = NULL;
    gptimer_new_timer(&timer_config, &gptimer_us);
    gptimer_enable(gptimer_us);
    gptimer_start(gptimer_us);
    return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset)
{
    uint64_t count;
    gptimer_get_raw_count(gptimer_us, &count);
    return count + offset;
}
void app_main(void)
{
    adc_oneshot_unit_handle_t adc1_handle;
    adc_oneshot_unit_init_cfg_t init_config1 = {
        .unit_id = ADC_UNIT_1,
        .ulp_mode = ADC_ULP_MODE_DISABLE,
    };
    adc_oneshot_new_unit(&init_config1, &adc1_handle);

    adc_oneshot_chan_cfg_t config = {
        .bitwidth = ADC_BITWIDTH_12,
        .atten = ADC_ATTEN_DB_0};
    adc_oneshot_config_channel(adc1_handle, ADC_CHANNEL_6, &config);

    /* adc_cali_line_fitting_config_t calfit = {
       .unit_id = ADC_UNIT_1,
        .atten = ADC_ATTEN_DB_0,
        .bitwidth = ADC_BITWIDTH_12
    }; */

    adc_cali_curve_fitting_config_t calfit = {
        .unit_id = ADC_UNIT_1,
        .atten = ADC_ATTEN_DB_0,
        .bitwidth = ADC_BITWIDTH_12};

    adc_cali_handle_t cali_handle;
    // adc_cali_create_scheme_line_fitting(&calfit, &cali_handle);
    adc_cali_create_scheme_curve_fitting(&calfit, &cali_handle);

    gptimer_handle_t timer = tick_us_start();

    int data;
    int64_t t = tick_us(timer, 0);
    for (int i = 0; i < 100000; i++)
    {
        adc_oneshot_read(adc1_handle, ADC_CHANNEL_6, &data);
    }
    t = tick_us(timer, 0) - t;
    printf("t=%lld \n", t / 100000);
}

 

Page 252 Note: Only works on an ESP32 or ESP32 S2

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/dac_oneshot.h"

void app_main(void)
{
  dac_oneshot_config_t oneshot_cfg = {
       .chan_id = DAC_CHAN_1
  };
  dac_oneshot_handle_t DAC_handle;
  dac_oneshot_new_channel(&oneshot_cfg, &DAC_handle);
 
  uint8_t value = 0;
  while (true) {
    dac_oneshot_output_voltage(DAC_handle, value);
    value++;
  }
}

 

Page 254 Note: Only works on an ESP32 or ESP32 S2

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/dac_oneshot.h"
#include "math.h"
uint8_t wave[256];

void app_main(void)
{
  for (int i = 0; i < 256; i++)
  {
    wave[i] = (uint8_t)((128.0 + 127 * sinf((float)i
                              * 2.0 * 3.14159 / 255.0)));
  }

  dac_oneshot_config_t oneshot_cfg = {
       .chan_id = DAC_CHAN_1
  };
  dac_oneshot_handle_t DAC_handle;
  dac_oneshot_new_channel(&oneshot_cfg, &DAC_handle);


  while (true) {
    for (int i = 0;i < 256;i++) {
      dac_oneshot_output_voltage(DAC_handle, wave[i]);
    }
  }
}

 

 

Page 255 Note: Only works on an ESP32 or ESP32 S2

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/dac_oneshot.h"
#include "math.h"
uint8_t wave[256];

void app_main(void)
{
  for (int i = 0; i < 256; i++)
  {
    wave[i] = (uint8_t)((128.0 + 127 * sinf((float)i
                              * 2.0 * 3.14159 / 255.0)));
  }

  dac_oneshot_config_t oneshot_cfg = {
       .chan_id = DAC_CHAN_1
  };
  dac_oneshot_handle_t DAC_handle;
  dac_oneshot_new_channel(&oneshot_cfg, &DAC_handle);


  while (true) {
    for (int i = 0;i < 256;i++) {
      dac_oneshot_output_voltage(DAC_handle, wave[i]);
    }
  }
}

 

Page 259 ESP32 only

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/touch_sensor.h"

void app_main(void)
{
  touch_pad_init();
  touch_pad_set_voltage(TOUCH_HVOLT_2V4,
                TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V);
  touch_pad_config(TOUCH_PAD_NUM5, 0);
  uint16_t touch_value=0;
  while (true) {
       touch_pad_read(TOUCH_PAD_NUM5, &touch_value);
    printf("val_touch_gpio12 = %d \n", touch_value);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
}

 

Page 259 ESP32 S3 only

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/touch_sensor.h"

void app_main(void)
{
    touch_pad_init();
    touch_pad_config(TOUCH_PAD_NUM5);
    touch_pad_set_fsm_mode(TOUCH_FSM_MODE_SW);
    uint32_t touch_value = 0;
    while (true)
    {
        touch_pad_sw_start();
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        touch_pad_read_raw_data(TOUCH_PAD_NUM5, &touch_value);
        printf("val_touch_gpio5 = %ld \n", touch_value);
    }
}

 

Page 260 ESP32 only

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/touch_sensor.h"
#include "driver/gpio.h"

void ISR(void *arg)
{
    gpio_set_level(2, !gpio_get_level(2));
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);
    touch_pad_init();
    touch_pad_set_voltage(TOUCH_HVOLT_2V4, TOUCH_LVOLT_0V5,
                          TOUCH_HVOLT_ATTEN_1V);

    touch_pad_config(TOUCH_PAD_NUM5, 800);
    touch_pad_set_trigger_mode(TOUCH_TRIGGER_BELOW);
    touch_pad_isr_register(ISR, NULL);
    touch_pad_intr_enable();
    uint16_t touch_value = 0;
    while (true)
    {
        uint32_t status = touch_pad_get_status();
        touch_pad_read(TOUCH_PAD_NUM5, &touch_value);
        printf("val_touch_gpio12 = %d \n", touch_value);
        printf("status = %ld\n", status);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

Page 262 ESP32 S3 only

 

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/touch_sensor.h"
#include "driver/gpio.h"

void ISR(void *arg)
{
    gpio_set_level(2, !gpio_get_level(2));
    touch_pad_clear_status();
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_INPUT_OUTPUT);

    touch_pad_init();
    touch_pad_config(TOUCH_PAD_NUM5);
    touch_pad_set_thresh(TOUCH_PAD_NUM5, 30000);
    touch_pad_set_channel_mask(1 << 5);
    touch_pad_isr_register(ISR, NULL, TOUCH_PAD_INTR_MASK_ALL);
    touch_pad_intr_enable(TOUCH_PAD_INTR_MASK_ACTIVE);
    touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
    touch_pad_fsm_start();
}

 


 

Page 274

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/i2c_master.h"

void app_main(void)
{
    i2c_master_bus_config_t i2cBus = {
        .i2c_port = I2C_NUM_0,
        .scl_io_num = 15,
        .sda_io_num = 16,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true};
    i2c_master_bus_handle_t bus_handle;
    i2c_new_master_bus(&i2cBus, &bus_handle);

    i2c_device_config_t i2cdev = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = 0x40,
        .scl_speed_hz = 100000,
        .scl_wait_us = 10};
    i2c_master_dev_handle_t dev_handle;
    i2c_master_bus_add_device(bus_handle, &i2cdev, &dev_handle);

    uint8_t buf[10] = {0xE7};
    i2c_master_transmit(dev_handle, buf, 1, 1000);
    i2c_master_receive(dev_handle, buf, 1, 100);
    printf("User Register = %X \r\n", buf[0]);
}

 

Page 278

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/i2c_master.h"

void app_main(void)
{
    i2c_master_bus_config_t i2cBus = {
        .i2c_port = I2C_NUM_0,
        .scl_io_num = 15,
        .sda_io_num = 16,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true};
    i2c_master_bus_handle_t bus_handle;
    i2c_new_master_bus(&i2cBus, &bus_handle);

    i2c_device_config_t i2cdev = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = 0x40,
        .scl_speed_hz = 100000,
        .scl_wait_us = 10};
    i2c_master_dev_handle_t dev_handle;
    i2c_master_bus_add_device(bus_handle, &i2cdev, &dev_handle);

    uint8_t buf[10] = {0xF3};
    i2c_master_transmit(dev_handle, buf, 1, 100);
    esp_err_t err;
    do
    {
        err = i2c_master_receive(dev_handle, buf, 3, 100);
        if (err != ESP_OK)
        {
            i2c_master_bus_rm_device(dev_handle);
            i2c_del_master_bus(bus_handle);
            i2c_new_master_bus(&i2cBus, &bus_handle);
            i2c_master_bus_add_device(bus_handle, &i2cdev, &dev_handle);
        };
    } while (err != ESP_OK);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n lsb %d \n checksum %d \n", msb, lsb, check);
    fflush(stdout);
}

 

Page 278 complete program from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/i2c_master.h"

void app_main(void)
{
    i2c_master_bus_config_t i2cBus = {
        .i2c_port = I2C_NUM_0,
        .scl_io_num = 15,
        .sda_io_num = 16,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true};
    i2c_master_bus_handle_t bus_handle;
    i2c_new_master_bus(&i2cBus, &bus_handle);

    i2c_device_config_t i2cdev = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = 0x40,
        .scl_speed_hz = 100000,
        .scl_wait_us = 10};
    i2c_master_dev_handle_t dev_handle;
    i2c_master_bus_add_device(bus_handle, &i2cdev, &dev_handle);

    uint8_t buf[10] = {0xF3};
    i2c_master_transmit(dev_handle, buf, 1, 100);
    esp_err_t err;
    do
    {
        err = i2c_master_receive(dev_handle, buf, 3, 100);
        vTaskDelay(10 / portTICK_PERIOD_MS);
    } while (err != ESP_OK);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n lsb %d \n checksum %d \n", msb, lsb, check);
    fflush(stdout);
}

 

Page 279 Complete program from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/i2c_master.h"

void app_main(void)
{
    i2c_master_bus_config_t i2cBus = {
        .i2c_port = I2C_NUM_0,
        .scl_io_num = 15,
        .sda_io_num = 16,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true};
    i2c_master_bus_handle_t bus_handle;
    i2c_new_master_bus(&i2cBus, &bus_handle);

    i2c_device_config_t i2cdev = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = 0x40,
        .scl_speed_hz = 100000,
        .scl_wait_us = 10};
    i2c_master_dev_handle_t dev_handle;
    i2c_master_bus_add_device(bus_handle, &i2cdev, &dev_handle);

    uint8_t buf[10] = {0xF3};
    i2c_master_transmit(dev_handle, buf, 1, 100);
    vTaskDelay(50 / portTICK_PERIOD_MS);
    i2c_master_receive(dev_handle, buf, 3, 100);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d \n lsb %d \n checksum %d \n", msb, lsb, check);
    fflush(stdout);
}

 

Page 282

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/i2c_master.h"

uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check)
{
    uint32_t data32 = ((uint32_t)msb << 16) | ((uint32_t)lsb << 8) |
                      (uint32_t)check;
    uint32_t divisor = 0x988000;
    for (int i = 0; i < 16; i++)
    {
        if (data32 & (uint32_t)1 << (23 - i))
            data32 ^= divisor;
        divisor >>= 1;
    };
    return (uint8_t)data32;
}

void app_main(void)
{
    i2c_master_bus_config_t i2cBus = {
        .i2c_port = I2C_NUM_0,
        .scl_io_num = 15,
        .sda_io_num = 16,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true};
    i2c_master_bus_handle_t bus_handle;
    i2c_new_master_bus(&i2cBus, &bus_handle);

    i2c_device_config_t i2cdev = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = 0x40,
        .scl_speed_hz = 100000,
        .scl_wait_us = 10};
    i2c_master_dev_handle_t dev_handle;
    i2c_master_bus_add_device(bus_handle, &i2cdev, &dev_handle);

    uint8_t buf[10] = {0xF3};
    i2c_master_transmit(dev_handle, buf, 1, 100);
    vTaskDelay(50 / portTICK_PERIOD_MS);
    i2c_master_receive(dev_handle, buf, 3, 100);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];

    unsigned int data16 = ((unsigned int)msb << 8) |
                          (unsigned int)(lsb & 0xFC);
    float temp = (float)(-46.85 + (175.72 * data16 / (float)65536));
    printf("Temperature %f C \n\r", temp);
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    buf[0] = 0xF5;
    i2c_master_transmit(dev_handle, buf, 1, 100);
    vTaskDelay(50 / portTICK_PERIOD_MS);
    i2c_master_receive(dev_handle, buf, 3, 100);
    msb = buf[0];
    lsb = buf[1];
    check = buf[2];
    data16 = ((unsigned int)msb << 8) | (unsigned int)(lsb & 0xFC);
    float hum = -6 + (125.0 * (float)data16) / 65536;
    printf("Humidity %f %% \n\r", hum);
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
}

 


Page 292

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include "driver/gptimer.h"
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}
gptimer_handle_t tick_us_start(void) {
  gptimer_config_t timer_config = {
      .clk_src = GPTIMER_CLK_SRC_DEFAULT,
      .direction = GPTIMER_COUNT_UP,
      .resolution_hz = 1000000,
  };
  gptimer_handle_t gptimer_us = NULL;
  gptimer_new_timer(&timer_config, &gptimer_us);
  gptimer_enable(gptimer_us);
  gptimer_start(gptimer_us);
  return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset) {
  uint64_t count;
  gptimer_get_raw_count(gptimer_us, &count);
  return count + offset;
}
void app_main(void)
{
    gptimer_handle_t timer = tick_us_start();
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_set_level(2, 1);
    delay_us(1000);
    gpio_set_level(2, 0);
    delay_us(1000);
    gpio_set_direction(2, GPIO_MODE_INPUT);

    while (gpio_get_level(2) == 1)
    {
    };
    while (gpio_get_level(2) == 0)
    {
    };
    while (gpio_get_level(2) == 1)
    {
    };

    int64_t t2;
    uint32_t data = 0;
    int64_t t1 = tick_us(timer, 0);
    for (int i = 0; i < 32; i++)
    {
        while (gpio_get_level(2) == 0)
        {
        };
        while (gpio_get_level(2) == 1)
        {
        };

        t2 = tick_us(timer, 0);
        data = data << 1;
        data = data | ((t2 - t1) > 100);
        t1 = t2;
    }

    uint8_t checksum = 0;
    for (int i = 0; i < 8; i++)
    {
        while (gpio_get_level(2) == 0)
        {
        };
        while (gpio_get_level(2) == 1)
        {
        };
        t2 = tick_us(timer, 0);
        checksum = checksum << 1;
        checksum = checksum | ((t2 - t1) > 100);
        t1 = t2;
    }

    printf("data %ld\n", data);
    uint8_t byte1 = (data >> 24 & 0xFF);
    uint8_t byte2 = (data >> 16 & 0xFF);
    uint8_t byte3 = (data >> 8 & 0xFF);
    uint8_t byte4 = (data & 0xFF);

    printf("Checksum %X %X\n", checksum,
           (byte1 + byte2 + byte3 + byte4) & 0xFF);
    float humidity = (float)((byte1 << 8) | byte2) / 10.0;
    printf("Humidity= %f %%\n", humidity);
    float temperature;
    int neg = byte3 & 0x80;
    byte3 = byte3 & 0x7F;
    temperature = (float)(byte3 << 8 | byte4) / 10.0;
    if (neg > 0)
        temperature = -temperature;
    printf("Temperature= %f C\n", temperature);
}

 

Page 294 from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_set_level(2, 1);
    delay_us(1000);
    gpio_set_level(2, 0);
    delay_us(1000);
    gpio_set_direction(2, GPIO_MODE_INPUT);

    while (gpio_get_level(2) == 1)
    {
    };
    while (gpio_get_level(2) == 0)
    {
    };
    while (gpio_get_level(2) == 1)
    {
    };

    uint32_t data = 0;
    for (int i = 0; i < 32; i++)
    {
        while (gpio_get_level(2) == 0)
        {
        };
        delay_us(50);
        data = data << 1;
        data = data | gpio_get_level(2);
        while (gpio_get_level(2) == 1)
        {
        };
    }

    uint8_t checksum = 0;
    for (int i = 0; i < 8; i++)
    {
        while (gpio_get_level(2) == 0)
        {
        };
        delay_us(50);
        checksum = checksum << 1;
        checksum = checksum | gpio_get_level(2);
        while (gpio_get_level(2) == 1)
        {
        };
    }

    printf("data %ld\n", data);
    uint8_t byte1 = (data >> 24 & 0xFF);
    uint8_t byte2 = (data >> 16 & 0xFF);
    uint8_t byte3 = (data >> 8 & 0xFF);
    uint8_t byte4 = (data & 0xFF);

    printf("Checksum %X %X\n", checksum,
           (byte1 + byte2 + byte3 + byte4) & 0xFF);
    float humidity = (float)((byte1 << 8) | byte2) / 10.0;
    printf("Humidity= %f %%\n", humidity);
    float temperature;
    int neg = byte3 & 0x80;
    byte3 = byte3 & 0x7F;
    temperature = (float)(byte3 << 8 | byte4) / 10.0;
    if (neg > 0)
        temperature = -temperature;
    printf("Temperature= %f C\n", temperature);
}

 

Page 298

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include "driver/rmt_rx.h"
#include <unistd.h>

TaskHandle_t taskhandle;

void delay_us(int t)
{
    usleep(t);
}

bool rmtrxDone(rmt_channel_handle_t channel,
               const rmt_rx_done_event_data_t *edata, void *user_data)
{
    xTaskResumeFromISR(*(TaskHandle_t *)user_data);
    return true;
}

rmt_symbol_word_t raw_symbols[100];

void app_main(void)
{
    rmt_rx_channel_config_t rmtrxconfig = {
        .gpio_num = 2,
        .resolution_hz = 1000000,
        .mem_block_symbols = 100,
        .clk_src = RMT_CLK_SRC_DEFAULT,
        .flags.invert_in = false,
        .flags.with_dma = false,
    };
    rmt_channel_handle_t rmtrxHandle;
    rmt_new_rx_channel(&rmtrxconfig, &rmtrxHandle);

    rmt_rx_event_callbacks_t cbs = {
        .on_recv_done = rmtrxDone};
    taskhandle = xTaskGetCurrentTaskHandle();
    rmt_rx_register_event_callbacks(rmtrxHandle, &cbs, &taskhandle);
    rmt_enable(rmtrxHandle);

    rmt_receive_config_t receive_config = {
        .signal_range_min_ns = 2000,
        .signal_range_max_ns = 900000,
    };

    while (true)
    {
        gpio_reset_pin(2);
        gpio_set_direction(2, GPIO_MODE_OUTPUT);
        gpio_set_level(2, 1);
        delay_us(1000);
        gpio_set_level(2, 0);
        delay_us(1000);
        gpio_set_direction(2, GPIO_MODE_INPUT);

        while (gpio_get_level(2) == 1)
        {
        };
        while (gpio_get_level(2) == 0)
        {
        };
        while (gpio_get_level(2) == 1)
        {
        };

        rmt_receive(rmtrxHandle, raw_symbols, sizeof(raw_symbols),
                    &receive_config);
        vTaskSuspend(taskhandle);

        uint8_t byte1 = 0;
        uint8_t byte2 = 0;
        uint8_t byte3 = 0;
        uint8_t byte4 = 0;
        uint8_t checksum = 0;

        for (int i = 0; i < 40; i = i + 1)
        {
            switch (i / 8)
            {
            case 0:
                byte1 = byte1 << 1;
                byte1 = byte1 | (raw_symbols[i].duration0 > 50);
                break;
            case 1:
                byte2 = byte2 << 1;
                byte2 = byte2 | (raw_symbols[i].duration0 > 50);
                break;
            case 2:
                byte3 = byte3 << 1;
                byte3 = byte3 | (raw_symbols[i].duration0 > 50);
                break;
            case 3:
                byte4 = byte4 << 1;
                byte4 = byte4 | (raw_symbols[i].duration0 > 50);
                break;
            case 4:
                checksum = checksum << 1;
                checksum = checksum | (raw_symbols[i].duration0 > 50);
                break;
            }
        }

        printf("Checksum %X %X\n", checksum,
               (byte1 + byte2 + byte3 + byte4) & 0xFF);
        float humidity = (float)((byte1 << 8) | byte2) / 10.0;
        printf("Humidity= %f %%\n", humidity);
        float temperature;
        int neg = byte3 & 0x80;
        byte3 = byte3 & 0x7F;
        temperature = (float)(byte3 << 8 | byte4) / 10.0;
        if (neg > 0)
            temperature = -temperature;
        printf("Temperature= %f C\n", temperature);
        delay_us(1000000);
    }
}

 

Page 311

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}

uint8_t readBit(uint8_t pin)
{
    gpio_set_level(pin, 0);
    delay_us(2);
    gpio_set_level(pin, 1);
    delay_us(5);
    uint8_t b = gpio_get_level(pin);
    delay_us(60);
    return b;
}

void writeBit(uint8_t pin, int b)
{
    int delay1, delay2;
    if (b == 1)
    {
        delay1 = 6;
        delay2 = 64;
    }
    else
    {
        delay1 = 60;
        delay2 = 10;
    }
    gpio_set_level(pin, 0);
    delay_us(delay1);
    gpio_set_level(pin, 1);
    delay_us(delay2);
}

int readByte(uint8_t pin)
{
    int byte = 0;
    for (int i = 0; i < 8; i++)
    {
        byte = byte | readBit(pin) << i;
    };
    return byte;
}
void writeByte(uint8_t pin, int byte)
{
    for (int i = 0; i < 8; i++)
    {
        if (byte & 1)
        {
            writeBit(pin, 1);
        }
        else
        {
            writeBit(pin, 0);
        }
        byte = byte >> 1;
    }
}

int presence(int pin)
{
    gpio_reset_pin(pin);
    gpio_set_direction(pin, GPIO_MODE_INPUT_OUTPUT_OD);
    gpio_set_level(pin, 1);
    delay_us(1000);
    gpio_set_level(pin, 0);
    delay_us(480);
    gpio_set_level(pin, 1);
    delay_us(70);
    int res = gpio_get_level(pin);
    delay_us(410);
    return res;
}

int convert(uint8_t pin)
{
    writeByte(pin, 0x44);
    int i;
    for (i = 0; i < 500; i++)
    {
        delay_us(10000);
        if (readBit(pin) == 1)
            break;
    }
    return i;
}
uint8_t crc8(uint8_t *data, uint8_t len)
{
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (int i = 0; i < len; i++)
    {
        databyte = data[i];
        for (int j = 0; j < 8; j++)
        {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;

            databyte >>= 1;
        }
    }
    return crc;
}

float getTemperature(uint8_t pin)
{
    if (presence(pin) == 1)
        return -1000;
    writeByte(pin, 0xCC);
    if (convert(pin) == 500)
        return -3000;
    presence(pin);
    writeByte(pin, 0xCC);
    writeByte(pin, 0xBE);
    uint8_t data[9];
    for (int i = 0; i < 9; i++)
    {
        data[i] = readByte(pin);
    }
    uint8_t crc = crc8(data, 9);
    if (crc != 0)
        return -2000;
    int t1 = data[0];
    int t2 = data[1];
    int16_t temp1 = (t2 << 8 | t1);
    float temp = (float)temp1 / 16;
    return temp;
}
void app_main(void)
{
    while (true)
    {
        float temp = getTemperature(2);
        printf("temperature=%f\n", temp);
        delay_us(1000000);
    }
}

 

Page 318  ESP32 S3

#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void writeGRB(int pin, int GRB)
{
    int mask = 0x800000;
    volatile int duty = 0;
    for (int j = 0; j < 24; j++)
    {
        gpio_set_level(pin, 1);
        if ((GRB & mask))
        {
            for (volatile int i = 0; i < 3; i++)
            {
            }
            duty = 0;
            duty = 0;
            gpio_set_level(pin, 0);
            duty++;
            duty = 0;
            duty = 0;
            duty = 0;
        }
        else
        {
            duty = 0;
            gpio_set_level(pin, 0);
            for (volatile int i = 0; i < 5; i++)
            {
            }
        }

        mask = mask >> 1;
    }
    vTaskDelay(60 / portTICK_PERIOD_MS);
}

void app_main(void)
{
    int pin = 48;
    gpio_reset_pin(pin);
    gpio_set_direction(pin, GPIO_MODE_OUTPUT);
    gpio_set_level(pin, 0);
    vTaskDelay(10 / portTICK_PERIOD_MS);
    int color = 0x0000FF;
    writeGRB(pin, color);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    color = 0x00FF00;
    writeGRB(pin, color);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    color = 0xFF0000;
    writeGRB(pin, color);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
}

 

Page 319  complete program

#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"

void writeGRB(int pin, int GRB)
{
    int mask = 0x800000;
    volatile int duty = 0;
    for (int j = 0; j < 24; j++)
    {
        gpio_set_level(pin, 1);
        if ((GRB & mask))
        {
            for (volatile int i = 0; i < 2; i++)
            {
            }
            duty = 0;
            gpio_set_level(pin, 0);
            duty = 0;
            duty = 0;
            duty = 0;
            duty = 0;
        }
        else
        {
            gpio_set_level(pin, 0);
            for (volatile int i = 0; i < 3; i++)
            {
            }
            duty = 0;
        }
        vTaskDelay(60 / portTICK_PERIOD_MS);
    }
}

void app_main(void)
{
    int pin = 48;
    gpio_reset_pin(pin);
    gpio_set_direction(pin, GPIO_MODE_OUTPUT);
    gpio_set_level(pin, 0);
    vTaskDelay(10 / portTICK_PERIOD_MS);
    int color = 0x0000FF;
    writeGRB(pin, color);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    color = 0x00FF00;
    writeGRB(pin, color);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    color = 0xFF0000;
    writeGRB(pin, color);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
}
 

Page 321

#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "driver/rmt_tx.h"

void convertGRB(int GRB, rmt_symbol_word_t *rawdata)
{
    int mask = 0x800000;
    for (int j = 0; j < 24; j++)
    {
        if ((GRB & mask))
        {
            rawdata[j].level0 = 1;
            rawdata[j].duration0 = 7;
            rawdata[j].level1 = 0;
            rawdata[j].duration1 = 12 - 7;
        }
        else
        {
            rawdata[j].level0 = 1;
            rawdata[j].duration0 = 3;
            rawdata[j].level1 = 0;
            rawdata[j].duration1 = 12 - 3;
        }
        mask = mask >> 1;
    }
}

rmt_symbol_word_t raw_symbols[100];

void app_main(void)
{

    int pin = 2;
    rmt_channel_handle_t led_chan = NULL;
    rmt_tx_channel_config_t tx_chan_config = {
        .clk_src = RMT_CLK_SRC_DEFAULT,
        .gpio_num = pin,
        .mem_block_symbols = 64,
        .resolution_hz = 10000000,
        .trans_queue_depth = 4,
        .flags.with_dma = false,
    };
    rmt_new_tx_channel(&tx_chan_config, &led_chan);

    rmt_copy_encoder_config_t config = {};
    rmt_encoder_handle_t encoder = NULL;
    rmt_new_copy_encoder(&config, &encoder);

    rmt_enable(led_chan);

    rmt_transmit_config_t txconf = {
        .loop_count = 1};
    int color = 0x00FFFF;
    convertGRB(color, raw_symbols);
    rmt_transmit(led_chan, encoder, raw_symbols, 24 * sizeof(rmt_symbol_word_t), &txconf);
    rmt_tx_wait_all_done(led_chan, 10000);
}
 

 

Page 330

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include <unistd.h>
#include "driver/uart.h"

void delay_us(int t)
{
    usleep(t);
}

void app_main(void)
{
    uart_driver_install(UART_NUM_2, 1024, 1024, 0, NULL, 0);
    uart_config_t uart_config = {
        .baud_rate = 9600,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT};
    uart_param_config(UART_NUM_2, &uart_config);
    uart_set_pin(UART_NUM_2, 1, 2, -1, -1);

    char SendData[] = "Hello World";
    uart_flush(UART_NUM_2);
    uart_write_bytes(UART_NUM_2, SendData, sizeof(SendData));
    char RecData[100];
    int n = uart_read_bytes(UART_NUM_2, RecData,
                            sizeof(SendData), 3);
    RecData[n + 1] = 0;
    printf("%s\n", RecData);
    printf("%d    %d\n", n, sizeof(SendData));
}

Page 333

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/uart.h"

#include "driver/gptimer.h"

gptimer_handle_t tick_us_start(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_handle_t gptimer_us = NULL;
    gptimer_new_timer(&timer_config, &gptimer_us);
    gptimer_enable(gptimer_us);
    gptimer_start(gptimer_us);
    return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset)
{
    uint64_t count;
    gptimer_get_raw_count(gptimer_us, &count);
    return count + offset;
}

void app_main(void)
{
    uart_driver_install(UART_NUM_2, 1024, 256, 0, NULL, 0);
    uart_config_t uart_config = {
        .baud_rate = 9600,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT};
    uart_param_config(UART_NUM_2, &uart_config);

    uart_set_pin(UART_NUM_2, 1, 2, -1, -1);

    int n = 4252;
    char SendData[n];
    for (int i = 0; i < n; i++)
    {
        SendData[i] = 'A';
    }
    SendData[n - 1] = 0;

    gptimer_handle_t th = tick_us_start();
    int64_t t = tick_us(th, 0);
    uart_flush(UART_NUM_2);
    uart_write_bytes(UART_NUM_2, SendData, sizeof(SendData));
    printf("t= %f\n", (tick_us(th, 0) - t) / 1000.0);
}

 

Page 335 full program from fragment

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/uart.h"

#include "driver/gptimer.h"

gptimer_handle_t tick_us_start(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_handle_t gptimer_us = NULL;
    gptimer_new_timer(&timer_config, &gptimer_us);
    gptimer_enable(gptimer_us);
    gptimer_start(gptimer_us);
    return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset)
{
    uint64_t count;
    gptimer_get_raw_count(gptimer_us, &count);
    return count + offset;
}

void app_main(void)
{
    uart_driver_install(UART_NUM_2, 1024, 256, 0, NULL, 0);
    uart_config_t uart_config = {
        .baud_rate = 9600,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT};
    uart_param_config(UART_NUM_2, &uart_config);

    uart_set_pin(UART_NUM_2, 1, 2, -1, -1);

    int n = 1000;
    char SendData[n];
    for (int i = 0; i < n; i++)
    {
        SendData[i] = 'A';
    }
    SendData[n - 1] = 0;

    gptimer_handle_t th = tick_us_start();
    int64_t t = tick_us(th, 0);
    uart_flush(UART_NUM_2);
    uart_write_bytes(UART_NUM_2, SendData, sizeof(SendData));
    printf("t= %f\n", (tick_us(th, 0) - t) / 1000.0);

    char RecData[2000];
    int nr = uart_read_bytes(UART_NUM_2, RecData,
                             sizeof(RecData), 300 / portTICK_PERIOD_MS);
    RecData[nr + 1] = 0;
    printf("%s\n", &RecData[1]);
    printf("%d    %d\n", nr, sizeof(SendData));
}

 

Page 335-336

#include "freertos/FreeRTOS.h"
#include <string.h>
#include <unistd.h>
#include "driver/uart.h"
#include "driver/gptimer.h"

gptimer_handle_t tick_us_start(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_handle_t gptimer_us = NULL;
    gptimer_new_timer(&timer_config, &gptimer_us);
    gptimer_enable(gptimer_us);
    gptimer_start(gptimer_us);
    return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset)
{
    uint64_t count;
    gptimer_get_raw_count(gptimer_us, &count);
    return count + offset;
}

void delay_us(int t)
{
    usleep(t);
}
void app_main(void)
{
    uart_driver_install(UART_NUM_2, 512, 1024 * 2, 0, NULL, 0);
    uart_config_t uart_config = {
        .baud_rate = 9600,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT};
    uart_param_config(UART_NUM_2, &uart_config);

    uart_set_pin(UART_NUM_2, 1, 2, -1, -1);
    int n = 1000;
    char SendData[n];
    for (int i = 0; i < n; i++)
    {
        SendData[i] = 'A' + i / 40;
    }
    SendData[n - 1] = 0;

    gptimer_handle_t th = tick_us_start();
    int64_t t = tick_us(th, 0);
    uart_flush(UART_NUM_2);
    uart_write_bytes(UART_NUM_2, SendData, sizeof(SendData));
    printf("t= %f\n", (tick_us(th, 0) - t) / 1000.0);

    delay_us(2000 * 1000);
    char RecData[2000];
    int nr = uart_read_bytes(UART_NUM_2, RecData, sizeof(RecData),
                             300 / portTICK_PERIOD_MS);
    RecData[nr + 1] = 0;
    printf("%s\n", &RecData[1]);
    printf("%d    %d\n", nr, sizeof(SendData));
    uart_driver_delete(UART_NUM_2);
}

 

Page 341

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include <unistd.h>
#include "driver/uart.h"
#include "driver/gptimer.h"

gptimer_handle_t tick_us_start(void)
{
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000,
    };
    gptimer_handle_t gptimer_us = NULL;
    gptimer_new_timer(&timer_config, &gptimer_us);
    gptimer_enable(gptimer_us);
    gptimer_start(gptimer_us);
    return gptimer_us;
}

int64_t tick_us(gptimer_handle_t gptimer_us, int64_t offset)
{
    uint64_t count;
    gptimer_get_raw_count(gptimer_us, &count);
    return count + offset;
}

void delay_us(int t)
{
    usleep(t);
}

void app_main(void)
{
    uart_driver_install(UART_NUM_2, 256, 2000, 0, NULL, 0);
    uart_config_t uart_config = {
        .baud_rate = 9600,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS,
        .rx_flow_ctrl_thresh = 50,
        .source_clk = UART_SCLK_DEFAULT};
    uart_param_config(UART_NUM_2, &uart_config);

    uart_set_pin(UART_NUM_2, 1, 2, 4, 5);
    int n = 1000;
    char SendData[n];
    for (int i = 0; i < n; i++)
    {
        SendData[i] = 'A' + i / 40;
    }
    SendData[n - 1] = 0;

    gptimer_handle_t th = tick_us_start();
    int64_t t = tick_us(th, 0);
    uart_flush(UART_NUM_2);
    uart_write_bytes(UART_NUM_2, SendData, sizeof(SendData));
    printf("t= %f\n", (tick_us(th, 0) - t) / 1000.0);
    fflush(stdout);

    delay_us(1000 * 1000);
    char RecData[2000];
    int nr = 0;
    int nt = 0;
    do
    {

        nt = uart_read_bytes(UART_NUM_2, &RecData[nr],
                             sizeof(RecData - nr), 30 / portTICK_PERIOD_MS);
        nr = nr + nt;
        printf("%d    %d\n", nt, nr);
    } while (nt != 0);

    RecData[nr + 1] = 0;
    printf("%s\n", &RecData[1]);
    printf("%d    %d\n", nr, sizeof(SendData));
    uart_driver_delete(UART_NUM_2);
}

Page 347

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include <unistd.h>
#include "driver/uart.h"

void delay_us(int t)
{
    usleep(t);
}

char uart_read(uart_port_t uart_num)
{
    size_t num;
    do
    {
        uart_get_buffered_data_len(uart_num, &num);
    } while (num == 0);
    char byte;
    uart_read_bytes(UART_NUM_2, &byte, 1, 0);
    return byte;
}

int uart_read_chars(uart_port_t uart_num, char *buf, int length, int timeout, int timeout_char)
{
    int nr = uart_read_bytes(uart_num, buf, 1, timeout / portTICK_PERIOD_MS);
    if (nr == 0)
        return 0;
    nr = uart_read_bytes(uart_num, &buf[1], length - 1, timeout_char / portTICK_PERIOD_MS);
    return nr;
}

int presence(uart_port_t uart_num)
{
    uart_set_baudrate(uart_num, 9600);
    char byte = 0xF0;
    uart_write_bytes(uart_num, &byte, 1);
    delay_us(1000);
    uart_read_bytes(uart_num, &byte, 1, 30 / portTICK_PERIOD_MS);
    uart_set_baudrate(uart_num, 115200);
    if (byte == 0xF0)
        return -1;
    return 0;
}

void writeByte(uart_port_t uart_num, int byte)
{
    char buf[8];
    for (int i = 0; i < 8; i++)
    {
        if ((byte & 1) == 1)
        {
            buf[i] = 0xFF;
        }
        else
        {
            buf[i] = 0x00;
        }
        byte = byte >> 1;
    };
    uart_write_bytes(uart_num, buf, 8);
    delay_us(1000);
    uart_read_bytes(uart_num, buf, 8, 30 / portTICK_PERIOD_MS);
}

char readByte(uart_port_t uart_num)
{
    char buf[8];
    for (int i = 0; i < 8; i++)
    {
        buf[i] = 0xFF;
    }
    uart_write_bytes(uart_num, buf, 8);
    delay_us(1000);
    uart_read_bytes(uart_num, buf, 8, 30 / portTICK_PERIOD_MS);
    char result = 0;
    for (int i = 0; i < 8; i++)
    {
        result = result >> 1;
        if (buf[i] == 0xFF)
            result = result | 0x80;
    }
    return result;
}

void app_main(void)
{
    uart_driver_install(UART_NUM_2, 256, 2000, 0, NULL, 0);
    uart_config_t uart_config = {
        .baud_rate = 9600,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .rx_flow_ctrl_thresh = 50,
        .source_clk = UART_SCLK_DEFAULT};
    uart_param_config(UART_NUM_2, &uart_config);

    uart_set_pin(UART_NUM_2, 1, 2, -1, -1);
    uart_flush(UART_NUM_2);
    printf("%d\n", presence(UART_NUM_2));
    presence(UART_NUM_2);
    writeByte(UART_NUM_2, 0xCC);
    writeByte(UART_NUM_2, 0x44);
    delay_us(1000 * 1000);
    presence(UART_NUM_2);
    writeByte(UART_NUM_2, 0xCC);
    writeByte(UART_NUM_2, 0xBE);

    char data[9];
    for (int i = 0; i < 9; i++)
    {
        data[i] = readByte(UART_NUM_2);
    }

    int t1 = data[0];
    int t2 = data[1];
    int temp1 = (t2 << 8 | t1);
    if (t2 & 0x80)
        temp1 = temp1 | 0xFFFF0000;
    float temp = temp1 / 16.0;
    printf("temp =%f\n", temp);

    uart_driver_delete(UART_NUM_2);
}

 


 

Page 354  complete program from fragments

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "nvs_flash.h"
#include "esp_wifi.h"

int retry_num = 0;

static void wifi_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    switch (event_id)
    {
    case WIFI_EVENT_STA_START:
        printf("WIFI CONNECTING....\n");
        break;
    case WIFI_EVENT_STA_CONNECTED:
        printf("WiFi CONNECTED\n");
        break;
    case WIFI_EVENT_STA_DISCONNECTED:
        printf("WiFi lost connection\n");
        if (retry_num < 5)
        {
            esp_wifi_connect();
            retry_num++;
            printf("Retrying to Connect...\n");
        }
        break;
    case IP_EVENT_STA_GOT_IP:
        printf("Wifi got IP...\n\n");
        break;
    }
}

void app_main(void)
{
    nvs_flash_init();
    esp_netif_init();
    esp_event_loop_create_default();

    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
                               wifi_event_handler, NULL);
    esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
                               wifi_event_handler, NULL);
    wifi_init_config_t wificonfig = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&wificonfig);

    esp_netif_t *netif = esp_netif_create_default_wifi_sta();
    wifi_config_t staconf = {
        .sta = {
            .ssid = "ssid",
            .password = "password",
            .threshold.authmode = WIFI_AUTH_WPA_PSK,
        }};
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_set_config(WIFI_IF_STA, &staconf);
    esp_wifi_set_country_code("CO", false);
    esp_wifi_start();
    esp_wifi_connect();
}

 

 

Page 355 wificonnect.h

int retry_num = 0;
int wifiStatus = 1000;

static void wifi_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    switch (event_id)
    {
    case WIFI_EVENT_STA_START:
        wifiStatus = 1001;
        break;
    case WIFI_EVENT_STA_CONNECTED:
        wifiStatus = 1002;
        break;
    case WIFI_EVENT_STA_DISCONNECTED:
        if (retry_num < 5)
        {
            esp_wifi_connect();
            retry_num++;
            wifiStatus = 1001;
        }
        break;
    case IP_EVENT_STA_GOT_IP:
        wifiStatus = 1010;
        break;
    }
}

void wifiConnect(char *country, char *ssid, char *password)
{
    nvs_flash_init();
    esp_netif_init();
    esp_event_loop_create_default();
    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
                               wifi_event_handler, NULL);
    esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
                               wifi_event_handler, NULL);
    wifi_init_config_t wificonfig = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&wificonfig);
    esp_netif_create_default_wifi_sta();
    wifi_config_t staconf = {
        .sta = {
            .threshold.authmode = WIFI_AUTH_WPA_PSK}};
    strcpy((char *)staconf.sta.ssid, ssid);
    strcpy((char *)staconf.sta.password, password);
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_set_config(WIFI_IF_STA, &staconf);
    esp_wifi_set_country_code(country, false);
    esp_wifi_start();
    esp_wifi_connect();
}

 

Page 356 main.c   uses wificonnect.h

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "string.h"
#include "nvs_flash.h"
#include "wificonnect.h"

void app_main(void)
{    
    wifiConnect("co", "ssid", "password");
        while (wifiStatus != 1010) {
        vTaskDelay(10 / portTICK_PERIOD_MS);
    };
//use WiFi connection
}

 

Page 361 uses  wificonnect.h

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"

#include "socket.h"
#include "wificonnect.h"

void app_main(void)
{
    wifiConnect("CO", "ssid", "password");
    while (wifiStatus != 1010)
    {
        vTaskDelay(10 / portTICK_PERIOD_MS);
    };
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    addr.sin_addr.s_addr = 0x0Ed7b85d;
    if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        return;
    char header[] = "GET /index.html HTTP/1.1\r\nHost:example.com\r\n\r\n";
    int n = write(sockfd, header, strlen(header));
    char buffer[2048];
    n = read(sockfd, buffer, 2048);
    buffer[n] = 0;
    printf("%s\n", buffer);
}

 

Page 364 uses wificonnect.h

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"

#include "esp_http_client.h"
#include "wificonnect.h"
#include "esp_crt_bundle.h"

esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    static int pos = 0;
    switch (evt->event_id)
    {
    case HTTP_EVENT_ERROR:
        printf("HTTP_EVENT_ERROR\n");
        break;
    case HTTP_EVENT_ON_CONNECTED:
        printf("HTTP_EVENT_ON_CONNECTED\n");
        break;
    case HTTP_EVENT_HEADER_SENT:
        printf("HTTP_EVENT_HEADER_SENT\n");
        break;
    case HTTP_EVENT_ON_HEADER:
        printf("HTTP_EVENT_ON_HEADER\n");
        printf("header = %s, %s\n", evt->header_key, evt->header_value);
        break;
    case HTTP_EVENT_ON_DATA:
        printf("HTTP_EVENT_ON_DATA, len=%d\n", evt->data_len);
        if (!esp_http_client_is_chunked_response(evt->client))
        {
            printf("%.*s", evt->data_len, (char *)evt->data);
            char *buf = (char *)(evt->user_data);
            memcpy(buf + pos, evt->data, evt->data_len);
            pos += evt->data_len;
            buf[pos] = 0;
        }
        break;
    case HTTP_EVENT_ON_FINISH:
        printf("HTTP_EVENT_ON_FINISH\n");
        pos = 0;
        break;
    case HTTP_EVENT_DISCONNECTED:
        printf("HTTP_EVENT_DISCONNECTED\n");
        break;
    default:
    }
    return ESP_OK;
}

char httpdata[2000];

void app_main(void)
{
    wifiConnect("co", "ssid", "password");
    while (wifiStatus != 1010)
    {
        vTaskDelay(10 / portTICK_PERIOD_MS);
    };

    esp_http_client_config_t httpconfig = {
        .url = "https://example.com",
        .method = HTTP_METHOD_GET,
        .event_handler = http_event_handler,
        .buffer_size = DEFAULT_HTTP_BUF_SIZE,
        .buffer_size_tx = DEFAULT_HTTP_BUF_SIZE,
        .user_data = httpdata,
        .transport_type = HTTP_TRANSPORT_OVER_SSL,
        .crt_bundle_attach = esp_crt_bundle_attach,
    };

    esp_http_client_handle_t httphandle = esp_http_client_init(&httpconfig);
    esp_http_client_perform(httphandle);
    printf("len data= %d\n", strlen(httpdata));
    printf("html \n %s\n ", httpdata);
}

 

Page 367 full program uses wificonnect.h

 

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"

#include "esp_http_client.h"
#include "wificonnect.h"
#include "esp_crt_bundle.h"

esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    static int pos = 0;
    switch (evt->event_id)
    {
    case HTTP_EVENT_ERROR:
        printf("HTTP_EVENT_ERROR\n");
        break;
    case HTTP_EVENT_ON_CONNECTED:
        printf("HTTP_EVENT_ON_CONNECTED\n");
        break;
    case HTTP_EVENT_HEADER_SENT:
        printf("HTTP_EVENT_HEADER_SENT\n");
        break;
    case HTTP_EVENT_ON_HEADER:
        printf("HTTP_EVENT_ON_HEADER\n");
        printf("header = %s, %s\n", evt->header_key, evt->header_value);
        break;
    case HTTP_EVENT_ON_DATA:
        printf("HTTP_EVENT_ON_DATA, len=%d\n", evt->data_len);
        if (!esp_http_client_is_chunked_response(evt->client))
        {
            printf("%.*s", evt->data_len, (char *)evt->data);
            char *buf = (char *)(evt->user_data);
            memcpy(buf + pos, evt->data, evt->data_len);
            pos += evt->data_len;
            buf[pos] = 0;
        }
        break;
    case HTTP_EVENT_ON_FINISH:
        printf("HTTP_EVENT_ON_FINISH\n");
        pos = 0;
        break;
    case HTTP_EVENT_DISCONNECTED:
        printf("HTTP_EVENT_DISCONNECTED\n");
        break;
    default:
    }
    return ESP_OK;
}

char httpdata[2000];

void app_main(void)
{
    wifiConnect("CO", "ssid", "password");
    while (wifiStatus != 1010) {
        vTaskDelay(10 / portTICK_PERIOD_MS);
    };

    esp_http_client_config_t httpconfig = {
        .host = "192.168.253.75",
        .path = "/test",
        .port = 8080,
        .method = HTTP_METHOD_PUT,
        .event_handler = http_event_handler,
        .buffer_size = DEFAULT_HTTP_BUF_SIZE,
        .buffer_size_tx = DEFAULT_HTTP_BUF_SIZE,
        .user_data = httpdata,
        .transport_type = HTTP_TRANSPORT_OVER_TCP
    };

    esp_http_client_handle_t httphandle =
                           esp_http_client_init(&httpconfig);
    esp_http_client_set_post_field(httphandle, "20.5", 3);
    esp_http_client_perform(httphandle);
    printf("html \n %s\n ", httpdata);
}

 

Page 368   Python

from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
     
    def log_message(self,*args, **kwargs):
        pass

    def do_PUT(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        bodyString= body.decode(encoding="utf-8")
        temp=float(bodyString)
        print(temp)
        self.send_response(200)
        self.end_headers()

httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()

 

 Page 368 complete program http server

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"

#include "wificonnect.h"
#include "esp_http_server.h"

esp_err_t get_handlertemp(httpd_req_t *req)
{
    const char resp[] = "Temperature is 20.3";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

esp_err_t get_handlerhum(httpd_req_t *req)
{
    /* Send a simple response */
    const char resp[] = "Humidity is 80%";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

void app_main(void)
{
    wifiConnect("co", "ssid", "password");
    while (wifiStatus != 1010)
    {
        vTaskDelay(10 / portTICK_PERIOD_MS);
    };

    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    httpd_handle_t server = NULL;
    httpd_uri_t uri_get = {
        .uri = "/temp",
        .method = HTTP_GET,
        .handler = get_handlertemp,
        .user_ctx = NULL};

    if (httpd_start(&server, &config) == ESP_OK)
    {
        httpd_register_uri_handler(server, &uri_get);
        uri_get.uri = "/hum";
        uri_get.handler = get_handlerhum;
        httpd_register_uri_handler(server, &uri_get);
    }
}
 

Page 371  Python

with open("iopress.key", 'rb') as f:
    lines = f.readlines()
lines=b'"'.join(lines)
lines=lines.decode("ascii")
lines=lines.replace("\n",'\\n"\n')
print("static const unsigned char key[]="+'"', lines+";")

with open("iopress.crt", 'rb') as f:
    lines = f.readlines()
lines=b'"'.join(lines)
lines=lines.decode("ascii")
lines=lines.replace("\n",'\\n"\n')
print("static const unsigned char cert[]="+'"', lines+";")

  

Page 372 HTTPS Server  - the certificates listed will eventually timeout and they need to be replaced

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"
#include "wificonnect.h"
#include "esp_https_server.h"


esp_err_t get_handlertemp(httpd_req_t* req)

{
    /* Send a simple response */
    const char resp[] = "Temperature is 20.3";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

esp_err_t get_handlerhum(httpd_req_t* req)
{
    /* Send a simple response */
    const char resp[] = "Humidity is 80%";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

void app_main(void)
{
    wifiConnect("co", "ssid", "password");
    while (wifiStatus != 1010) {
        vTaskDelay(10 / portTICK_PERIOD_MS);
    };




    static const unsigned char cert[] = " -----BEGIN CERTIFICATE-----\n"
        "MIIDazCCAlOgAwIBAgIUA+lvUf9wMrNvaz9DuKnfx4TCoeQwDQYJKoZIhvcNAQEL\n"
        "BQAwRTELMAkGA1UEBhMCR0IxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM\n"
        "GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDA4MTYxMzQwMTNaFw0yNTA4\n"
        "MTYxMzQwMTNaMEUxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw\n"
        "HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB\n"
        "AQUAA4IBDwAwggEKAoIBAQC5zxoZHid/tAtRY+V/Y1rRue4yMiHVLBTmh0kqGM/h\n"
        "NvOuxJUnXKP2qn9cbM1OhZvF7NIIcqNTfHaNwDG+tF8p7YlQGcSBdk5+v3HTIAFI\n"
        "gg3nwHEWdhNhfNnyHrjJG4YDkLGR9KZwMFfBYpsQJHwegUEpYG+5HnaMncjsJu2Q\n"
        "bSO7fQ9dSBC7tIidfv6DhWdz/dHGjqpWYRwHhPACgwS1kKjWiOSrUMWUm3T3px7p\n"
        "UfND7Ypz4/1ObTNZJs8zV8bnWp68YxS0rAeD0QIX3yTgvAGV56Dqdl2V4V5D/dpR\n"
        "No99W3oUu99YeAK/t5pL+Xu5aXDdeg2e1OhPW7o9fZnlAgMBAAGjUzBRMB0GA1Ud\n"
        "DgQWBBQQ4grGsqpNnsjZhWuWOg/Cey7AtTAfBgNVHSMEGDAWgBQQ4grGsqpNnsjZ\n"
        "hWuWOg/Cey7AtTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAj\n"
        "lw6xqyLBB86XIpW1YAINVHEw9x5ewMSbYTN7pDj01tRlaLfr8S4Qvo4FBA2Mq5fn\n"
        "fstJzucb18yX15ZNo6xD1fAPYRf6BK6UwSeo/U4Hjewkk7gOyKEW8IjAMtWB5Svr\n"
        "bZn4wxcSZEX/EHtGWe0kCZ4bDlWn9GuSjtAIZcrKo+jr0Cos2O4t19MWgxrbOwMx\n"
        "AJYepL5+YcMd0NPuERBfTHE7mIG1heH8DAXAHtnFw26835aEyseZIR6EYPVxESYI\n"
        "xmszSRgHFWDEqPpvaFpdOT1fT4KsloSP+wkE8DcmvjYRbPeabc4z8vTHRWgyLsHJ\n"
        "mjqAoUl1y8um2Iw5ko0N\n"
        "-----END CERTIFICATE-----\n"
        ;

    static const unsigned char key[] = " -----BEGIN PRIVATE KEY-----\n"
        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5zxoZHid/tAtR\n"
        "Y+V/Y1rRue4yMiHVLBTmh0kqGM/hNvOuxJUnXKP2qn9cbM1OhZvF7NIIcqNTfHaN\n"
        "wDG+tF8p7YlQGcSBdk5+v3HTIAFIgg3nwHEWdhNhfNnyHrjJG4YDkLGR9KZwMFfB\n"
        "YpsQJHwegUEpYG+5HnaMncjsJu2QbSO7fQ9dSBC7tIidfv6DhWdz/dHGjqpWYRwH\n"
        "hPACgwS1kKjWiOSrUMWUm3T3px7pUfND7Ypz4/1ObTNZJs8zV8bnWp68YxS0rAeD\n"
        "0QIX3yTgvAGV56Dqdl2V4V5D/dpRNo99W3oUu99YeAK/t5pL+Xu5aXDdeg2e1OhP\n"
        "W7o9fZnlAgMBAAECggEABezu3iIyDEaHnd7bsMZQXSPazsr+fTfcqsVhte/4oSwJ\n"
        "dWdbglfX+sPRL/dgTMLCBvvYbuCJCN6NQVQBwh0qc8HZgS5xL9fABRbB4IPCxrcv\n"
        "Dlb6xEabs54xrSEBr5grG+3/W7I7pJRGGCq22zruomJo25LxvSuViEJ35+AN728d\n"
        "rQW4qce1w0837O15u5EnWVrtEtFbvZHytuywvrGKDkB5mmoCE+31ASPnVH3iQFjw\n"
        "s0HPmMufHfKRKnlucfCl5jJToHxIHf4JBd1LlvjpJfi0EtjLNbxg9vhCr4roKdqq\n"
        "BvM+btu31X7Q/R0Ne3p7V5J3FRNwA3Bce7P6TVsqAQKBgQDdi+5e3FR8QY/qJ9xk\n"
        "4MnxycBhcpd2Wtk7oqCs314fk0ifxtQHUh3QKPmTnqJiwxGRdYje05JHHCo2bgMb\n"
        "FN7AHw1NsYSfsxqYxpgkovc1HJxKNbcqfI/bC1q1lT3Vt9gGk7DCD73EauVIAwOe\n"
        "ybfpqte0Ej95zzTAWqRzw3JmQQKBgQDWtGiC/82qJ7X7xwpjnP0++RauF+TC71Hy\n"
        "alqgTbwy0SEaGcxSdGMaxHKK0p94BIs3ZrSsSXLLUSrYC2c0UYnzFLT2i/uJD4NY\n"
        "NrD4Xwq1Wo6vWLvY2EU618nTFmzDGOaC1enA030puRGRWEH+35iud7AIyuuPyLhr\n"
        "Ek0zNIkypQKBgG9UUwu+QoJSW+R59WmIAFMNZCxT7kLeck1icsWMVXsegx8vRfsL\n"
        "y8l/3bLNw6JHjjt/SbFXtikfwSKq88qXGTyIHiJNs2yhDxt4qJm4futknjE4fvvN\n"
        "rmiPcxzOi00rXlYnv2o1iNH8OY2PXjFcApxcapqllNo8QrDqm7tEmudBAoGAcNua\n"
        "CCoQYH3JQhSJGH1//OcQDekPXYxQ5f0TsCnMYGXfYYnoBfuZ0Issrl4yZvL0fuWk\n"
        "2N8u0ULUI4Yy9KRbwAPFb8d7K7uUzfzJn3TN+zAjynX5H+3mzhx5wVSLTS48lM9+\n"
        "tNY2d4UJf/4FisTby/Gr/aM0mXrnvZh8LgtShuUCgYEAw+3K2PalVraWHGbg18pz\n"
        "fL212YObHDdbHM+SaBoopuiJed9Yz5DRbhVSSfuJMNu9WMjk9aR3Tr7s41l5L/+M\n"
        "YGJGNJCE7I4mIfvgXwezxgd5P39+2Ei/qwR9nwsX/y6Mp3EuLKuPJUUaZERjrkIl\n"
        "EVzn7XZ781QWSSBer5/vcQM=\n"
        "-----END PRIVATE KEY-----\n"
       ;

    httpd_ssl_config_t config = HTTPD_SSL_CONFIG_DEFAULT();

    printf("%s", key);

    config.servercert = cert;
    config.servercert_len = sizeof(cert);
    config.prvtkey_pem = key;
    config.prvtkey_len = sizeof(key);



    httpd_handle_t server = NULL;
    httpd_uri_t uri_get = {
    .uri = "/temp",
    .method = HTTP_GET,
    .handler = get_handlertemp,
    .user_ctx = NULL
    };

 

    if (httpd_ssl_start(&server, &config) == ESP_OK) {

        httpd_register_uri_handler(server, &uri_get);
        uri_get.uri = "/hum";
        uri_get.handler = get_handlerhum;
        httpd_register_uri_handler(server, &uri_get);

    }

}



Page 379

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"

void app_main(void)
{
    uint32_t *GPIObase = (uint32_t *)0x60004000; // EP32 S3
    // uint32_t* GPIObase = (uint32_t*)0x3FF44000; //ESP32
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    uint32_t *GPIOSet = GPIObase + 8 / 4;
    uint32_t *GPIOClear = GPIObase + 0xC / 4;
    uint32_t mask = 1 << 2;
    while (true)
    {
        *GPIOSet = mask;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        *GPIOClear = mask;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

 

Page 380

 

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "soc/gpio_reg.h"

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    uint32_t mask = 1 << 2;
    while (true)
    {
        *(int32_t *)GPIO_OUT_W1TS_REG = mask;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        *(int32_t *)GPIO_OUT_W1TC_REG = mask;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}

 

Page 382

#include <stdio.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "soc/gpio_reg.h"

void gpio_value_mask(int32_t value, int32_t mask)
{
    *(int32_t *)GPIO_OUT_REG = (*(int32_t *)GPIO_OUT_REG & ~mask) |
                               (value & mask);
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_OUTPUT);

    uint32_t mask = (1 << 2) | (1 << 4);
    uint32_t value1 = (1 << 2);
    uint32_t value2 = (1 << 4);
    while (true)
    {
        gpio_value_mask(value1, mask);
        gpio_value_mask(value2, mask);
    }
}

 

 

Page 385 Complete program

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_rom_sys.h"
#include <sys/time.h>
#include "driver/ledc.h"
#include "math.h"
#include <unistd.h>

void delay_us(int t)
{
    usleep(t);
}
bool isrollover(int timer)
{
    int32_t *base = (int32_t *)0x600190C0; // ESP32 3S
    // int32_t *base=(int32_t*)0x3FF59180; //ESP32
    bool value = *((int32_t *)base) & 1 << timer;
    *((int32_t *)base + 3) = 1 << timer;
    return value;
}

void PWMconfigLow(int gpio, int chan, int timer, int res, int freq, float duty)
{
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .clk_cfg = LEDC_APB_CLK};
    ledc_timer.timer_num = timer;
    ledc_timer.duty_resolution = res;
    ledc_timer.freq_hz = freq;

    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_LOW_SPEED_MODE,
        .hpoint = 0,
        .intr_type = LEDC_INTR_DISABLE,
    };
    ledc_channel.channel = chan;
    ledc_channel.timer_sel = timer;
    ledc_channel.gpio_num = gpio;
    ledc_channel.duty = ((float)(2 << (res - 1))) * duty;

    ledc_timer_config(&ledc_timer);
    ledc_channel_config(&ledc_channel);
}

uint8_t wave[256];
void app_main(void)
{
    gpio_reset_pin(4);
    gpio_set_direction(4, GPIO_MODE_OUTPUT);
    gpio_set_level(4, 0);

    for (int i = 0; i < 256; i++)
    {
        wave[i] = (uint8_t)((128.0 + sinf((float)i * 2.0 *
                                          3.14159 / 255.0) *
                                         128.0));
    }
    int f = 60000;

    PWMconfigLow(2, 0, 0, 8, f, 0.25);
    while (true)
    {
        for (int i = 0; i < 256; i++)
        {
            ledc_set_duty(LEDC_LOW_SPEED_MODE, 0, wave[i]);
            ledc_update_duty(LEDC_LOW_SPEED_MODE, 0);
            while (!isrollover(0))
            {
            };
        }
    }
}

 

Page 385 full program from fragment

#include "esp_wifi.h"
#include "string.h"
#include "nvs_flash.h"
#include "esp_netif_sntp.h"
#include "sys/time.h"
#include "wificonnect.h"

void app_main(void)
{
    wifiConnect("co", "ssid", "password");
    while (wifiStatus != 1010)
    {
        vTaskDelay(3 / portTICK_PERIOD_MS);
    };

    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
    esp_netif_sntp_init(&config);
    if (esp_netif_sntp_sync_wait(pdMS_TO_TICKS(10000)) != ESP_OK)
    {
        printf("Failed to update system time within 10s timeout");
    }
    struct timeval t;
    gettimeofday(&t, NULL);
    setenv("TZ", "UTC-1", 1);
    tzset();
    struct tm *tm = localtime(&(t.tv_sec));
    printf("hour = %d\n", tm->tm_hour);
    printf("min = %d\n", tm->tm_min);
    char date[100];
    strftime(date, 100, "%a, %d %b %Y %T", tm);
    printf("date = %s\n", date);
}

 

 

Page 390

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_sleep.h"

void app_main(void)
{
    esp_sleep_enable_timer_wakeup(1000000);
    for (int i = 0; i < 10; i++)
    {
        printf("starting sleep %d \n", i);
        fflush(stdout);
        esp_light_sleep_start();
        printf("back from sleep %d \n", i);
        fflush(stdout);
    }
}

 

 

Page 390

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_sleep.h"

void app_main(void)
{
    esp_sleep_enable_timer_wakeup(1000000);
    for (int i = 0; i < 10; i++)
    {
        printf("starting sleep %d \n", i);
        fflush(stdout);
        esp_deep_sleep_start();
        printf("back from sleep %d \n", i);
        fflush(stdout);
    }
}

 

Page 399

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_partition.h"

void app_main(void)
{

    esp_partition_iterator_t partit = esp_partition_find(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);

    while (partit != NULL)
    {
        const esp_partition_t *part = esp_partition_get(partit);
        printf("DATA label= %s Address= %lX  size = %ld \n", part->label, part->address, part->size);
        partit = esp_partition_next(partit);
    };
    esp_partition_iterator_release(partit);
    printf("\n");
    partit = esp_partition_find(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, NULL);
    while (partit != NULL)
    {
        const esp_partition_t *part = esp_partition_get(partit);
        printf("APP label= %s Address= %lX  size = %ld \n", part->label, part->address, part->size);
        partit = esp_partition_next(partit);
    };
    esp_partition_iterator_release(partit);
    return;
}

 

Page 403

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "nvs_flash.h"
void app_main(void)
{

    nvs_flash_init();
    nvs_handle_t my_handle;

    nvs_open("localstorage", NVS_READWRITE, &my_handle);
    char key[] = "mykey";
    int32_t myvalue = 42;
    int32_t myretrievedvalue;
    nvs_set_i32(my_handle, key, myvalue);
    nvs_commit(my_handle);
    nvs_get_i32(my_handle, key, &myretrievedvalue);
    printf("%ld\n", myretrievedvalue);
    return;
}

 

Page 404 You have to create a data partition subtype fat named FAT for this to work

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_vfs_fat.h"

static wl_handle_t s_wl_handle = WL_INVALID_HANDLE;
void app_main(void)
{

    const esp_vfs_fat_mount_config_t mount_config = {
            .max_files = 4,
            .format_if_mount_failed = true,
            .allocation_unit_size = CONFIG_WL_SECTOR_SIZE,          
    };
    esp_err_t err = esp_vfs_fat_spiflash_mount_rw_wl("/spiflash", "FAT", &mount_config, &s_wl_handle);
    if (err != ESP_OK) {
       printf("%X\n",err);
        return;
    }
 
    FILE *f = fopen("/spiflash/hello.txt", "wb");
    fprintf(f, "Hello world");
    fclose(f);

    char buf[25];
    f = fopen("/spiflash/hello.txt", "rb");
    fgets(buf,sizeof(buf),f);
    fclose(f);
    printf("%s\n",buf);
    return;
}

 

 Page 408

#include <string.h>
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"

void app_main(void)
{
    spi_bus_config_t bus_cfg = {
        .mosi_io_num = 15,
        .miso_io_num = 4,
        .sclk_io_num = 18,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 4000,
    };

    sdmmc_host_t host_config = SDSPI_HOST_DEFAULT();
    host_config.max_freq_khz = 400;

    sdspi_device_config_t slot_config =
                            SDSPI_DEVICE_CONFIG_DEFAULT();
    slot_config.gpio_cs = 5;
    slot_config.host_id = host_config.slot;

    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = false,
        .max_files = 5,
        .allocation_unit_size = 16 * 1024
    };

    spi_bus_initialize(host_config.slot, &bus_cfg,
                                     SDSPI_DEFAULT_DMA);

    sdmmc_card_t* card;
    esp_err_t  err = esp_vfs_fat_sdspi_mount("/sdcard",
            &host_config, &slot_config, &mount_config, &card);
    if (err != ESP_OK) {
        printf("%d", err);
    }
    sdmmc_card_print_info(stdout, card);

    FILE *f = fopen("/sdcard/hello.txt", "w");
    fprintf(f, "Hello World");
    fclose(f);

   char buf[25];
    f = fopen("/sdcard/hello.txt", "rb");
    fgets(buf,sizeof(buf),f);
    fclose(f);
    printf("%s\n",buf);
    return;
}

 

 


 

Page 416

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "driver/gpio.h"

void task1(void *arg)
{
    for (;;)
    {
        gpio_set_level(2, 1);
    }
}
void task2(void *arg)
{
    for (;;)
    {
        gpio_set_level(2, 0);
    }
}

void app_main(void)
{
    gpio_reset_pin(2);
    gpio_set_direction(2, GPIO_MODE_OUTPUT);

    TaskHandle_t th1;
    xTaskCreatePinnedToCore(task1, "task1", 2048,
                            NULL, 0, &th1, 1);
    TaskHandle_t th2;
    xTaskCreatePinnedToCore(task2, "task2", 2048,
                            NULL, 0, &th2, 1);
}

 

Page 422

#include <stdio.h>
#include "freertos/FreeRTOS.h"
uint64_t flag1 = 0;
uint64_t flag2 = 0;

void task1(void *arg)
{
    for (;;)
    {
        flag1 = 0xFFFFFFFFFFFFFFFF;
        flag2 = 0xFFFFFFFFFFFFFFFF;
        if (flag1 != flag2)
        {
            printf("task 1 %llX   %llX\n", flag1, flag2);
            fflush(stdout);
        }
    }
}
void task2(void *arg)
{
    for (;;)
    {
        flag1 = 0x0;
        flag2 = 0x0;
        if (flag1 != flag2)
        {
            printf("task 2 %llX   %llX\n", flag1, flag1);
            fflush(stdout);
        }
    }
}
void app_main(void)
{
    TaskHandle_t th1;
    xTaskCreatePinnedToCore(task1, "task1", 4048, NULL, 0, &th1, 1);
    TaskHandle_t th2;
    xTaskCreatePinnedToCore(task2, "task2", 4048, NULL, 0, &th2, 0);
}

 

 Path  424

#include <stdio.h>
#include "freertos/FreeRTOS.h"
int64_t count = 0;

void task1(void *arg)
{
    for (int i = 0; i < 0xFFFFF; i++)
    {
        count = count + 1;
    }
    for (;;)
    {
    }
}
void task2(void *arg)
{
    for (int i = 0; i < 0xFFFFF; i++)
    {
        count = count + 1;
    }
    for (;;)
    {
    }
}

void app_main(void)
{
    TaskHandle_t th1;
    xTaskCreatePinnedToCore(task1, "task1", 2048, NULL, 0, &th1, 1);
    TaskHandle_t th2;
    xTaskCreatePinnedToCore(task2, "task2", 2048, NULL, 0, &th2, 0);
    vTaskDelay(4000 / portTICK_PERIOD_MS);
    printf("%llX\n", count);
}

 

Path 426

#include <stdio.h>
#include "freertos/FreeRTOS.h"
int64_t count = 0;

static portMUX_TYPE my_spinlock = portMUX_INITIALIZER_UNLOCKED;
void task1(void *arg)
{
    for (int i = 0; i < 0xFFFFF; i++)
    {
        taskENTER_CRITICAL(&my_spinlock);
        count = count + 1;
        taskEXIT_CRITICAL(&my_spinlock);
    }
    for (;;)
    {
    }
}
void task2(void *arg)
{
    for (int i = 0; i < 0xFFFFF; i++)
    {
        taskENTER_CRITICAL(&my_spinlock);
        count = count + 1;
        taskEXIT_CRITICAL(&my_spinlock);
    }
    for (;;)
    {
    }
}

void app_main(void)
{
    TaskHandle_t th1;
    xTaskCreatePinnedToCore(task1, "task1", 2048, NULL, 0, &th1, 1);
    TaskHandle_t th2;
    xTaskCreatePinnedToCore(task2, "task2", 2048, NULL, 0, &th2, 0);
    vTaskDelay(4000 / portTICK_PERIOD_MS);
    printf("%llX\n", count);
}

 

Page 428

#include <stdio.h>
#include "freertos/FreeRTOS.h"
QueueHandle_t q;
int64_t count = 0;

void task1(void *arg)
{
    for (;;)
    {
        xQueueSendToBack(q, &count, 2);
        count++;
        vTaskDelay(1);
    }
}
void task2(void *arg)
{
    int64_t data;
    for (;;)
    {
        xQueueReceive(q, &data, 20);
        printf("%llX %d\n", data, uxQueueSpacesAvailable(q));
    }
}

void app_main(void)
{
    q = xQueueCreate(100, sizeof(int64_t));

    TaskHandle_t th1;
    xTaskCreatePinnedToCore(task1, "task1", 2048, NULL, 0, &th1, 1);
    TaskHandle_t th2;
    xTaskCreatePinnedToCore(task2, "task2", 4048, NULL, 0, &th2, 0);
}