Programming the ESP32 in MicroPython
Second Edition
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 46
Page 48
Page 50
Page 51
Page 51
Page 52
Page 53
Page 53
Page 54
Page 56
Page 58
Page 59
Page 61
The address used in machine.mem32 is for the ESP32 for the ESP32 S3 and Nano ESP32 change this to 0x60004004.
Page 87
Page 88
Page 89
Page 90
Page 91
Page 91
Page 94
Page 96
Page 97
Page 105
Page 105
Page 108
Page 109
Page 110
import time
from time import sleep
Page 116
pwm1 = PWM(Pin(4),freq=250)
pwm2 = PWM(Pin(2),freq=250)
pwm1.duty_u16(65535//2)
pwm2.duty_u16(65535//4)
Page 117
import time
from machine import Pin, PWM
pwm1 = PWM(Pin(4),freq = 50)
while True:
pwm1.duty_u16(65535//2)
time.sleep_ms(19)
pwm1.duty_u16(65535//4)
time.sleep_ms(19)
Page 118
Page 119
from machine import Pin, PWM
pwm1 = PWM(Pin(4),freq = 20000000)
pwm1.duty_u16(65535//4*2 +2)
Page 121
Page 123
Page 124
Page 135
Page 139
Page 143
Page 150
Page 154
Page 164
Page 172
Page 173
Page 180
Page 182
Page 184 Only works on ESP32
Page 185 Only works on ESP32
Note: If you have problems running any of these programs check the pullup resistors first and the USB power second.
The hardware I2C often works when the software I2C fails because of pullup or USB power problems.
Page 201
Page 203
Page 203
Page 205
Page 205
Page 206
Page 212
Page 217
Page 221
Page 227
Page 234
Page 243
Page 246
Page 246
Page 247
Page 251
Page 256
Page 257
Page 265
Page 268
Page 268
Page 270
Page 271
Page 280
Page 281
Page 285 Note DS1820 is connected to GPIO4
Page 287
Page 288
Note DS1820 is connected to GPIO4
Page 308
Page 309
Page 311
Page 314
Note DS1820 is connected to GPIO4
Page 319
Page 319
Page 323
Page 326 ESP32 only
Page 328
Page 330
Page 331 What you see as the output of this depends on the IDE you are using
Page 331
What you see as the output of this depends on the IDE you are using
Page 333
What you see as the output of this depends on the IDE you are using
Page 335
What you see as the output of this depends on the IDE you are using
Page 336
What you see as the output of this depends on the IDE you are using
Page 344
import machine
import os
sd =machine.SDCard(slot=2, sck=18, miso=4, mosi=14, cs=5, freq=400)
print(sd)
os.mount(sd, "/sd")
f = open('/sd/Hello.txt', 'w')
f.write('Hello World')
f.close()
print(os.listdir('/sd'))
f = open('/sd/Hello.txt', 'r')
s=f.read()
f.close()
print(s)
Clicking on any link opens an HTML page with the program.
Right click on page and use view source to see code.
Use inspect to see any additional JavaScript loaded.
Part I
Chapter 2
Chapter 3
Page 26 Page 28 Page 30 Page 33 Page 34 Page 38 Page 47 Page 49
Chapter 4
Page 55 Page 57 Page 59 Page 61 Page 63 Page 67 Page 69 Page 70 Page 71 Page 72 Page 73 Page 74 Page 74b Page 76
Chapter 5
Page 81 Page 85 Page 86 Page 87 Page 89
Chapter 6
Chapter 7
Part II
Chapter 8
Page 130 Page 132 Page 134 Page 139 Page 140 Page 140b Page 141 Page 145 Page 148 Page 149
Chapter 9
Chapter 12
Page 201 Page 205 Page 205b Page 206 Page 208 Page 214
The file upload examples are listed as text files to avoid priviacy and security issues.
(IO Press cannot host files users upload without conforming to the GDPR)
Page 216 (text) Page 217 (text) Page 218 (text) Page 219 (text) Page 221 (text) Page 222 (text) Page 224
Chapter 13
Page 229 Page 230 Page 231 Page 235 Page 239 Page 246
You can use pond.pcx to test the PCX program, page 246. Download it to a suitable directory and then use at as a local file to be processed.
Chapter 14
Page 257 This is the program that starts being built up on page 257 and finishes at page 265 Page 270
Chapter 15
IOT Raspberry Pi Programs
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.
There is also the problem of what happens when NetBeans changes and the downloads no longer work.
The best solution is to provide the source code of the programs in a form that can be copied and pasted into a NetBeans project. This means that you have some interaction with the code rather than just running it and it means that it is immune to changes in NetBeans.
The only downside is that you have to create a project to paste the code into.
To do this follow the instruction starting on page 31 - in particular remember to add the bcm2835 library as described on page 33.
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 34
#include <bcm2835.h> #include <stdio.h> int main(int argc, char **argv) { if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(RPI_GPIO_P1_07,BCM2835_GPIO_FSEL_OUTP); while (1) { bcm2835_gpio_write(RPI_GPIO_P1_07, HIGH); bcm2835_delay(500); bcm2835_gpio_write(RPI_GPIO_P1_07, LOW); bcm2835_delay(500); } bcm2835_close(); return 0; }
Page 47
#define _GNU_SOURCE //added not in first edition
#include <stdlib.h> #include <stdio.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); }
include <time.h> int busyWaitCalibrate() { 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) * 1000000000L)+(double) (etime.tv_nsec - btime.tv_nsec); int n = (int) 10 / nseconds * 1000000000L + 0.5; return n; }
Page 49 - See Errata This program doesn't work
#include "bcm2835.h" #include <stdio.h> #include <unistd.h> int main() { bcm2835_init(); bcm2835_gpio_context pin15 = bcm2835_gpio_init(15); bcm2835_gpio_dir(pin15, bcm2835_GPIO_OUT_HIGH); bcm2835_gpio_context pin31 = bcm2835_gpio_init(31); bcm2835_gpio_dir(pin31, bcm2835_GPIO_OUT_LOW); for (;;) { bcm2835_gpio_write(pin15, 0); bcm2835_gpio_write(pin31, 1); bcm2835_gpio_write(pin15, 1); bcm2835_gpio_write(pin31, 0); } return bcm2835_SUCCESS; } }
Page 55
#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 56
#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; }
Page 64
#include <stdio.h> #include <stdlib.h> #include <bcm2835.h> #include <sched.h> #include <sys/mman.h> 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_GPIO_P1_07,BCM2835_GPIO_FSEL_INPT); volatile int i; while (1) { while (1 == bcm2835_gpio_lev(RPI_GPIO_P1_07)); while (0 == bcm2835_gpio_lev(RPI_GPIO_P1_07)); for (i = 0; i < 5000; i++) { if (0 == bcm2835_gpio_lev(RPI_GPIO_P1_07)) break; } printf("%d\n\r", i); fflush(stdout); } return (EXIT_SUCCESS); }
Page 73
#include <stdio.h> #include <string.h> #include <bcm2835.h> #include <fcntl.h> #include <unistd.h> #include <poll.h> #define BUFFER_MAX 50 int fd[32] = {0}; int openGPIO(int pin, int direction); int writeGPIO(int gpio, int value); int readGPIO(int gpio); int setEdgeGPIO(int gpio, char *edge); int main(int argc, char** argv) { if (!bcm2835_init()) return 1; openGPIO(4, 0); setEdgeGPIO(4, "rising"); struct pollfd fdset[1]; for (;;) { fdset[0].fd = fd[4]; fdset[0].events = POLLPRI; fdset[0].revents = 0; int rc = poll(fdset, 1, 5000); if (rc < 0) { printf("\npoll() failed!\n"); return -1; } if (rc == 0) { printf("."); } if (fdset[0].revents & POLLPRI) { lseek(fd[4], 0, SEEK_SET); int val=readGPIO(4); printf("\npoll() GPIO 4 interrupt occurred %d\n\r",val); } 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; }
Page 92
#include <stdio.h> #include <stdlib.h> #include <bcm2835.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> int main(int argc, char** argv) { 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, 0x3f200000); if (map == MAP_FAILED) printf("bcm2835_init: %s 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 98
#define CLK_GP0_CTL 28 #define CLK_GP0_DIV 29 void bcm2835_GPIO4_set_clock_source( uint32_t source, uint32_t divisorI, uint32_t divisorF) { if (bcm2835_clk == MAP_FAILED) return; 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 105
#include <bcm2835.h> #include <stdio.h> #include <sched.h>
int main(int argc, char **argv) { if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(RPI_GPIO_P1_07 , BCM2835_GPIO_FSEL_OUTP); while (1) { bcm2835_gpio_write(RPI_GPIO_P1_07 , HIGH); bcm2835_gpio_write(RPI_GPIO_P1_07 , LOW); } bcm2835_close(); return 0; }
Page 107
#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_GPIO_P1_07 ,BCM2835_GPIO_FSEL_OUTP); while (1) { bcm2835_gpio_write(RPI_GPIO_P1_07 , HIGH); bcm2835_gpio_write(RPI_GPIO_P1_07 , LOW); } bcm2835_close(); return 0; }
Page 116
#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 (EXIT_SUCCESS); }
Page 117
#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 146
#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_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 154
#include <stdio.h> #include <stdlib.h> #include <bcm2835.h> 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_626); setTimeout(40000); bcm2835_i2c_setSlaveAddress(0x40); char buf[4] = {0xE3}; uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3); printf("status=%d\n\r",status); 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); 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("msb %d\n\rlsb%d\n\rchecksum %d\n\r",msb,lsb,check); 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); } 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; int i; for (i = 0; i < 16; i++) { if (data32 & (uint32_t) 1 << (23 - i)) data32 ^= divisor; divisor >>= 1; }; return (uint8_t) data32; } void setTimeout(uint16_t timeout) { volatile uint32_t* stimeout = bcm2835_bsc1+BCM2835_BSC_CLKT/4; bcm2835_peri_write(stimeout, timeout); }
Page 165
#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_GPIO_P1_07, BCM2835_GPIO_FSEL_INPT); bcm2835_delayMicroseconds(1000); GetDHT22data(RPI_GPIO_P1_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 182
#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_GPIO_P1_07, BCM2835_GPIO_FSEL_INPT); int i; uint8_t code[8]; for (;;) { int p = readiButton(RPI_GPIO_P1_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 202
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 208
int main(int argc, char **argv) { const struct sched_param priority = {5}; sched_setscheduler(0, SCHED_FIFO, &priority); mlockall(MCL_CURRENT | MCL_FUTURE); if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(RPI_GPIO_P1_07, BCM2835_GPIO_FSEL_INPT); uint64_t serial[15]; int i, j; uint8_t *code; int crc,d; for (;;) { for (j = 0; j < 1000; j++) { d = oneWireScan(RPI_GPIO_P1_07, serial); if (d != 4)continue; crc = 0; for (i = 0; i < d; i++) { code = (uint8_t*) & serial[i ]; crc += crc8(code, 8); } printf("%hho %d %d\n\r", crc, d, j); fflush(stdout); if (crc == 0)break; bcm2835_delayMicroseconds(30000); } for (i = 0; i < d; i++) { printf("%llX \n", serial[i]); float temp = getDeviceTemperature(RPI_GPIO_P1_07,serial[i]); printf("temperature = %f C \n", temp); } }
Page 219
#include <stdio.h> #include <stdlib.h> #include <bcm2835.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"); bcm2835_spi_end(); bcm2835_close(); return (EXIT_SUCCESS); }
Page 247
#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 This email address is being protected from spambots. You need JavaScript enabled to view it."); 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 248
#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 This email address is being protected from spambots. You need JavaScript enabled to view it.");
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;
(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 257
#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 263
#define _POSIX_C_SOURCE 200112L
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h>
#include <unistd.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); struct sockaddr_storage client_addr; socklen_t addr_size = sizeof client_addr; char headers[] = "HTTP/1.0 200 OK\r\nServer:CPi\r\nContent-type:text/html\r\n\r\n"; char buffer[2048]; char html[] = "<html><head><title>Temperature</title></head><body>{\"humidity\":81%,\"airtemperature\":23.5C}</p></body></html>\r\n"; char data[2048] = {0}; snprintf(data, sizeof data,"%s %s", headers, html); for (;;) { 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 271
#define _GNU_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 <time.h> #define blocksize 255 #define DEBUG 1 int sfd; char buf[blocksize]; int initWiFi(); int ATWiFi(); int getBlock(); int main(int argc, char** argv) { initWiFi(); ATWiFi(); return (EXIT_SUCCESS); } int initWiFi() { system("sudo systemctl stop This email address is being protected from spambots. You need JavaScript enabled to view it."); 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, B115200); cfmakeraw(&options); options.c_cflag &= ~CSTOPB; options.c_cflag |= CLOCAL; options.c_cflag |= CREAD; options.c_cc[VTIME] = 1; options.c_cc[VMIN] = blocksize; (sfd, TCSANOW, &options); }; int getBlock() { int bytes; struct timespec pause; pause.tv_sec = 0; pause.tv_nsec = 100000000; nanosleep(&pause, NULL); memset(buf, '\0', sizeof (buf)); ioctl(sfd, FIONREAD, &bytes); if (bytes == 0)return 0; int count = read(sfd, buf, blocksize - 1); buf[count] = 0; if (DEBUG) { printf("%s", buf); fflush(stdout); } return count; } int ATWiFi() { dprintf(sfd, "AT\r\n"); return getBlock(); }
Page 282
#define _GNU_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 <time.h> #define blocksize 255 #define DEBUG 1int sfd; char buf[blocksize];int initWiFi(); int ATWiFi(); int getBlock(); int getBlocks(int num, char target[]); int getVersionWiFi(); int resetWiFi(); int setUARTWiFi(); int modeWiFi(int mode); int scanWiFi(); int connectWiFi(char ssid[], char pass[]); int getIPWiFi(); int startServerWiFi(); int getWebPageWiFi(char URL[], char page[]);/* int main(int argc, char** argv) { initWiFi();ATWiFi(); connectWiFi("ssid", "password"); getIPWiFi(); startServerWiFi(); return (EXIT_SUCCESS); } int initWiFi() { system("sudo systemctl stop This email address is being protected from spambots. You need JavaScript enabled to view it.";); 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, B115200); cfmakeraw(&options); options.c_cflag &= ~CSTOPB; options.c_cflag |= CLOCAL; options.c_cflag |= CREAD; options.c_cc[VTIME] = 1; options.c_cc[VMIN] = blocksize; (sfd, TCSANOW, &options); }; int ATWiFi() {dprintf(sfd, "AT\r\n"); return getBlock(); } int getVersionWiFi() { dprintf(sfd, "AT+GMR\r\n"); return getBlock(); } int resetWiFi() { dprintf(sfd, "AT+RST\r\n"); return getBlock(); } int setUARTWiFi() { dprintf(sfd, "AT+UART_CUR=115200,8,1,0,0\r\n"); return getBlock(); } int modeWiFi(int mode) { dprintf(sfd, "AT+CWMODE_CUR=%d\r\n", mode); return getBlock(); } int scanWiFi() { dprintf(sfd, "AT+CWLAP\r\n"); return getBlocks(20, "OK"); } int connectWiFi(char ssid[], char pass[]) { dprintf(sfd, "AT+CWJAP_CUR=\"%s\",\"%s\"\r\n", ssid, pass); return getBlocks(20, "OK"); } int getIPWiFi() { dprintf(sfd, "AT+CIFSR\r\n"); return getBlocks(10, "OK"); } int getWebPageWiFi(char URL[], char page[]) { dprintf(sfd, "AT+CIPSTART=\"TCP\",\"%s\",80\r\n", URL); if (getBlocks(10, "OK") < 0) return -1; char http[150]; sprintf(http, "GET %s HTTP/1.1\r\nHost:%s\r\n\r\n", page, URL); dprintf(sfd, "AT+CIPSEND=%d\r\n", strlen(http)); if (getBlocks(10, ">") < 0) return -1; dprintf(sfd, "%s", http); return getBlocks(10, "</html>"); } int startServerWiFi() { char temp[blocksize]; char id[10]; dprintf(sfd, "AT+CIPMUX=1\r\n"); if (getBlocks(10, "OK") < 0) return -1; dprintf(sfd, "AT+CIPSERVER=1,80\r\n"); if (getBlocks(10, "OK") < 0) return -1; char data[] = "HTTP/1.0 200 OK\r\nServer:Pi\r\nContent-type: text/html\r\n\r\n<html><head><title>Temperature</title></head><body><p>{\"humidity\":81%,\"airtemperature\":23.5C}</p></body></html>\r\n"; for (;;) { if (getBlocks(1, "+IPD") < 0)continue; char *b = strstr(buf, "+IPD"); b += 5; strncpy(temp, b, sizeof (temp)); char *e = strstr(temp, ","); int d = e - temp; memset(id, '\0', sizeof (id)); strncpy(id, temp, d); dprintf(sfd, "AT+CIPSEND=%s,%d\r\n",id, strlen(data)); if (getBlocks(10, ">") < 0) return -1; dprintf(sfd, "%s", data); if (getBlocks(10, "OK") < 0) return -1; dprintf(sfd, "AT+CIPCLOSE=%s\r\n", id); if (getBlocks(10, "OK") < 0) return -1; } } int getBlock() { int bytes; struct timespec pause; pause.tv_sec = 0; pause.tv_nsec = 100000000; nanosleep(&pause, NULL); memset(buf, '\0', sizeof (buf)); ioctl(sfd, FIONREAD, &bytes); if (bytes == 0)return 0; int count = read(sfd, buf, blocksize - 1); buf[count] = 0; if (DEBUG) { printf("%s", buf); fflush(stdout); } return count; } int getBlocks(int num, char target[]) { int i; struct timespec pause; pause.tv_sec = 1; pause.tv_nsec = 0; for (i = 0; i < num; i++) { nanosleep(&pause, NULL); getBlock(); if (strstr(buf, target))return i; } return -1; }
Page 6 of 6