Professional Documents
Culture Documents
SIGNAL TRANSMISSION
Nowadays devices, either they are made for regular or industrial use, are based on wireless
communication technology and the main reason is not to get rid of wires, but to be able to
interconnect between them. Meanwhile buying a wireless device became natural for everyone
and price for Wi-Fi Ready equipment lowered with time passing.
While you read this, a WiFi microchip has no more than 5mm length and can be powered with as
low as 10 micro Amps during sleep period. In this article we are going to test one of the cheapest
and easy to use WiFi development platform, the ESP8266 Arduino compatible device.
1.2PROBLEM STATEMENT
Nowadays, everything is moving toward the Internet of Things (IoT). Devices employ
microchips connected to the internet. A lot of work is put in place when dealing with the manual
configuration of devices. With this module, many IoT projects can be performed, one including
the transmission of audio signals over a great distance, even up to 1 km.
1.3OBJECTIVES
1.3.1 General Objectives
The ultimate objective of this project is to transmit an audio signal using the WiFi ESP8266
module. The receiver module will decode the signal and deliver the output for given purposes.
To establish communication between the two ESP8266 modules, one acting like an AP
and the other like an SP
To simulate the system on Proteus
1.4 PROPOSED METHODOLOGY
The proposed methodology I took to implement this project is to first of all understand the
functioning principle behind the project and to implement the various hardware and software
needed to realize this project with brilliance.
Chapter three is the analysis and design of the project. It gives the proposed methodology used to
implement the project, and the various steps to be undertaken for the project to work.
Chapter four gives the implementation of the project and the results obtained. It is in this chapter
that the output is shown and the work proper is demonstrated.
Chapter five gives a general conclusion to the whole work, with a summary of findings,
contribution to Engineering and Technology, open points and future scope.
2.1INTRODUCTION
This chapter is devoted to having a knowledge on the ESP8266 module. This is important to
know how it functions. Proper understanding of the module would serve a means to better use it
for Telecommunication purposes.
In wireless communications, there must be a sender, a receiver, and a wireless channel for the
transfer of the signals. Many such channels exist. They include radio waves, microwaves, and X-
rays, all part of the EM spectrum.
In the subsequent years, the use of radio (and later television) became widespread throughout
the world. While in the “normal” language, we usually do not think of radio or TV as “wireless
communications,” they certainly are, in a scientific sense, information transmission from one
place to another by means of electromagnetic waves. They can even constitute “mobile
communications,” as evidenced by car radios. A lot of basic research – especially concerning
wireless propagation channels – was done for entertainment broadcasting. By the late 1930s, a
wide network of wireless information transmission – though unidirectional – was in place.
When considering wireless communications, the following parameters need to be taken into
consideration: frequency, waveform, antennas, and spread spectrum, modulation,
multiplexing and signal propagation. The table below gives the different frequency bands and
the classification between them.
In wireless communications we have analog and digital signals. Analog signals are signals in a
continuous waveform while digital signals are discrete signals. I.e. they are analog signals that
have been sampled, quantized and encoded. The figure below shows examples of analog and
digital signals.
S (t) = At sin (2 π ft t + φt) where ft is the frequency of the signal and φt is the phase.
The table below shows the various frequency bands in MHz and their applications in wireless
communications.
2.2.2 WIFI
At its most basic, Wi-Fi is the transmission of radio signals. WiFi is an IEEE 802.11 standard
dealing with a packet protocol that defines data transmission and manages location-independent
network access using radio signals.
Wi-Fi is a physical/link layer interface, as is Ethernet. The layers above the physical and data
link layers include TCP/IP. On a practical level, this means that all Rabbit sample programs and
customer applications for TCP/IP that are run on an Ethernet interface will also run on a Wi-Fi
interface.
Benefits of Wi-Fi
1. Wireless Ethernet: Wi-Fi is an Ethernet replacement. Wi-Fi and Ethernet, both IEEE
802 networks, share some core elements.
2. Extended Access: The absence of wires and cables extends access to places where
wires and cables cannot go or where it is too expensive for them to go.
3. Cost Reduction: As mentioned above, the absence of wires and cables brings down
cost. This is accomplished by a combination of factors, the relatively low cost of
wireless routers, and no need for trenching, drilling and other methods that may be
necessary to make physical connections.
4. Mobility: Wires tie you down to one location. Going wireless means you have the
freedom to change your location without losing your connection.
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 8
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
5. Flexibility: Extended access, cost reductions, and mobility create opportunities for new
applications as well as the possibility of creative new solutions for legacy applications.
[12]
The ESP8266 is a low-cost Wi-Fi microchip with full TCP/IP stack and microcontroller
capability produced by manufacturer Espressif Systems in Shanghai, China. [1]
ESP8266 offers a complete and self-contained Wi-Fi networking solution, allowing it to either
host the application or to offload all Wi-Fi networking functions from another application
processor. [7]
When ESP8266 hosts the application, and when it is the only application processor in the device,
it is able to boot up directly from an external flash. It has integrated cache to improve the
performance of the system in such applications, and to minimize the memory requirements.
Alternately, serving as a Wi-Fi adapter, wireless internet access can be added to any
microcontroller-based design with simple connectivity through UART interface or the CPU
AHB bridge interface.
ESP8266 on-board processing and storage capabilities allow it to be integrated with the sensors
and other application specific devices through its GPIOs with minimal development up-front and
minimal loading during runtime. With its high degree of on-chip integration, which includes the
antenna switch balun, power management converters, it requires minimal external circuitry, and
the entire solution, including front-end module, is designed to occupy minimal PCB area.
Sophisticated system-level features include fast sleep/wake context switching for energy-
efficient VoIP, adaptive radio biasing for low-power operation, advance signal processing, and
spur cancellation and radio co-existence features for common cellular, Bluetooth, DDR, LVDS,
LCD interference mitigation.
Successor ESP 32
Price 3$
Pin Specifications
Features
32-pin QFN package
11 b/g/n
The following current consumption is based on 3.3V supply, and 25℃ ambient, using internal
regulators. Measurements are done at antenna port without SAW filter. All the transmitter’s
measurements are based on 90% duty cycle, continuous transmit mode.
Standby 0.9 mA
Deep Sleep 10 mA
2. RF Performance
The following are measured under room temperature conditions with 3.3V and 1.1V power
supplies.
Input impedance 50 Ω
Sensitivity
OFDM, 6Mbps 37 dB
OFDM, 54 Mbps 21 dB
HT20, MCS0 37 dB
HT20, MCS7
Pros of ESP8266
The main advantage is that it is very cheap starting from $3. [1]
It can very well receive commands via the internet or local host.
The ESP8266 is also faster and stores more than the Arduino
CONS OF ESP8266
The main disadvantage of the ESP-01 is that it has only 2 GPIO pins. Hence in this respect, the
ESP-12 would be preferable.
Home Automation
Mesh Network
Baby Monitor
Network Camera
Sensor Networks
Wearable Electronics
Security ID tag
2.3RELATED WORKS
A lot of related works were carried out by previous Engineers in the same technology. Sven 337
used the ESP8266 module to send the sound data of a baby over WiFi to a receiver (mum) at the
other room. This project helps in determining the state of the baby (baby monitor).
In [8] Dola Chakraborty developed a system capable of performing Voice Controlled Home
Automation using the ESP8266 NodeMCU. This system is designed to control electrical devices
throughout the house with ease of installing it, ease of use and cost effective design and
implement.
Rahul Singh and Saheli Dutta in [9] undertook the project of controlling home appliances via
Bluetooth, which is similar to WiFi home automation.
2.4PARTIAL CONCLUSION
In this chapter we have seen the fundamentals in the Engineering of the project. In the next
chapter we shall see the analysis and design of the project.
3.1INTRODUCTION
This chapter is devoted to understanding the methodology used to implement the project. It deals
with the various steps taken for the project to work.
3.2PROPOSED METHODOLOGY
This is a clear understanding of the path needed to undertake in order to achieve the goal of the
project. The ultimate objective of this project is to investigate the ESP8266 WiFi module and
apply it to an audio signal transmission. The investigation part has been done in the previous
chapters, where the RF characteristics, power consumption, specs and features of the ESP-01
module were given, together with the pin specifications and operating voltage. The next phase is
to use the ESP8266 to transmit an audio signal.
The methodology employed will be based on the investigation of the module and will be such as
to get an input sound signal, transmit the sound data over the WiFi frequency to the receiver, and
output through a loud speaker. Two ESP8266 modules will be used for this; one a server and the
other a client. Firstly, a serial communication will be established between the two modules to
ensure that any data can be transmitted. Then the sound data will be sent. A flow diagram shows
the different steps needed to be taken for this project.
3.3 DESIGN
Start
No
Is there sound
transmission?
Check code and
circuit connection
Yes
Is there sound No
reception?
Check code and
Yes circuit connection
End
The following circuit was simulated on Proteus to serve as a guide to the actual work that is to be
done in the project. No libraries of ESP-01 were found online, just that of ESP-12 were found,
and that is what was used during simulation.
ESP8266 ESP8266
sender receiver
PLL module module PLL
frequency frequency Loud
modulator AP SP
Sound demodulator speaker
Working of ESP8266:
1. First we connect and set-up the environment required for ESP8266,that is through the
Arduino-IDE. Nowadays there are many different platforms to run ESP8266, but since
Arduino is universal, we will use that.
2. The ESP8266 needs to be flashed with a firmware which will host the program. In this too
there are many different firmware(s). And it needs to be put into Flash mode before
flashing.
3. After Flashing we upload our program in the same way like an Arduino but with a small
catch that the ESP8266 needs to be put into Boot loader mode before uploading.
4. Saving the program on the ESP8266 so that it does not reset after restarting.
5. Last but not the least ONLY 3.3V and NOT 5V. Any other higher voltage may end up
frying the module.
4.1INTRODUCTION
In this chapter we shall see the implementation of the system, the results and the discussion with
relation with the results.
4.2.2 Hardware
ESP8266 (ESP-01) WiFi module
Arduino UNO
Breadboard
Jumper wires
Sound sensor
Green LED
Resistors
Capacitors
4.2.3 Software
Arduino IDE
ESP826 Flasher
Fritzing
Proteus
4.3DESCRIPTION OF THE IMPLEMENTATION PROCESS
The steps described below are those taken for the implementation of the project.
4.3.1: Collect Material and setup environment for ESP8266
Collect Material
As stated before, the very first step needed is to collect the material needed to implement the
project. They are all the materials described above.
Next the environment for programing the ESP8266 needs to be setup. The software used is
Arduino Environment v 1.6.4 or greater. Installing with Boards Manager Starting with 1.6.4,
Arduino allows installation of third-party platform packages using Boards Manager. It has
packages available for Windows, Mac OS, and Linux (32 and 64 bit).
Install Arduino 1.6.4 (or greater) from the Arduino website (I have 1.6.11). Start Arduino and
open Preferences window.
Select ‘Tools’ -‘Flash Size’ ‘512K (64K SPIFFS) and ‘Upload Speed’ ‘115200’ for ESP 12E,
also Some ESPs may be 9600
Important part here is the ESP uses more current than the Arduino, thus at risk .Therefore I use
and external DC 9 V, 1 A beside the PC connection.
we can use to check the connections between the ESP8266 and the Arduino (without Atmega).
The ESP modules usually come with a built in AT Firmware by the Ai-Thinker.
The Arduino IDE is open
Go to the Serial Monitor (Do select your COM port) and Write: AT. This should return OK
, else it's not working
Possible Errors might be loose connections, the proper baud rate was not selected, the Arduino
COM port is not correct, or the red LED on the ESP 01 is not high, meaning the module is not
supplied.
We need to flash our ESP8266 modules in a firmware that will host the program. So we will
flash a firmware which will make the ESP to take the Arduino Script (Cpp script) and run it.
The ESP can be programmed by various methods. There are many firmwares for it like the
NodeMCU, ESPBasic, Arduino, etc. The NodeMCU runs on the LUA script but Arduino still
runs on C++ (In my expertise)
So we will flash a firmware which will make the ESP to take the Arduino Script (Cpp script) and
run it. The softwares available are: ESP8266 Flasher, NodeMCU own Flasher, and ESP Flash
Download Tool. The software used is ESP8266 Flasher.
Select 0x00000
Hit Download
It will start to Erase and Write firmware (0 to 99%). It will end at saying Unable to leave
Flash mode, don’t worry it's perfectly fine. THE BIN FILE is in THE ZIP (v0.9.2.2 AT
Firmware. bin). Use this.
Possible Errors:
Loose connections
If nothing works, restart your ESP and Take the RST (Reset) to Gnd and remove. It will let the
blue Led flash once and try again from the start.
4.3.2: Establishing connection between the transmitter and receiver ESP8266 modules
After all the above steps have been taken, we can now program the ESP8266 module. Many
programmers are available for this, but the programmer I used was the ESP8266 USB-to-Serial
UART programmer shown on the picture.
There are two ESP8266 modules. One will act as a server or an Access Point (AP), and the other
as a client or a Station Point (SP). These two modules need to be programmed in this way in
order to initiate communication between the two.
The results of the serial monitor below show the various connections done for both the AP and
SP ESP modules.
4.3.3: Upload transmitter and receiver codes for audio signal transmission
After we have successfully established communication between the two ESP8266 Wi-Fi
modules, one as an AP and the other as an SP, we now need to upload the code for audio signal
transmission and reception on both sides respectively. The various codes are found in the
appendix section below.
Once the codes have been uploaded to the WiFi modules, we now need to implement the project
circuit that will get the sound from a sound sensor and at the end receive the signal from a loud
speaker connected at the receiver side.
Why the necessity of using this project for sound transmission in our today world?
(problem statement)
What are the different material in making the project and how can they be coupled
together?
What are the different tests to be done in order to determine the effectiveness and
efficiency of the project?
The first thing considered was investigating the WiFi module and understanding all its
characteristics for the implementation of the project. Then the various materials, both hardware
and software were gathered for the mounting of the circuit. Afterwards, testing and debugging
were done to make sure the project works. Finally the project was tested to see if it meets up to
the task of the objective. i.e. if it can actually transmit audio signal.
It can also be used in large conferences for the distant transmission of sound data to various users
of the WLAN network.
5.3 RECOMMENDATIONS
This project can be recommended to teaching conferences and large centers and auditoriums for
the distant communication between all panelists in the field.
It can also be used as a baby monitor to monitor the cries of babies and respond to them in case
of incidents- in homes, or other domestic purposes.
This project is also recommended in social spheres for the long-distant transfer of sound data
from one user to another.
REFERENCES
[1] http://en.wikipedia.org “ESP8266”, Article, last consultation on the 14/06/2019.
[3] Geekstips.com, “ESP8266 Arduino tutorial – WiFi module complete review”, 14/06/2019.
[5] EVOTHINGS NAVIGATION, “ How to connect your phone to your ESP8266 module”,
Research Engine, 14/06/2019
[6] Luka RUGGERI “Top 5 wireless ways to communicate with your controller”, OPEN
ELECTRONICS, on March 3 2015.
[11] Rabbit, “An Introduction to WiFi”, PRODUCT MANUAL, Part Number 019-0170
•090409–B Printed in U.S.A. Digi International Inc. © 2007-2008 All rights reserved.
APPENDIX
[Appendix A]: Schematic of the ESP8266 (ESP-01) WiFi module
[Appendix B]: Arduino code for serial communication between the two ESP8266 WiFi modules
(AP code)
/* Create a WiFi access point and provide a web server on it. */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#ifndef APSSID
#define APSSID "ESPap"
#define APPSK "thereisnospoon"
#endif
/* Set these to your desired credentials. */
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 33
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
delay(5000);
return;
}
// This will send a string to the server
Serial.println("sending data to server");
if (client.connected()) {
client.println("hello from ESP8266");
}
// wait for data to be available
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 36
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
delay(60000);
return;
}
}
// Read all the lines of the reply from server and print them to Serial
Serial.println("receiving from remote server");
// not testing 'client.connected()' since we do not need to send data here
while (client.available()) {
char ch = static_cast<char>(client.read());
Serial.print(ch);
}
// Close the connection
Serial.println();
Serial.println("closing connection");
client.stop();
delay(300000); // execute once every 5 minutes, don't flood remote service
}
[Appendix D]: Arduino code for audio signal transmission through ESP8266 WiFi module
// Based on ESP_MCP3201_SPI
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include "wifi_params.h"
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
WiFiUDP udp;
const int udp_recv_port = 45990; // for command&control
uint32_t send_sound_util = 0; // date until sound transmission ends after an envelope threshold has
triggered sound transmission
int enable_highpass_filter = 0;
static inline void setDataBits(uint16_t bits) {
const uint32_t mask = ~((SPIMMOSI << SPILMOSI) | (SPIMMISO << SPILMISO));
bits--;
SPI1U1 = ((SPI1U1 & mask) | ((bits << SPILMOSI) | (bits << SPILMISO)));
}
void spiBegin(void)
{
SPI.begin();
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV8);
SPI.setHwCs(1);
setDataBits(16);
}
#define ICACHE_RAM_ATTR __attribute__((section(".iram.text")))
/* SPI code based on the SPI library */
static inline ICACHE_RAM_ATTR uint16_t transfer16(void) {
union {
uint16_t val;
struct {
uint8_t lsb;
uint8_t msb;
};
} out;
// Transfer 16 bits at once, leaving HW CS low for the whole 16 bits
while(SPI1CMD & SPIBUSY) {}
SPI1W0 = 0;
SPI1CMD |= SPIBUSY;
{
// Disable timer when an OTA happens
timer1_detachInterrupt();
timer1_disable();
}
void ota_onprogress(unsigned int sz, unsigned int total)
{
Serial.print("OTA: "); Serial.print(sz); Serial.print("/"); Serial.print(total);
Serial.print("="); Serial.print(100*sz/total); Serial.println("%%");
}
void ota_onerror(ota_error_t err)
{
Serial.print("OTA ERROR:"); Serial.println((int)err);
}
void setup(void)
{
Serial.begin(115200);
Serial.println("I was built on " __DATE__ " at " __TIME__ "");
WiFi.setOutputPower(10); // reduce power to 10dBm = 10mW
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to wifi SSID ");
Serial.print(ssid);
// Wait for connection
int now = millis();
while (WiFi.status() != WL_CONNECTED && (millis() - now) < 10000) {
delay(500);
Serial.print(".");
}
if (WiFi.status() != WL_CONNECTED) {
envelope_value += rectified;
// delta7-compress the data
writeptr = delta7_sample(last, readptr, writeptr);
last = val;
}
accum_silence /= number_of_samples;
envelope_value /= number_of_samples;
silence_value = (SILENCE_EMA_WEIGHT * silence_value + accum_silence) /
(SILENCE_EMA_WEIGHT + 1);
envelope_value = envelope_value;
if (envelope_value > envelope_threshold) {
send_sound_util = millis() + 15000;
}
if (millis() < send_sound_util) {
udp.beginPacket(IP_target, udp_target_port);
udp.write((const uint8_t *)(&adc_buf[!current_adc_buf][0]), writeptr - (uint8_t
*)&adc_buf[!current_adc_buf][0]);
udp.endPacket();
}
send_samples_now = 0;
Serial.print("Silence val "); Serial.print(silence_value); Serial.print(" envelope val ");
Serial.print(envelope_value);
Serial.print("delay "); Serial.print(millis() - now);
Serial.println("");
}
if (udp.parsePacket()) {
// Command and control packets
char buf[32];
char *ptr = &buf[0];
udp.read(&buf[0], 31);
buf[31] = 0;
#define MATCHSTR(X,Y) !strncmp(X, Y, strlen(Y))
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 45
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
udp.beginPacket(udp.remoteIP(), udp.remotePort());
if (MATCHSTR(buf, "target PC")) {
// Direct sound to PC
IP_target = IP_target_PC;
udp.print("target PC");
} else if (MATCHSTR(buf, "target dev")) {
// Direct sound to device
IP_target = IP_target_device;
udp.print("target dev");
} else if (MATCHSTR(buf, "threshold ")) {
// Modify envelope threshold
ptr += strlen("threshold ");
envelope_threshold = atoi(ptr);
udp.print("threshold "); udp.println(envelope_threshold);
} else if (MATCHSTR(buf, "sendnow")) {
send_sound_util = millis() + 15000;
udp.print("sending for 15 sec");
} else if (MATCHSTR(buf, "filter")) {
enable_highpass_filter = !enable_highpass_filter;
if (enable_highpass_filter) {
udp.print("enabled");
} else {
udp.print("disabled");
}
udp.println(" highpass filter");
} else {
udp.print("unknown command "); udp.println(buf);
}
udp.endPacket();
}
[Appendix E]: Arduino code for audio signal reception through ESP8266 WiFi module
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include "ESP8266mDNS.h"
#include <ArduinoOTA.h>
#include "wifi_params.h"
const IPAddress softAP_myaddress(192, 168, 0, 13);
const int mySDA = D7;
const int mySCL = D6;
const int AMPLI_MUTE_PIN = D2;
const int AMPLI_SHUTDOWN_PIN = D1;
const int RIGHT_BTN = D3;
const int LEFT_BTN = D4;
const int LED1 = D8;
const int udp_recv_port = 45990;
WiFiUDP udp;
TwoWire i2c;
#define NB_DATA_BUFS 5
uint16_t data_buf[NB_DATA_BUFS][700]; // data buffer, N buffered
unsigned int current_play_data_buf; // current data buf being played
unsigned int play_data_buf_pos; // position in the ADC data buffer
SDA_HIGH();
if (SDA_READ() == 0) return false;
SDA_LOW();
return true;
}
static inline ICACHE_RAM_ATTR bool twi_write_stop(void){
uint32_t i = 0;
SCL_LOW();
SDA_LOW();
SCL_HIGH();
while (SCL_READ() == 0 && (i++) < twi_clockStretchLimit); // Clock stretching
SDA_HIGH();
return true;
}
static inline ICACHE_RAM_ATTR bool twi_write_bit(bool bit) {
uint32_t i = 0;
SCL_LOW();
if (bit) SDA_HIGH();
else SDA_LOW();
twi_delay(twi_dcount+1);
SCL_HIGH();
while (SCL_READ() == 0 && (i++) < twi_clockStretchLimit);// Clock stretching
return true;
}
static inline ICACHE_RAM_ATTR bool twi_read_bit(void) {
uint32_t i = 0;
SCL_LOW();
SDA_HIGH();
twi_delay(twi_dcount+2);
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 49
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
SCL_HIGH();
while (SCL_READ() == 0 && (i++) < twi_clockStretchLimit);// Clock stretching
bool bit = SDA_READ();
return bit;
}
static inline ICACHE_RAM_ATTR bool twi_write_byte(unsigned char byte) {
unsigned char bit;
for (bit = 0; bit < 8; bit++) {
twi_write_bit(byte & 0x80);
byte <<= 1;
}
return !twi_read_bit();//NACK/ACK
}
static inline ICACHE_RAM_ATTR unsigned char twi_read_byte(bool nack) {
unsigned char byte = 0;
unsigned char bit;
for (bit = 0; bit < 8; bit++) byte = (byte << 1) | twi_read_bit();
twi_write_bit(nack);
return byte;
}
unsigned char inline ICACHE_RAM_ATTR mytwi_writeTo(unsigned char address, unsigned
char * buf, unsigned int len, unsigned char sendStop){
unsigned int i;
if(!twi_write_start()) return 4;//line busy
if(!twi_write_byte(((address << 1) | 0) & 0xFF)) {
if (sendStop) twi_write_stop();
return 2; //received NACK on transmit of address
}
for(i=0; i<len; i++) {
if(!twi_write_byte(buf[i])) {
if (sendStop) twi_write_stop();
return 3;//received NACK on transmit of data
}
}
if(sendStop) twi_write_stop();
i = 0;
while(SDA_READ() == 0 && (i++) < 10){
SCL_LOW();
SCL_HIGH();
}
return 0;
}
static inline ICACHE_RAM_ATTR uint8_t DAC(uint16_t value)
{
/* value is 76543210 XXXXBA98
per the datasheet for fast write:
1 1 0 0 A2 A1 A0 0 <ACK> 0 0 PD1 PD0 D11 D10 D9 D8 <ACK> D7 D6 D5 D4 D3 D2 D1
D0 <ACK>
*/
uint8_t buf[2] = { (value >> 8) & 0x0F, (value & 0xFF) };
int ret = mytwi_writeTo(0x60, buf, 2, true);
return ret;
}
void ICACHE_RAM_ATTR playsample_isr(void)
{
if (play_waiting) {
return;
}
DAC(data_buf[current_play_data_buf][play_data_buf_pos]);
play_data_buf_pos++;
if (play_data_buf_pos >= sizeof(data_buf[0])/sizeof(data_buf[0][0])) {
play_data_buf_pos = 0;
current_play_data_buf++;
if (current_play_data_buf == NB_DATA_BUFS) {
current_play_data_buf = 0;
}
if (current_play_data_buf == current_recv_data_buf) {
play_waiting = true;
play_waiting_at = micros();
}
}
}
void ota_onstart(void)
{
// Disable timer when an OTA happens
timer1_detachInterrupt();
timer1_disable();
}
void ota_onprogress(unsigned int sz, unsigned int total)
{
Serial.print("OTA: "); Serial.print(sz); Serial.print("/"); Serial.print(total);
Serial.print("="); Serial.print(100*sz/total); Serial.println("%");
}
void ota_onerror(ota_error_t err)
{
Serial.print("OTA ERROR:"); Serial.println((int)err);
}
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 52
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
void left_btn_intr()
{
left_btn_pressed = 1;
}
void right_btn_intr()
{
right_btn_pressed = 1;
}
void setup ( void )
{
Serial.begin ( 115200 );
Serial.println("I was built on " __DATE__ " at " __TIME__ "");
i2c.begin(mySDA, mySCL);
i2c.setClock(400000);
WiFi.mode(WIFI_STA);
bool found = false;
int n = WiFi.scanNetworks();
for (int i = 0; i < n; i++) {
if (WiFi.SSID(i).equals(ssid)) {
found = true;
break;
}
}
if (!found) {
Serial.println("No wifi network found, starting softAP\n");
WiFi.disconnect();
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(softAP_myaddress, softAP_myaddress, IPAddress(255,255,255,0));
WiFi.softAP(softap_ssid, softap_password);
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 53
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
} else {
WiFi.begin(ssid, password);
WiFi.setSleepMode(WIFI_MODEM_SLEEP);
Serial.print("Connecting to wifi");
int now = millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
Serial.println ( "" );
Serial.print ( "Cnnectd to " );
Serial.println ( ssid );
Serial.print ( "IP " );
Serial.println ( WiFi.localIP() );
ArduinoOTA.onStart(ota_onstart);
ArduinoOTA.onError(ota_onerror);
ArduinoOTA.onProgress(ota_onprogress);
ArduinoOTA.setHostname("bb-recv");
ArduinoOTA.begin();
timer1_isr_init();
timer1_attachInterrupt(playsample_isr);
timer1_enable(TIM_DIV16, TIM_EDGE, TIM_LOOP);
timer1_write(clockCyclesPerMicrosecond() / 16 * 50); //50us = 20 kHz sampling freq
udp.begin(udp_recv_port);
pinMode(AMPLI_MUTE_PIN, OUTPUT);
pinMode(AMPLI_SHUTDOWN_PIN, OUTPUT);
digitalWrite(AMPLI_SHUTDOWN_PIN, 0);
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 54
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
digitalWrite(AMPLI_MUTE_PIN, 0);
pinMode(LEFT_BTN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(LEFT_BTN), left_btn_intr, FALLING);
pinMode(RIGHT_BTN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(RIGHT_BTN), right_btn_intr, FALLING);
pinMode(LED1, OUTPUT);
digitalWrite(LED1, 0);
}
int do_undelta7(const uint8_t *val, int sz, uint16_t *out)
{
// Implement delta 7 decompression.
// First bit = 0 <=> uncompressed 15 bits following
// First bit = 1 <=> 7 bits follow representing delta
// must switch to big endian...
uint16_t last = 0;
uint8_t *ptr = (uint8_t *)&out[0];
const uint8_t *start = ptr;
for (int i = 0; i < sz; i++) {
uint16_t *ptr16 = (uint16_t *)ptr;
const int8_t firstbyte = val[i];
if (firstbyte & 0x80) {
// Delta7 compressed
// byte is CSMMMMMM
int8_t delta = firstbyte & 0x3F;
if (firstbyte & 0x40) {
delta = -delta;
}
const uint16_t value = last + delta;
*ptr16 = value;
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 55
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
ptr += 2;
last = value;
} else {
// uncompressed -- switch bytes back to LE
*ptr++ = val[i+1];
*ptr++ = val[i];
last = val[i+1] | val[i] << 8;
i++;
}
}
return ptr - start;
}
void loop ( void )
{
ArduinoOTA.handle();
int sz = udp.parsePacket();
if (sz) {
uint8_t buf[sz];
udp.read(&buf[0], sz);
current_recv_data_buf++;
if (current_recv_data_buf == NB_DATA_BUFS) {
current_recv_data_buf = 0;
if (current_recv_data_buf == current_play_data_buf && !play_waiting) {
Serial.println("buffer overflow when receiving");
}
}
do_undelta7(buf, sz, &data_buf[current_recv_data_buf][0]);
if (play_waiting) {
Serial.print("Restarting play, was waiting (us)"); Serial.println(micros() - play_waiting_at);
DISSERTATION/ BATCHANOU TATAP PERETS ARNAUD/ FE15A031/LEVEL 500/ UB/FET/2018-2019
Page | 56
INVESTIGATION OF WI-FI (ESP8266) MODULE AND APPLICATION TO AN AUDIO
SIGNAL TRANSMISSION
udp.beginPacket(bcast, 45990);
udp.write("sendnow");
udp.endPacket();
right_btn_pressed = 0;
}
// If the amplifier is stopped, add a delay for power saving
if (amplifier_stopped) {
delay(10);
}
}
[Appendix F]: AT commands for the ESP8266