diff --git a/docs/library/pyb.ADC.rst b/docs/library/pyb.ADC.rst index 05aaa50150..a95f2d537c 100644 --- a/docs/library/pyb.ADC.rst +++ b/docs/library/pyb.ADC.rst @@ -4,173 +4,164 @@ class ADC -- analog to digital conversion ========================================= -.. only:: port_pyboard +Usage:: - Usage:: + import pyb - import pyb - - adc = pyb.ADC(pin) # create an analog object from a pin - val = adc.read() # read an analog value - - adc = pyb.ADCAll(resolution) # create an ADCAll object - adc = pyb.ADCAll(resolution, mask) # create an ADCAll object for selected analog channels - val = adc.read_channel(channel) # read the given channel - val = adc.read_core_temp() # read MCU temperature - val = adc.read_core_vbat() # read MCU VBAT - val = adc.read_core_vref() # read MCU VREF - val = adc.read_vref() # read MCU supply voltage + adc = pyb.ADC(pin) # create an analog object from a pin + val = adc.read() # read an analog value + + adc = pyb.ADCAll(resolution) # create an ADCAll object + adc = pyb.ADCAll(resolution, mask) # create an ADCAll object for selected analog channels + val = adc.read_channel(channel) # read the given channel + val = adc.read_core_temp() # read MCU temperature + val = adc.read_core_vbat() # read MCU VBAT + val = adc.read_core_vref() # read MCU VREF + val = adc.read_vref() # read MCU supply voltage Constructors ------------ +.. class:: pyb.ADC(pin) -.. only:: port_pyboard - - .. class:: pyb.ADC(pin) - - Create an ADC object associated with the given pin. - This allows you to then read analog values on that pin. + Create an ADC object associated with the given pin. + This allows you to then read analog values on that pin. Methods ------- -.. only:: port_pyboard +.. method:: ADC.read() - .. method:: ADC.read() + Read the value on the analog pin and return it. The returned value + will be between 0 and 4095. - Read the value on the analog pin and return it. The returned value - will be between 0 and 4095. +.. method:: ADC.read_timed(buf, timer) - .. method:: ADC.read_timed(buf, timer) - - Read analog values into ``buf`` at a rate set by the ``timer`` object. + Read analog values into ``buf`` at a rate set by the ``timer`` object. - ``buf`` can be bytearray or array.array for example. The ADC values have - 12-bit resolution and are stored directly into ``buf`` if its element size is - 16 bits or greater. If ``buf`` has only 8-bit elements (eg a bytearray) then - the sample resolution will be reduced to 8 bits. + ``buf`` can be bytearray or array.array for example. The ADC values have + 12-bit resolution and are stored directly into ``buf`` if its element size is + 16 bits or greater. If ``buf`` has only 8-bit elements (eg a bytearray) then + the sample resolution will be reduced to 8 bits. - ``timer`` should be a Timer object, and a sample is read each time the timer - triggers. The timer must already be initialised and running at the desired - sampling frequency. + ``timer`` should be a Timer object, and a sample is read each time the timer + triggers. The timer must already be initialised and running at the desired + sampling frequency. - To support previous behaviour of this function, ``timer`` can also be an - integer which specifies the frequency (in Hz) to sample at. In this case - Timer(6) will be automatically configured to run at the given frequency. + To support previous behaviour of this function, ``timer`` can also be an + integer which specifies the frequency (in Hz) to sample at. In this case + Timer(6) will be automatically configured to run at the given frequency. - Example using a Timer object (preferred way):: + Example using a Timer object (preferred way):: - adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 - tim = pyb.Timer(6, freq=10) # create a timer running at 10Hz - buf = bytearray(100) # creat a buffer to store the samples - adc.read_timed(buf, tim) # sample 100 values, taking 10s + adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 + tim = pyb.Timer(6, freq=10) # create a timer running at 10Hz + buf = bytearray(100) # creat a buffer to store the samples + adc.read_timed(buf, tim) # sample 100 values, taking 10s - Example using an integer for the frequency:: + Example using an integer for the frequency:: - adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 - buf = bytearray(100) # create a buffer of 100 bytes - adc.read_timed(buf, 10) # read analog values into buf at 10Hz - # this will take 10 seconds to finish - for val in buf: # loop over all values - print(val) # print the value out + adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19 + buf = bytearray(100) # create a buffer of 100 bytes + adc.read_timed(buf, 10) # read analog values into buf at 10Hz + # this will take 10 seconds to finish + for val in buf: # loop over all values + print(val) # print the value out - This function does not allocate any heap memory. It has blocking behaviour: - it does not return to the calling program until the buffer is full. + This function does not allocate any heap memory. It has blocking behaviour: + it does not return to the calling program until the buffer is full. - .. method:: ADC.read_timed_multi((adcx, adcy, ...), (bufx, bufy, ...), timer) +.. method:: ADC.read_timed_multi((adcx, adcy, ...), (bufx, bufy, ...), timer) - This is a static method. It can be used to extract relative timing or - phase data from multiple ADC's. + This is a static method. It can be used to extract relative timing or + phase data from multiple ADC's. - It reads analog values from multiple ADC's into buffers at a rate set by - the *timer* object. Each time the timer triggers a sample is rapidly - read from each ADC in turn. + It reads analog values from multiple ADC's into buffers at a rate set by + the *timer* object. Each time the timer triggers a sample is rapidly + read from each ADC in turn. - ADC and buffer instances are passed in tuples with each ADC having an - associated buffer. All buffers must be of the same type and length and - the number of buffers must equal the number of ADC's. + ADC and buffer instances are passed in tuples with each ADC having an + associated buffer. All buffers must be of the same type and length and + the number of buffers must equal the number of ADC's. - Buffers can be ``bytearray`` or ``array.array`` for example. The ADC values - have 12-bit resolution and are stored directly into the buffer if its element - size is 16 bits or greater. If buffers have only 8-bit elements (eg a - ``bytearray``) then the sample resolution will be reduced to 8 bits. + Buffers can be ``bytearray`` or ``array.array`` for example. The ADC values + have 12-bit resolution and are stored directly into the buffer if its element + size is 16 bits or greater. If buffers have only 8-bit elements (eg a + ``bytearray``) then the sample resolution will be reduced to 8 bits. - *timer* must be a Timer object. The timer must already be initialised - and running at the desired sampling frequency. + *timer* must be a Timer object. The timer must already be initialised + and running at the desired sampling frequency. - Example reading 3 ADC's:: + Example reading 3 ADC's:: - adc0 = pyb.ADC(pyb.Pin.board.X1) # Create ADC's - adc1 = pyb.ADC(pyb.Pin.board.X2) - adc2 = pyb.ADC(pyb.Pin.board.X3) - tim = pyb.Timer(8, freq=100) # Create timer - rx0 = array.array('H', (0 for i in range(100))) # ADC buffers of - rx1 = array.array('H', (0 for i in range(100))) # 100 16-bit words - rx2 = array.array('H', (0 for i in range(100))) - # read analog values into buffers at 100Hz (takes one second) - pyb.ADC.read_timed_multi((adc0, adc1, adc2), (rx0, rx1, rx2), tim) - for n in range(len(rx0)): - print(rx0[n], rx1[n], rx2[n]) + adc0 = pyb.ADC(pyb.Pin.board.X1) # Create ADC's + adc1 = pyb.ADC(pyb.Pin.board.X2) + adc2 = pyb.ADC(pyb.Pin.board.X3) + tim = pyb.Timer(8, freq=100) # Create timer + rx0 = array.array('H', (0 for i in range(100))) # ADC buffers of + rx1 = array.array('H', (0 for i in range(100))) # 100 16-bit words + rx2 = array.array('H', (0 for i in range(100))) + # read analog values into buffers at 100Hz (takes one second) + pyb.ADC.read_timed_multi((adc0, adc1, adc2), (rx0, rx1, rx2), tim) + for n in range(len(rx0)): + print(rx0[n], rx1[n], rx2[n]) - This function does not allocate any heap memory. It has blocking behaviour: - it does not return to the calling program until the buffers are full. + This function does not allocate any heap memory. It has blocking behaviour: + it does not return to the calling program until the buffers are full. - The function returns ``True`` if all samples were acquired with correct - timing. At high sample rates the time taken to acquire a set of samples - can exceed the timer period. In this case the function returns ``False``, - indicating a loss of precision in the sample interval. In extreme cases - samples may be missed. + The function returns ``True`` if all samples were acquired with correct + timing. At high sample rates the time taken to acquire a set of samples + can exceed the timer period. In this case the function returns ``False``, + indicating a loss of precision in the sample interval. In extreme cases + samples may be missed. - The maximum rate depends on factors including the data width and the - number of ADC's being read. In testing two ADC's were sampled at a timer - rate of 210kHz without overrun. Samples were missed at 215kHz. For three - ADC's the limit is around 140kHz, and for four it is around 110kHz. - At high sample rates disabling interrupts for the duration can reduce the - risk of sporadic data loss. + The maximum rate depends on factors including the data width and the + number of ADC's being read. In testing two ADC's were sampled at a timer + rate of 210kHz without overrun. Samples were missed at 215kHz. For three + ADC's the limit is around 140kHz, and for four it is around 110kHz. + At high sample rates disabling interrupts for the duration can reduce the + risk of sporadic data loss. The ADCAll Object ----------------- -.. only:: port_pyboard +Instantiating this changes all masked ADC pins to analog inputs. The preprocessed MCU temperature, +VREF and VBAT data can be accessed on ADC channels 16, 17 and 18 respectively. +Appropriate scaling is handled according to reference voltage used (usually 3.3V). +The temperature sensor on the chip is factory calibrated and allows to read the die temperature +to +/- 1 degree centigrade. Although this sounds pretty accurate, don't forget that the MCU's internal +temperature is measured. Depending on processing loads and I/O subsystems active the die temperature +may easily be tens of degrees above ambient temperature. On the other hand a pyboard woken up after a +long standby period will show correct ambient temperature within limits mentioned above. - Instantiating this changes all masked ADC pins to analog inputs. The preprocessed MCU temperature, - VREF and VBAT data can be accessed on ADC channels 16, 17 and 18 respectively. - Appropriate scaling is handled according to reference voltage used (usually 3.3V). - The temperature sensor on the chip is factory calibrated and allows to read the die temperature - to +/- 1 degree centigrade. Although this sounds pretty accurate, don't forget that the MCU's internal - temperature is measured. Depending on processing loads and I/O subsystems active the die temperature - may easily be tens of degrees above ambient temperature. On the other hand a pyboard woken up after a - long standby period will show correct ambient temperature within limits mentioned above. +The ``ADCAll`` ``read_core_vbat()``, ``read_vref()`` and ``read_core_vref()`` methods read +the backup battery voltage, reference voltage and the (1.21V nominal) reference voltage using the +actual supply as a reference. All results are floating point numbers giving direct voltage values. - The ``ADCAll`` ``read_core_vbat()``, ``read_vref()`` and ``read_core_vref()`` methods read - the backup battery voltage, reference voltage and the (1.21V nominal) reference voltage using the - actual supply as a reference. All results are floating point numbers giving direct voltage values. +``read_core_vbat()`` returns the voltage of the backup battery. This voltage is also adjusted according +to the actual supply voltage. To avoid analog input overload the battery voltage is measured +via a voltage divider and scaled according to the divider value. To prevent excessive loads +to the backup battery, the voltage divider is only active during ADC conversion. - ``read_core_vbat()`` returns the voltage of the backup battery. This voltage is also adjusted according - to the actual supply voltage. To avoid analog input overload the battery voltage is measured - via a voltage divider and scaled according to the divider value. To prevent excessive loads - to the backup battery, the voltage divider is only active during ADC conversion. +``read_vref()`` is evaluated by measuring the internal voltage reference and backscale it using +factory calibration value of the internal voltage reference. In most cases the reading would be close +to 3.3V. If the pyboard is operated from a battery, the supply voltage may drop to values below 3.3V. +The pyboard will still operate fine as long as the operating conditions are met. With proper settings +of MCU clock, flash access speed and programming mode it is possible to run the pyboard down to +2 V and still get useful ADC conversion. - ``read_vref()`` is evaluated by measuring the internal voltage reference and backscale it using - factory calibration value of the internal voltage reference. In most cases the reading would be close - to 3.3V. If the pyboard is operated from a battery, the supply voltage may drop to values below 3.3V. - The pyboard will still operate fine as long as the operating conditions are met. With proper settings - of MCU clock, flash access speed and programming mode it is possible to run the pyboard down to - 2 V and still get useful ADC conversion. +It is very important to make sure analog input voltages never exceed actual supply voltage. - It is very important to make sure analog input voltages never exceed actual supply voltage. +Other analog input channels (0..15) will return unscaled integer values according to the selected +precision. - Other analog input channels (0..15) will return unscaled integer values according to the selected - precision. +To avoid unwanted activation of analog inputs (channel 0..15) a second parameter can be specified. +This parameter is a binary pattern where each requested analog input has the corresponding bit set. +The default value is 0xffffffff which means all analog inputs are active. If just the internal +channels (16..18) are required, the mask value should be 0x70000. - To avoid unwanted activation of analog inputs (channel 0..15) a second parameter can be specified. - This parameter is a binary pattern where each requested analog input has the corresponding bit set. - The default value is 0xffffffff which means all analog inputs are active. If just the internal - channels (16..18) are required, the mask value should be 0x70000. - - Example:: +Example:: - adcall = pyb.ADCAll(12, 0x70000) # 12 bit resolution, internal channels - temp = adcall.read_core_temp() + adcall = pyb.ADCAll(12, 0x70000) # 12 bit resolution, internal channels + temp = adcall.read_core_temp() diff --git a/docs/library/pyb.I2C.rst b/docs/library/pyb.I2C.rst index 7400318902..d549c1a812 100644 --- a/docs/library/pyb.I2C.rst +++ b/docs/library/pyb.I2C.rst @@ -10,78 +10,72 @@ level it consists of 2 wires: SCL and SDA, the clock and data lines respectively I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on. -.. only:: port_pyboard +Example:: - Example:: + from pyb import I2C - from pyb import I2C - - i2c = I2C(1) # create on bus 1 - i2c = I2C(1, I2C.MASTER) # create and init as a master - i2c.init(I2C.MASTER, baudrate=20000) # init as a master - i2c.init(I2C.SLAVE, addr=0x42) # init as a slave with given address - i2c.deinit() # turn off the peripheral + i2c = I2C(1) # create on bus 1 + i2c = I2C(1, I2C.MASTER) # create and init as a master + i2c.init(I2C.MASTER, baudrate=20000) # init as a master + i2c.init(I2C.SLAVE, addr=0x42) # init as a slave with given address + i2c.deinit() # turn off the peripheral Printing the i2c object gives you information about its configuration. -.. only:: port_pyboard +The basic methods are send and recv:: - The basic methods are send and recv:: + i2c.send('abc') # send 3 bytes + i2c.send(0x42) # send a single byte, given by the number + data = i2c.recv(3) # receive 3 bytes - i2c.send('abc') # send 3 bytes - i2c.send(0x42) # send a single byte, given by the number - data = i2c.recv(3) # receive 3 bytes - - To receive inplace, first create a bytearray:: +To receive inplace, first create a bytearray:: - data = bytearray(3) # create a buffer - i2c.recv(data) # receive 3 bytes, writing them into data + data = bytearray(3) # create a buffer + i2c.recv(data) # receive 3 bytes, writing them into data - You can specify a timeout (in ms):: +You can specify a timeout (in ms):: - i2c.send(b'123', timeout=2000) # timeout after 2 seconds + i2c.send(b'123', timeout=2000) # timeout after 2 seconds - A master must specify the recipient's address:: +A master must specify the recipient's address:: - i2c.init(I2C.MASTER) - i2c.send('123', 0x42) # send 3 bytes to slave with address 0x42 - i2c.send(b'456', addr=0x42) # keyword for address + i2c.init(I2C.MASTER) + i2c.send('123', 0x42) # send 3 bytes to slave with address 0x42 + i2c.send(b'456', addr=0x42) # keyword for address - Master also has other methods:: +Master also has other methods:: - i2c.is_ready(0x42) # check if slave 0x42 is ready - i2c.scan() # scan for slaves on the bus, returning - # a list of valid addresses - i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of slave 0x42, - # starting at address 2 in the slave - i2c.mem_write('abc', 0x42, 2, timeout=1000) # write 'abc' (3 bytes) to memory of slave 0x42 - # starting at address 2 in the slave, timeout after 1 second + i2c.is_ready(0x42) # check if slave 0x42 is ready + i2c.scan() # scan for slaves on the bus, returning + # a list of valid addresses + i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of slave 0x42, + # starting at address 2 in the slave + i2c.mem_write('abc', 0x42, 2, timeout=1000) # write 'abc' (3 bytes) to memory of slave 0x42 + # starting at address 2 in the slave, timeout after 1 second Constructors ------------ -.. only:: port_pyboard +.. class:: pyb.I2C(bus, ...) - .. class:: pyb.I2C(bus, ...) + Construct an I2C object on the given bus. ``bus`` can be 1 or 2, 'X' or + 'Y'. With no additional parameters, the I2C object is created but not + initialised (it has the settings from the last initialisation of + the bus, if any). If extra arguments are given, the bus is initialised. + See ``init`` for parameters of initialisation. - Construct an I2C object on the given bus. ``bus`` can be 1 or 2, 'X' or - 'Y'. With no additional parameters, the I2C object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. + The physical pins of the I2C busses on Pyboards V1.0 and V1.1 are: - The physical pins of the I2C busses on Pyboards V1.0 and V1.1 are: + - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` + - ``I2C(2)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PB10, PB11)`` - - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` - - ``I2C(2)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PB10, PB11)`` - - On the Pyboard Lite: - - - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` - - ``I2C(3)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PA8, PB8)`` - - Calling the constructor with 'X' or 'Y' enables portability between Pyboard - types. + On the Pyboard Lite: + + - ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)`` + - ``I2C(3)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PA8, PB8)`` + + Calling the constructor with 'X' or 'Y' enables portability between Pyboard + types. Methods ------- @@ -90,71 +84,69 @@ Methods Turn off the I2C bus. -.. only:: port_pyboard +.. method:: I2C.init(mode, \*, addr=0x12, baudrate=400000, gencall=False, dma=False) - .. method:: I2C.init(mode, \*, addr=0x12, baudrate=400000, gencall=False, dma=False) + Initialise the I2C bus with the given parameters: - Initialise the I2C bus with the given parameters: + - ``mode`` must be either ``I2C.MASTER`` or ``I2C.SLAVE`` + - ``addr`` is the 7-bit address (only sensible for a slave) + - ``baudrate`` is the SCL clock rate (only sensible for a master) + - ``gencall`` is whether to support general call mode + - ``dma`` is whether to allow the use of DMA for the I2C transfers (note + that DMA transfers have more precise timing but currently do not handle bus + errors properly) - - ``mode`` must be either ``I2C.MASTER`` or ``I2C.SLAVE`` - - ``addr`` is the 7-bit address (only sensible for a slave) - - ``baudrate`` is the SCL clock rate (only sensible for a master) - - ``gencall`` is whether to support general call mode - - ``dma`` is whether to allow the use of DMA for the I2C transfers (note - that DMA transfers have more precise timing but currently do not handle bus - errors properly) +.. method:: I2C.is_ready(addr) - .. method:: I2C.is_ready(addr) + Check if an I2C device responds to the given address. Only valid when in master mode. - Check if an I2C device responds to the given address. Only valid when in master mode. +.. method:: I2C.mem_read(data, addr, memaddr, \*, timeout=5000, addr_size=8) - .. method:: I2C.mem_read(data, addr, memaddr, \*, timeout=5000, addr_size=8) + Read from the memory of an I2C device: - Read from the memory of an I2C device: + - ``data`` can be an integer (number of bytes to read) or a buffer to read into + - ``addr`` is the I2C device address + - ``memaddr`` is the memory location within the I2C device + - ``timeout`` is the timeout in milliseconds to wait for the read + - ``addr_size`` selects width of memaddr: 8 or 16 bits - - ``data`` can be an integer (number of bytes to read) or a buffer to read into - - ``addr`` is the I2C device address - - ``memaddr`` is the memory location within the I2C device - - ``timeout`` is the timeout in milliseconds to wait for the read - - ``addr_size`` selects width of memaddr: 8 or 16 bits + Returns the read data. + This is only valid in master mode. - Returns the read data. - This is only valid in master mode. +.. method:: I2C.mem_write(data, addr, memaddr, \*, timeout=5000, addr_size=8) - .. method:: I2C.mem_write(data, addr, memaddr, \*, timeout=5000, addr_size=8) + Write to the memory of an I2C device: - Write to the memory of an I2C device: + - ``data`` can be an integer or a buffer to write from + - ``addr`` is the I2C device address + - ``memaddr`` is the memory location within the I2C device + - ``timeout`` is the timeout in milliseconds to wait for the write + - ``addr_size`` selects width of memaddr: 8 or 16 bits - - ``data`` can be an integer or a buffer to write from - - ``addr`` is the I2C device address - - ``memaddr`` is the memory location within the I2C device - - ``timeout`` is the timeout in milliseconds to wait for the write - - ``addr_size`` selects width of memaddr: 8 or 16 bits + Returns ``None``. + This is only valid in master mode. - Returns ``None``. - This is only valid in master mode. +.. method:: I2C.recv(recv, addr=0x00, \*, timeout=5000) - .. method:: I2C.recv(recv, addr=0x00, \*, timeout=5000) + Receive data on the bus: - Receive data on the bus: + - ``recv`` can be an integer, which is the number of bytes to receive, + or a mutable buffer, which will be filled with received bytes + - ``addr`` is the address to receive from (only required in master mode) + - ``timeout`` is the timeout in milliseconds to wait for the receive - - ``recv`` can be an integer, which is the number of bytes to receive, - or a mutable buffer, which will be filled with received bytes - - ``addr`` is the address to receive from (only required in master mode) - - ``timeout`` is the timeout in milliseconds to wait for the receive - - Return value: if ``recv`` is an integer then a new buffer of the bytes received, - otherwise the same buffer that was passed in to ``recv``. + Return value: if ``recv`` is an integer then a new buffer of the bytes received, + otherwise the same buffer that was passed in to ``recv``. - .. method:: I2C.send(send, addr=0x00, \*, timeout=5000) +.. method:: I2C.send(send, addr=0x00, \*, timeout=5000) - Send data on the bus: + Send data on the bus: - - ``send`` is the data to send (an integer to send, or a buffer object) - - ``addr`` is the address to send to (only required in master mode) - - ``timeout`` is the timeout in milliseconds to wait for the send + - ``send`` is the data to send (an integer to send, or a buffer object) + - ``addr`` is the address to send to (only required in master mode) + - ``timeout`` is the timeout in milliseconds to wait for the send - Return value: ``None``. + Return value: ``None``. .. method:: I2C.scan() @@ -168,8 +160,6 @@ Constants for initialising the bus to master mode -.. only:: port_pyboard +.. data:: I2C.SLAVE - .. data:: I2C.SLAVE - - for initialising the bus to slave mode + for initialising the bus to slave mode diff --git a/docs/library/pyb.Pin.rst b/docs/library/pyb.Pin.rst index b766c5280c..07292f3440 100644 --- a/docs/library/pyb.Pin.rst +++ b/docs/library/pyb.Pin.rst @@ -10,68 +10,66 @@ digital logic level. For analog control of a pin, see the ADC class. Usage Model: -.. only:: port_pyboard +All Board Pins are predefined as pyb.Pin.board.Name:: - All Board Pins are predefined as pyb.Pin.board.Name:: - - x1_pin = pyb.Pin.board.X1 - - g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN) - - CPU pins which correspond to the board pins are available - as ``pyb.cpu.Name``. For the CPU pins, the names are the port letter - followed by the pin number. On the PYBv1.0, ``pyb.Pin.board.X1`` and - ``pyb.Pin.cpu.A0`` are the same pin. - - You can also use strings:: - - g = pyb.Pin('X1', pyb.Pin.OUT_PP) - - Users can add their own names:: - - MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 } - pyb.Pin.dict(MyMapperDict) - g = pyb.Pin("LeftMotorDir", pyb.Pin.OUT_OD) - - and can query mappings:: - - pin = pyb.Pin("LeftMotorDir") - - Users can also add their own mapping function:: - - def MyMapper(pin_name): - if pin_name == "LeftMotorDir": - return pyb.Pin.cpu.A0 - - pyb.Pin.mapper(MyMapper) - - So, if you were to call: ``pyb.Pin("LeftMotorDir", pyb.Pin.OUT_PP)`` - then ``"LeftMotorDir"`` is passed directly to the mapper function. - - To summarise, the following order determines how things get mapped into - an ordinal pin number: - - 1. Directly specify a pin object - 2. User supplied mapping function - 3. User supplied mapping (object must be usable as a dictionary key) - 4. Supply a string which matches a board pin - 5. Supply a string which matches a CPU port/pin - - You can set ``pyb.Pin.debug(True)`` to get some debug information about - how a particular object gets mapped to a pin. - - When a pin has the ``Pin.PULL_UP`` or ``Pin.PULL_DOWN`` pull-mode enabled, - that pin has an effective 40k Ohm resistor pulling it to 3V3 or GND - respectively (except pin Y5 which has 11k Ohm resistors). + x1_pin = pyb.Pin.board.X1 - Now every time a falling edge is seen on the gpio pin, the callback will be - executed. Caution: mechanical push buttons have "bounce" and pushing or - releasing a switch will often generate multiple edges. - See: http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed - explanation, along with various techniques for debouncing. + g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN) - All pin objects go through the pin mapper to come up with one of the - gpio pins. +CPU pins which correspond to the board pins are available +as ``pyb.cpu.Name``. For the CPU pins, the names are the port letter +followed by the pin number. On the PYBv1.0, ``pyb.Pin.board.X1`` and +``pyb.Pin.cpu.A0`` are the same pin. + +You can also use strings:: + + g = pyb.Pin('X1', pyb.Pin.OUT_PP) + +Users can add their own names:: + + MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 } + pyb.Pin.dict(MyMapperDict) + g = pyb.Pin("LeftMotorDir", pyb.Pin.OUT_OD) + +and can query mappings:: + + pin = pyb.Pin("LeftMotorDir") + +Users can also add their own mapping function:: + + def MyMapper(pin_name): + if pin_name == "LeftMotorDir": + return pyb.Pin.cpu.A0 + + pyb.Pin.mapper(MyMapper) + +So, if you were to call: ``pyb.Pin("LeftMotorDir", pyb.Pin.OUT_PP)`` +then ``"LeftMotorDir"`` is passed directly to the mapper function. + +To summarise, the following order determines how things get mapped into +an ordinal pin number: + +1. Directly specify a pin object +2. User supplied mapping function +3. User supplied mapping (object must be usable as a dictionary key) +4. Supply a string which matches a board pin +5. Supply a string which matches a CPU port/pin + +You can set ``pyb.Pin.debug(True)`` to get some debug information about +how a particular object gets mapped to a pin. + +When a pin has the ``Pin.PULL_UP`` or ``Pin.PULL_DOWN`` pull-mode enabled, +that pin has an effective 40k Ohm resistor pulling it to 3V3 or GND +respectively (except pin Y5 which has 11k Ohm resistors). + +Now every time a falling edge is seen on the gpio pin, the callback will be +executed. Caution: mechanical push buttons have "bounce" and pushing or +releasing a switch will often generate multiple edges. +See: http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed +explanation, along with various techniques for debouncing. + +All pin objects go through the pin mapper to come up with one of the +gpio pins. Constructors ------------ @@ -81,52 +79,48 @@ Constructors Create a new Pin object associated with the id. If additional arguments are given, they are used to initialise the pin. See :meth:`pin.init`. -.. only:: port_pyboard +Class methods +------------- - Class methods - ------------- +.. classmethod:: Pin.debug([state]) - .. classmethod:: Pin.debug([state]) - - Get or set the debugging state (``True`` or ``False`` for on or off). - - .. classmethod:: Pin.dict([dict]) - - Get or set the pin mapper dictionary. - - .. classmethod:: Pin.mapper([fun]) - - Get or set the pin mapper function. + Get or set the debugging state (``True`` or ``False`` for on or off). + +.. classmethod:: Pin.dict([dict]) + + Get or set the pin mapper dictionary. + +.. classmethod:: Pin.mapper([fun]) + + Get or set the pin mapper function. Methods ------- -.. only:: port_pyboard +.. method:: Pin.init(mode, pull=Pin.PULL_NONE, af=-1) - .. method:: Pin.init(mode, pull=Pin.PULL_NONE, af=-1) - - Initialise the pin: - - - ``mode`` can be one of: + Initialise the pin: - - ``Pin.IN`` - configure the pin for input; - - ``Pin.OUT_PP`` - configure the pin for output, with push-pull control; - - ``Pin.OUT_OD`` - configure the pin for output, with open-drain control; - - ``Pin.AF_PP`` - configure the pin for alternate function, pull-pull; - - ``Pin.AF_OD`` - configure the pin for alternate function, open-drain; - - ``Pin.ANALOG`` - configure the pin for analog. + - ``mode`` can be one of: - - ``pull`` can be one of: + - ``Pin.IN`` - configure the pin for input; + - ``Pin.OUT_PP`` - configure the pin for output, with push-pull control; + - ``Pin.OUT_OD`` - configure the pin for output, with open-drain control; + - ``Pin.AF_PP`` - configure the pin for alternate function, pull-pull; + - ``Pin.AF_OD`` - configure the pin for alternate function, open-drain; + - ``Pin.ANALOG`` - configure the pin for analog. - - ``Pin.PULL_NONE`` - no pull up or down resistors; - - ``Pin.PULL_UP`` - enable the pull-up resistor; - - ``Pin.PULL_DOWN`` - enable the pull-down resistor. + - ``pull`` can be one of: - - when mode is ``Pin.AF_PP`` or ``Pin.AF_OD``, then af can be the index or name - of one of the alternate functions associated with a pin. - - Returns: ``None``. + - ``Pin.PULL_NONE`` - no pull up or down resistors; + - ``Pin.PULL_UP`` - enable the pull-up resistor; + - ``Pin.PULL_DOWN`` - enable the pull-down resistor. + + - when mode is ``Pin.AF_PP`` or ``Pin.AF_OD``, then af can be the index or name + of one of the alternate functions associated with a pin. + + Returns: ``None``. .. method:: Pin.value([value]) @@ -137,47 +131,45 @@ Methods anything that converts to a boolean. If it converts to ``True``, the pin is set high, otherwise it is set low. -.. only:: port_pyboard +.. method:: Pin.__str__() - .. method:: Pin.__str__() - - Return a string describing the pin object. - - .. method:: Pin.af() - - Returns the currently configured alternate-function of the pin. The - integer returned will match one of the allowed constants for the af - argument to the init function. + Return a string describing the pin object. - .. method:: Pin.af_list() +.. method:: Pin.af() - Returns an array of alternate functions available for this pin. - - .. method:: Pin.gpio() - - Returns the base address of the GPIO block associated with this pin. - - .. method:: Pin.mode() - - Returns the currently configured mode of the pin. The integer returned - will match one of the allowed constants for the mode argument to the init - function. - - .. method:: Pin.name() + Returns the currently configured alternate-function of the pin. The + integer returned will match one of the allowed constants for the af + argument to the init function. - Get the pin name. +.. method:: Pin.af_list() - .. method:: Pin.names() - - Returns the cpu and board names for this pin. - - .. method:: Pin.pin() - - Get the pin number. - - .. method:: Pin.port() - - Get the pin port. + Returns an array of alternate functions available for this pin. + +.. method:: Pin.gpio() + + Returns the base address of the GPIO block associated with this pin. + +.. method:: Pin.mode() + + Returns the currently configured mode of the pin. The integer returned + will match one of the allowed constants for the mode argument to the init + function. + +.. method:: Pin.name() + + Get the pin name. + +.. method:: Pin.names() + + Returns the cpu and board names for this pin. + +.. method:: Pin.pin() + + Get the pin number. + +.. method:: Pin.port() + + Get the pin port. .. method:: Pin.pull() @@ -188,93 +180,89 @@ Methods Constants --------- -.. only:: port_pyboard +.. data:: Pin.AF_OD - .. data:: Pin.AF_OD - - initialise the pin to alternate-function mode with an open-drain drive - - .. data:: Pin.AF_PP - - initialise the pin to alternate-function mode with a push-pull drive - - .. data:: Pin.ANALOG - - initialise the pin to analog mode - - .. data:: Pin.IN - - initialise the pin to input mode - - .. data:: Pin.OUT_OD - - initialise the pin to output mode with an open-drain drive - - .. data:: Pin.OUT_PP - - initialise the pin to output mode with a push-pull drive - - .. data:: Pin.PULL_DOWN - - enable the pull-down resistor on the pin - - .. data:: Pin.PULL_NONE - - don't enable any pull up or down resistors on the pin - - .. data:: Pin.PULL_UP - - enable the pull-up resistor on the pin + initialise the pin to alternate-function mode with an open-drain drive -.. only:: port_pyboard +.. data:: Pin.AF_PP - class PinAF -- Pin Alternate Functions - ====================================== - - A Pin represents a physical pin on the microprocessor. Each pin - can have a variety of functions (GPIO, I2C SDA, etc). Each PinAF - object represents a particular function for a pin. - - Usage Model:: - - x3 = pyb.Pin.board.X3 - x3_af = x3.af_list() - - x3_af will now contain an array of PinAF objects which are available on - pin X3. - - For the pyboard, x3_af would contain: - [Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2] - - Normally, each peripheral would configure the af automatically, but sometimes - the same function is available on multiple pins, and having more control - is desired. - - To configure X3 to expose TIM2_CH3, you could use:: - - pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2) - - or:: - - pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1) + initialise the pin to alternate-function mode with a push-pull drive - Methods - ------- - - .. method:: pinaf.__str__() - - Return a string describing the alternate function. - - .. method:: pinaf.index() - - Return the alternate function index. - - .. method:: pinaf.name() - - Return the name of the alternate function. - - .. method:: pinaf.reg() - - Return the base register associated with the peripheral assigned to this - alternate function. For example, if the alternate function were TIM2_CH3 - this would return stm.TIM2 +.. data:: Pin.ANALOG + + initialise the pin to analog mode + +.. data:: Pin.IN + + initialise the pin to input mode + +.. data:: Pin.OUT_OD + + initialise the pin to output mode with an open-drain drive + +.. data:: Pin.OUT_PP + + initialise the pin to output mode with a push-pull drive + +.. data:: Pin.PULL_DOWN + + enable the pull-down resistor on the pin + +.. data:: Pin.PULL_NONE + + don't enable any pull up or down resistors on the pin + +.. data:: Pin.PULL_UP + + enable the pull-up resistor on the pin + +class PinAF -- Pin Alternate Functions +====================================== + +A Pin represents a physical pin on the microprocessor. Each pin +can have a variety of functions (GPIO, I2C SDA, etc). Each PinAF +object represents a particular function for a pin. + +Usage Model:: + + x3 = pyb.Pin.board.X3 + x3_af = x3.af_list() + +x3_af will now contain an array of PinAF objects which are available on +pin X3. + +For the pyboard, x3_af would contain: + [Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2] + +Normally, each peripheral would configure the af automatically, but sometimes +the same function is available on multiple pins, and having more control +is desired. + +To configure X3 to expose TIM2_CH3, you could use:: + + pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2) + +or:: + + pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1) + +Methods +------- + +.. method:: pinaf.__str__() + + Return a string describing the alternate function. + +.. method:: pinaf.index() + + Return the alternate function index. + +.. method:: pinaf.name() + + Return the name of the alternate function. + +.. method:: pinaf.reg() + + Return the base register associated with the peripheral assigned to this + alternate function. For example, if the alternate function were TIM2_CH3 + this would return stm.TIM2 diff --git a/docs/library/pyb.RTC.rst b/docs/library/pyb.RTC.rst index 1a1df90951..286268655e 100644 --- a/docs/library/pyb.RTC.rst +++ b/docs/library/pyb.RTC.rst @@ -33,51 +33,46 @@ Methods date and time. With 1 argument (being an 8-tuple) it sets the date and time (and ``subseconds`` is reset to 255). - .. only:: port_pyboard + The 8-tuple has the following format: - The 8-tuple has the following format: - - (year, month, day, weekday, hours, minutes, seconds, subseconds) - - ``weekday`` is 1-7 for Monday through Sunday. - - ``subseconds`` counts down from 255 to 0 + (year, month, day, weekday, hours, minutes, seconds, subseconds) -.. only:: port_pyboard + ``weekday`` is 1-7 for Monday through Sunday. - .. method:: RTC.wakeup(timeout, callback=None) - - Set the RTC wakeup timer to trigger repeatedly at every ``timeout`` - milliseconds. This trigger can wake the pyboard from both the sleep - states: :meth:`pyb.stop` and :meth:`pyb.standby`. - - If ``timeout`` is ``None`` then the wakeup timer is disabled. - - If ``callback`` is given then it is executed at every trigger of the - wakeup timer. ``callback`` must take exactly one argument. - - .. method:: RTC.info() - - Get information about the startup time and reset source. - - - The lower 0xffff are the number of milliseconds the RTC took to - start up. - - Bit 0x10000 is set if a power-on reset occurred. - - Bit 0x20000 is set if an external reset occurred - - .. method:: RTC.calibration(cal) - - Get or set RTC calibration. - - With no arguments, ``calibration()`` returns the current calibration - value, which is an integer in the range [-511 : 512]. With one - argument it sets the RTC calibration. - - The RTC Smooth Calibration mechanism adjusts the RTC clock rate by - adding or subtracting the given number of ticks from the 32768 Hz - clock over a 32 second period (corresponding to 2^20 clock ticks.) - Each tick added will speed up the clock by 1 part in 2^20, or 0.954 - ppm; likewise the RTC clock it slowed by negative values. The - usable calibration range is: - (-511 * 0.954) ~= -487.5 ppm up to (512 * 0.954) ~= 488.5 ppm + ``subseconds`` counts down from 255 to 0 +.. method:: RTC.wakeup(timeout, callback=None) + + Set the RTC wakeup timer to trigger repeatedly at every ``timeout`` + milliseconds. This trigger can wake the pyboard from both the sleep + states: :meth:`pyb.stop` and :meth:`pyb.standby`. + + If ``timeout`` is ``None`` then the wakeup timer is disabled. + + If ``callback`` is given then it is executed at every trigger of the + wakeup timer. ``callback`` must take exactly one argument. + +.. method:: RTC.info() + + Get information about the startup time and reset source. + + - The lower 0xffff are the number of milliseconds the RTC took to + start up. + - Bit 0x10000 is set if a power-on reset occurred. + - Bit 0x20000 is set if an external reset occurred + +.. method:: RTC.calibration(cal) + + Get or set RTC calibration. + + With no arguments, ``calibration()`` returns the current calibration + value, which is an integer in the range [-511 : 512]. With one + argument it sets the RTC calibration. + + The RTC Smooth Calibration mechanism adjusts the RTC clock rate by + adding or subtracting the given number of ticks from the 32768 Hz + clock over a 32 second period (corresponding to 2^20 clock ticks.) + Each tick added will speed up the clock by 1 part in 2^20, or 0.954 + ppm; likewise the RTC clock it slowed by negative values. The + usable calibration range is: + (-511 * 0.954) ~= -487.5 ppm up to (512 * 0.954) ~= 488.5 ppm diff --git a/docs/library/pyb.SPI.rst b/docs/library/pyb.SPI.rst index fd110be190..a1910be49b 100644 --- a/docs/library/pyb.SPI.rst +++ b/docs/library/pyb.SPI.rst @@ -7,46 +7,42 @@ class SPI -- a master-driven serial protocol SPI is a serial protocol that is driven by a master. At the physical level there are 3 lines: SCK, MOSI, MISO. -.. only:: port_pyboard +See usage model of I2C; SPI is very similar. Main difference is +parameters to init the SPI bus:: - See usage model of I2C; SPI is very similar. Main difference is - parameters to init the SPI bus:: + from pyb import SPI + spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7) - from pyb import SPI - spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7) +Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be +0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1 +to sample data on the first or second clock edge respectively. Crc can be +None for no CRC, or a polynomial specifier. - Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be - 0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1 - to sample data on the first or second clock edge respectively. Crc can be - None for no CRC, or a polynomial specifier. +Additional methods for SPI:: - Additional methods for SPI:: - - data = spi.send_recv(b'1234') # send 4 bytes and receive 4 bytes - buf = bytearray(4) - spi.send_recv(b'1234', buf) # send 4 bytes and receive 4 into buf - spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf + data = spi.send_recv(b'1234') # send 4 bytes and receive 4 bytes + buf = bytearray(4) + spi.send_recv(b'1234', buf) # send 4 bytes and receive 4 into buf + spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf Constructors ------------ -.. only:: port_pyboard +.. class:: pyb.SPI(bus, ...) - .. class:: pyb.SPI(bus, ...) + Construct an SPI object on the given bus. ``bus`` can be 1 or 2, or + 'X' or 'Y'. With no additional parameters, the SPI object is created but + not initialised (it has the settings from the last initialisation of + the bus, if any). If extra arguments are given, the bus is initialised. + See ``init`` for parameters of initialisation. - Construct an SPI object on the given bus. ``bus`` can be 1 or 2, or - 'X' or 'Y'. With no additional parameters, the SPI object is created but - not initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. + The physical pins of the SPI busses are: - The physical pins of the SPI busses are: + - ``SPI(1)`` is on the X position: ``(NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4, PA5, PA6, PA7)`` + - ``SPI(2)`` is on the Y position: ``(NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)`` - - ``SPI(1)`` is on the X position: ``(NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4, PA5, PA6, PA7)`` - - ``SPI(2)`` is on the Y position: ``(NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)`` - - At the moment, the NSS pin is not used by the SPI driver and is free - for other use. + At the moment, the NSS pin is not used by the SPI driver and is free + for other use. Methods ------- @@ -55,78 +51,72 @@ Methods Turn off the SPI bus. -.. only:: port_pyboard +.. method:: SPI.init(mode, baudrate=328125, \*, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None) - .. method:: SPI.init(mode, baudrate=328125, \*, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None) + Initialise the SPI bus with the given parameters: - Initialise the SPI bus with the given parameters: + - ``mode`` must be either ``SPI.MASTER`` or ``SPI.SLAVE``. + - ``baudrate`` is the SCK clock rate (only sensible for a master). + - ``prescaler`` is the prescaler to use to derive SCK from the APB bus frequency; + use of ``prescaler`` overrides ``baudrate``. + - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. + - ``phase`` can be 0 or 1 to sample data on the first or second clock edge + respectively. + - ``bits`` can be 8 or 16, and is the number of bits in each transferred word. + - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. + - ``crc`` can be None for no CRC, or a polynomial specifier. - - ``mode`` must be either ``SPI.MASTER`` or ``SPI.SLAVE``. - - ``baudrate`` is the SCK clock rate (only sensible for a master). - - ``prescaler`` is the prescaler to use to derive SCK from the APB bus frequency; - use of ``prescaler`` overrides ``baudrate``. - - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. - - ``phase`` can be 0 or 1 to sample data on the first or second clock edge - respectively. - - ``bits`` can be 8 or 16, and is the number of bits in each transferred word. - - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. - - ``crc`` can be None for no CRC, or a polynomial specifier. + Note that the SPI clock frequency will not always be the requested baudrate. + The hardware only supports baudrates that are the APB bus frequency + (see :meth:`pyb.freq`) divided by a prescaler, which can be 2, 4, 8, 16, 32, + 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise + control over the SPI clock frequency, specify ``prescaler`` instead of + ``baudrate``. - Note that the SPI clock frequency will not always be the requested baudrate. - The hardware only supports baudrates that are the APB bus frequency - (see :meth:`pyb.freq`) divided by a prescaler, which can be 2, 4, 8, 16, 32, - 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise - control over the SPI clock frequency, specify ``prescaler`` instead of - ``baudrate``. + Printing the SPI object will show you the computed baudrate and the chosen + prescaler. - Printing the SPI object will show you the computed baudrate and the chosen - prescaler. +.. method:: SPI.recv(recv, \*, timeout=5000) -.. only:: port_pyboard + Receive data on the bus: - .. method:: SPI.recv(recv, \*, timeout=5000) - - Receive data on the bus: + - ``recv`` can be an integer, which is the number of bytes to receive, + or a mutable buffer, which will be filled with received bytes. + - ``timeout`` is the timeout in milliseconds to wait for the receive. - - ``recv`` can be an integer, which is the number of bytes to receive, - or a mutable buffer, which will be filled with received bytes. - - ``timeout`` is the timeout in milliseconds to wait for the receive. + Return value: if ``recv`` is an integer then a new buffer of the bytes received, + otherwise the same buffer that was passed in to ``recv``. - Return value: if ``recv`` is an integer then a new buffer of the bytes received, - otherwise the same buffer that was passed in to ``recv``. - - .. method:: SPI.send(send, \*, timeout=5000) +.. method:: SPI.send(send, \*, timeout=5000) - Send data on the bus: + Send data on the bus: - - ``send`` is the data to send (an integer to send, or a buffer object). - - ``timeout`` is the timeout in milliseconds to wait for the send. + - ``send`` is the data to send (an integer to send, or a buffer object). + - ``timeout`` is the timeout in milliseconds to wait for the send. - Return value: ``None``. + Return value: ``None``. - .. method:: SPI.send_recv(send, recv=None, \*, timeout=5000) - - Send and receive data on the bus at the same time: +.. method:: SPI.send_recv(send, recv=None, \*, timeout=5000) - - ``send`` is the data to send (an integer to send, or a buffer object). - - ``recv`` is a mutable buffer which will be filled with received bytes. - It can be the same as ``send``, or omitted. If omitted, a new buffer will - be created. - - ``timeout`` is the timeout in milliseconds to wait for the receive. + Send and receive data on the bus at the same time: - Return value: the buffer with the received bytes. + - ``send`` is the data to send (an integer to send, or a buffer object). + - ``recv`` is a mutable buffer which will be filled with received bytes. + It can be the same as ``send``, or omitted. If omitted, a new buffer will + be created. + - ``timeout`` is the timeout in milliseconds to wait for the receive. + + Return value: the buffer with the received bytes. Constants --------- -.. only:: port_pyboard +.. data:: SPI.MASTER +.. data:: SPI.SLAVE - .. data:: SPI.MASTER - .. data:: SPI.SLAVE - - for initialising the SPI bus to master or slave mode - - .. data:: SPI.LSB - .. data:: SPI.MSB - - set the first bit to be the least or most significant bit + for initialising the SPI bus to master or slave mode + +.. data:: SPI.LSB +.. data:: SPI.MSB + + set the first bit to be the least or most significant bit diff --git a/docs/library/pyb.Timer.rst b/docs/library/pyb.Timer.rst index 052bce2efd..977ba8890d 100644 --- a/docs/library/pyb.Timer.rst +++ b/docs/library/pyb.Timer.rst @@ -4,47 +4,45 @@ class Timer -- control internal timers ====================================== -.. only:: port_pyboard +Timers can be used for a great variety of tasks. At the moment, only +the simplest case is implemented: that of calling a function periodically. - Timers can be used for a great variety of tasks. At the moment, only - the simplest case is implemented: that of calling a function periodically. - - Each timer consists of a counter that counts up at a certain rate. The rate - at which it counts is the peripheral clock frequency (in Hz) divided by the - timer prescaler. When the counter reaches the timer period it triggers an - event, and the counter resets back to zero. By using the callback method, - the timer event can call a Python function. - - Example usage to toggle an LED at a fixed frequency:: - - tim = pyb.Timer(4) # create a timer object using timer 4 - tim.init(freq=2) # trigger at 2Hz - tim.callback(lambda t:pyb.LED(1).toggle()) - - Example using named function for the callback:: - - def tick(timer): # we will receive the timer object when being called - print(timer.counter()) # show current timer's counter value - tim = pyb.Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz - tim.callback(tick) # set the callback to our tick function - - Further examples:: - - tim = pyb.Timer(4, freq=100) # freq in Hz - tim = pyb.Timer(4, prescaler=0, period=99) - tim.counter() # get counter (can also set) - tim.prescaler(2) # set prescaler (can also get) - tim.period(199) # set period (can also get) - tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance) - tim.callback(None) # clear callback - - *Note:* Timer(2) and Timer(3) are used for PWM to set the intensity of LED(3) - and LED(4) respectively. But these timers are only configured for PWM if - the intensity of the relevant LED is set to a value between 1 and 254. If - the intensity feature of the LEDs is not used then these timers are free for - general purpose use. Similarly, Timer(5) controls the servo driver, and - Timer(6) is used for timed ADC/DAC reading/writing. It is recommended to - use the other timers in your programs. +Each timer consists of a counter that counts up at a certain rate. The rate +at which it counts is the peripheral clock frequency (in Hz) divided by the +timer prescaler. When the counter reaches the timer period it triggers an +event, and the counter resets back to zero. By using the callback method, +the timer event can call a Python function. + +Example usage to toggle an LED at a fixed frequency:: + + tim = pyb.Timer(4) # create a timer object using timer 4 + tim.init(freq=2) # trigger at 2Hz + tim.callback(lambda t:pyb.LED(1).toggle()) + +Example using named function for the callback:: + + def tick(timer): # we will receive the timer object when being called + print(timer.counter()) # show current timer's counter value + tim = pyb.Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz + tim.callback(tick) # set the callback to our tick function + +Further examples:: + + tim = pyb.Timer(4, freq=100) # freq in Hz + tim = pyb.Timer(4, prescaler=0, period=99) + tim.counter() # get counter (can also set) + tim.prescaler(2) # set prescaler (can also get) + tim.period(199) # set period (can also get) + tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance) + tim.callback(None) # clear callback + +*Note:* Timer(2) and Timer(3) are used for PWM to set the intensity of LED(3) +and LED(4) respectively. But these timers are only configured for PWM if +the intensity of the relevant LED is set to a value between 1 and 254. If +the intensity feature of the LEDs is not used then these timers are free for +general purpose use. Similarly, Timer(5) controls the servo driver, and +Timer(6) is used for timed ADC/DAC reading/writing. It is recommended to +use the other timers in your programs. *Note:* Memory can't be allocated during a callback (an interrupt) and so exceptions raised within a callback don't give much information. See @@ -57,184 +55,168 @@ Constructors .. class:: pyb.Timer(id, ...) - .. only:: port_pyboard - - Construct a new timer object of the given id. If additional - arguments are given, then the timer is initialised by ``init(...)``. - ``id`` can be 1 to 14. + Construct a new timer object of the given id. If additional + arguments are given, then the timer is initialised by ``init(...)``. + ``id`` can be 1 to 14. Methods ------- -.. only:: port_pyboard +.. method:: Timer.init(\*, freq, prescaler, period) - .. method:: Timer.init(\*, freq, prescaler, period) - - Initialise the timer. Initialisation must be either by frequency (in Hz) - or by prescaler and period:: - - tim.init(freq=100) # set the timer to trigger at 100Hz - tim.init(prescaler=83, period=999) # set the prescaler and period directly - - Keyword arguments: - - - ``freq`` --- specifies the periodic frequency of the timer. You might also - view this as the frequency with which the timer goes through one complete cycle. - - - ``prescaler`` [0-0xffff] - specifies the value to be loaded into the - timer's Prescaler Register (PSC). The timer clock source is divided by - (``prescaler + 1``) to arrive at the timer clock. Timers 2-7 and 12-14 - have a clock source of 84 MHz (pyb.freq()[2] \* 2), and Timers 1, and 8-11 - have a clock source of 168 MHz (pyb.freq()[3] \* 2). - - - ``period`` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. - Specifies the value to be loaded into the timer's AutoReload - Register (ARR). This determines the period of the timer (i.e. when the - counter cycles). The timer counter will roll-over after ``period + 1`` - timer clock cycles. - - - ``mode`` can be one of: - - - ``Timer.UP`` - configures the timer to count from 0 to ARR (default) - - ``Timer.DOWN`` - configures the timer to count from ARR down to 0. - - ``Timer.CENTER`` - configures the timer to count from 0 to ARR and - then back down to 0. - - - ``div`` can be one of 1, 2, or 4. Divides the timer clock to determine - the sampling clock used by the digital filters. - - - ``callback`` - as per Timer.callback() - - - ``deadtime`` - specifies the amount of "dead" or inactive time between - transitions on complimentary channels (both channels will be inactive) - for this time). ``deadtime`` may be an integer between 0 and 1008, with - the following restrictions: 0-128 in steps of 1. 128-256 in steps of - 2, 256-512 in steps of 8, and 512-1008 in steps of 16. ``deadtime`` - measures ticks of ``source_freq`` divided by ``div`` clock ticks. - ``deadtime`` is only available on timers 1 and 8. - - You must either specify freq or both of period and prescaler. + Initialise the timer. Initialisation must be either by frequency (in Hz) + or by prescaler and period:: + + tim.init(freq=100) # set the timer to trigger at 100Hz + tim.init(prescaler=83, period=999) # set the prescaler and period directly + + Keyword arguments: + + - ``freq`` --- specifies the periodic frequency of the timer. You might also + view this as the frequency with which the timer goes through one complete cycle. + + - ``prescaler`` [0-0xffff] - specifies the value to be loaded into the + timer's Prescaler Register (PSC). The timer clock source is divided by + (``prescaler + 1``) to arrive at the timer clock. Timers 2-7 and 12-14 + have a clock source of 84 MHz (pyb.freq()[2] \* 2), and Timers 1, and 8-11 + have a clock source of 168 MHz (pyb.freq()[3] \* 2). + + - ``period`` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. + Specifies the value to be loaded into the timer's AutoReload + Register (ARR). This determines the period of the timer (i.e. when the + counter cycles). The timer counter will roll-over after ``period + 1`` + timer clock cycles. + + - ``mode`` can be one of: + + - ``Timer.UP`` - configures the timer to count from 0 to ARR (default) + - ``Timer.DOWN`` - configures the timer to count from ARR down to 0. + - ``Timer.CENTER`` - configures the timer to count from 0 to ARR and + then back down to 0. + + - ``div`` can be one of 1, 2, or 4. Divides the timer clock to determine + the sampling clock used by the digital filters. + + - ``callback`` - as per Timer.callback() + + - ``deadtime`` - specifies the amount of "dead" or inactive time between + transitions on complimentary channels (both channels will be inactive) + for this time). ``deadtime`` may be an integer between 0 and 1008, with + the following restrictions: 0-128 in steps of 1. 128-256 in steps of + 2, 256-512 in steps of 8, and 512-1008 in steps of 16. ``deadtime`` + measures ticks of ``source_freq`` divided by ``div`` clock ticks. + ``deadtime`` is only available on timers 1 and 8. + + You must either specify freq or both of period and prescaler. .. method:: Timer.deinit() Deinitialises the timer. - .. only:: port_pyboard - - Disables the callback (and the associated irq). + Disables the callback (and the associated irq). Disables any channel callbacks (and the associated irq). Stops the timer, and disables the timer peripheral. -.. only:: port_pyboard +.. method:: Timer.callback(fun) - .. method:: Timer.callback(fun) - - Set the function to be called when the timer triggers. - ``fun`` is passed 1 argument, the timer object. - If ``fun`` is ``None`` then the callback will be disabled. + Set the function to be called when the timer triggers. + ``fun`` is passed 1 argument, the timer object. + If ``fun`` is ``None`` then the callback will be disabled. -.. only:: port_pyboard +.. method:: Timer.channel(channel, mode, ...) - .. method:: Timer.channel(channel, mode, ...) - - If only a channel number is passed, then a previously initialized channel - object is returned (or ``None`` if there is no previous channel). - - Otherwise, a TimerChannel object is initialized and returned. - - Each channel can be configured to perform pwm, output compare, or - input capture. All channels share the same underlying timer, which means - that they share the same timer clock. - - Keyword arguments: - - - ``mode`` can be one of: - - - ``Timer.PWM`` --- configure the timer in PWM mode (active high). - - ``Timer.PWM_INVERTED`` --- configure the timer in PWM mode (active low). - - ``Timer.OC_TIMING`` --- indicates that no pin is driven. - - ``Timer.OC_ACTIVE`` --- the pin will be made active when a compare match occurs (active is determined by polarity) - - ``Timer.OC_INACTIVE`` --- the pin will be made inactive when a compare match occurs. - - ``Timer.OC_TOGGLE`` --- the pin will be toggled when an compare match occurs. - - ``Timer.OC_FORCED_ACTIVE`` --- the pin is forced active (compare match is ignored). - - ``Timer.OC_FORCED_INACTIVE`` --- the pin is forced inactive (compare match is ignored). - - ``Timer.IC`` --- configure the timer in Input Capture mode. - - ``Timer.ENC_A`` --- configure the timer in Encoder mode. The counter only changes when CH1 changes. - - ``Timer.ENC_B`` --- configure the timer in Encoder mode. The counter only changes when CH2 changes. - - ``Timer.ENC_AB`` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes. - - - ``callback`` - as per TimerChannel.callback() - - - ``pin`` None (the default) or a Pin object. If specified (and not None) - this will cause the alternate function of the the indicated pin - to be configured for this timer channel. An error will be raised if - the pin doesn't support any alternate functions for this timer channel. - - Keyword arguments for Timer.PWM modes: - - - ``pulse_width`` - determines the initial pulse width value to use. - - ``pulse_width_percent`` - determines the initial pulse width percentage to use. - - Keyword arguments for Timer.OC modes: - - - ``compare`` - determines the initial value of the compare register. - - - ``polarity`` can be one of: - - - ``Timer.HIGH`` - output is active high - - ``Timer.LOW`` - output is active low - - Optional keyword arguments for Timer.IC modes: - - - ``polarity`` can be one of: - - - ``Timer.RISING`` - captures on rising edge. - - ``Timer.FALLING`` - captures on falling edge. - - ``Timer.BOTH`` - captures on both edges. - - Note that capture only works on the primary channel, and not on the - complimentary channels. - - Notes for Timer.ENC modes: - - - Requires 2 pins, so one or both pins will need to be configured to use - the appropriate timer AF using the Pin API. - - Read the encoder value using the timer.counter() method. - - Only works on CH1 and CH2 (and not on CH1N or CH2N) - - The channel number is ignored when setting the encoder mode. - - PWM Example:: - - timer = pyb.Timer(2, freq=1000) - ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000) - ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000) + If only a channel number is passed, then a previously initialized channel + object is returned (or ``None`` if there is no previous channel). -.. only:: port_pyboard + Otherwise, a TimerChannel object is initialized and returned. - .. method:: Timer.counter([value]) + Each channel can be configured to perform pwm, output compare, or + input capture. All channels share the same underlying timer, which means + that they share the same timer clock. - Get or set the timer counter. + Keyword arguments: -.. only:: port_pyboard + - ``mode`` can be one of: - .. method:: Timer.freq([value]) - - Get or set the frequency for the timer (changes prescaler and period if set). + - ``Timer.PWM`` --- configure the timer in PWM mode (active high). + - ``Timer.PWM_INVERTED`` --- configure the timer in PWM mode (active low). + - ``Timer.OC_TIMING`` --- indicates that no pin is driven. + - ``Timer.OC_ACTIVE`` --- the pin will be made active when a compare match occurs (active is determined by polarity) + - ``Timer.OC_INACTIVE`` --- the pin will be made inactive when a compare match occurs. + - ``Timer.OC_TOGGLE`` --- the pin will be toggled when an compare match occurs. + - ``Timer.OC_FORCED_ACTIVE`` --- the pin is forced active (compare match is ignored). + - ``Timer.OC_FORCED_INACTIVE`` --- the pin is forced inactive (compare match is ignored). + - ``Timer.IC`` --- configure the timer in Input Capture mode. + - ``Timer.ENC_A`` --- configure the timer in Encoder mode. The counter only changes when CH1 changes. + - ``Timer.ENC_B`` --- configure the timer in Encoder mode. The counter only changes when CH2 changes. + - ``Timer.ENC_AB`` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes. -.. only:: port_pyboard + - ``callback`` - as per TimerChannel.callback() - .. method:: Timer.period([value]) - - Get or set the period of the timer. - - .. method:: Timer.prescaler([value]) - - Get or set the prescaler for the timer. - - .. method:: Timer.source_freq() - - Get the frequency of the source of the timer. + - ``pin`` None (the default) or a Pin object. If specified (and not None) + this will cause the alternate function of the the indicated pin + to be configured for this timer channel. An error will be raised if + the pin doesn't support any alternate functions for this timer channel. + + Keyword arguments for Timer.PWM modes: + + - ``pulse_width`` - determines the initial pulse width value to use. + - ``pulse_width_percent`` - determines the initial pulse width percentage to use. + + Keyword arguments for Timer.OC modes: + + - ``compare`` - determines the initial value of the compare register. + + - ``polarity`` can be one of: + + - ``Timer.HIGH`` - output is active high + - ``Timer.LOW`` - output is active low + + Optional keyword arguments for Timer.IC modes: + + - ``polarity`` can be one of: + + - ``Timer.RISING`` - captures on rising edge. + - ``Timer.FALLING`` - captures on falling edge. + - ``Timer.BOTH`` - captures on both edges. + + Note that capture only works on the primary channel, and not on the + complimentary channels. + + Notes for Timer.ENC modes: + + - Requires 2 pins, so one or both pins will need to be configured to use + the appropriate timer AF using the Pin API. + - Read the encoder value using the timer.counter() method. + - Only works on CH1 and CH2 (and not on CH1N or CH2N) + - The channel number is ignored when setting the encoder mode. + + PWM Example:: + + timer = pyb.Timer(2, freq=1000) + ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000) + ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000) + +.. method:: Timer.counter([value]) + + Get or set the timer counter. + +.. method:: Timer.freq([value]) + + Get or set the frequency for the timer (changes prescaler and period if set). + +.. method:: Timer.period([value]) + + Get or set the period of the timer. + +.. method:: Timer.prescaler([value]) + + Get or set the prescaler for the timer. + +.. method:: Timer.source_freq() + + Get the frequency of the source of the timer. class TimerChannel --- setup a channel for a timer ================================================== @@ -246,41 +228,37 @@ TimerChannel objects are created using the Timer.channel() method. Methods ------- -.. only:: port_pyboard +.. method:: timerchannel.callback(fun) - .. method:: timerchannel.callback(fun) + Set the function to be called when the timer channel triggers. + ``fun`` is passed 1 argument, the timer object. + If ``fun`` is ``None`` then the callback will be disabled. - Set the function to be called when the timer channel triggers. - ``fun`` is passed 1 argument, the timer object. - If ``fun`` is ``None`` then the callback will be disabled. +.. method:: timerchannel.capture([value]) -.. only:: port_pyboard + Get or set the capture value associated with a channel. + capture, compare, and pulse_width are all aliases for the same function. + capture is the logical name to use when the channel is in input capture mode. - .. method:: timerchannel.capture([value]) - - Get or set the capture value associated with a channel. - capture, compare, and pulse_width are all aliases for the same function. - capture is the logical name to use when the channel is in input capture mode. - - .. method:: timerchannel.compare([value]) - - Get or set the compare value associated with a channel. - capture, compare, and pulse_width are all aliases for the same function. - compare is the logical name to use when the channel is in output compare mode. - - .. method:: timerchannel.pulse_width([value]) - - Get or set the pulse width value associated with a channel. - capture, compare, and pulse_width are all aliases for the same function. - pulse_width is the logical name to use when the channel is in PWM mode. - - In edge aligned mode, a pulse_width of ``period + 1`` corresponds to a duty cycle of 100% - In center aligned mode, a pulse width of ``period`` corresponds to a duty cycle of 100% - - .. method:: timerchannel.pulse_width_percent([value]) - - Get or set the pulse width percentage associated with a channel. The value - is a number between 0 and 100 and sets the percentage of the timer period - for which the pulse is active. The value can be an integer or - floating-point number for more accuracy. For example, a value of 25 gives - a duty cycle of 25%. +.. method:: timerchannel.compare([value]) + + Get or set the compare value associated with a channel. + capture, compare, and pulse_width are all aliases for the same function. + compare is the logical name to use when the channel is in output compare mode. + +.. method:: timerchannel.pulse_width([value]) + + Get or set the pulse width value associated with a channel. + capture, compare, and pulse_width are all aliases for the same function. + pulse_width is the logical name to use when the channel is in PWM mode. + + In edge aligned mode, a pulse_width of ``period + 1`` corresponds to a duty cycle of 100% + In center aligned mode, a pulse width of ``period`` corresponds to a duty cycle of 100% + +.. method:: timerchannel.pulse_width_percent([value]) + + Get or set the pulse width percentage associated with a channel. The value + is a number between 0 and 100 and sets the percentage of the timer period + for which the pulse is active. The value can be an integer or + floating-point number for more accuracy. For example, a value of 25 gives + a duty cycle of 25%. diff --git a/docs/library/pyb.UART.rst b/docs/library/pyb.UART.rst index c299c838e7..4359f1d9d6 100644 --- a/docs/library/pyb.UART.rst +++ b/docs/library/pyb.UART.rst @@ -16,12 +16,10 @@ UART objects can be created and initialised using:: uart = UART(1, 9600) # init with given baudrate uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters -.. only:: port_pyboard +Bits can be 7, 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2. - Bits can be 7, 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2. - - *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, - only 7 and 8 bits are supported. +*Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, +only 7 and 8 bits are supported. A UART object acts like a `stream` object and reading and writing is done using the standard stream methods:: @@ -32,84 +30,76 @@ using the standard stream methods:: uart.readinto(buf) # read and store into the given buffer uart.write('abc') # write the 3 characters -.. only:: port_pyboard +Individual characters can be read/written using:: - Individual characters can be read/written using:: + uart.readchar() # read 1 character and returns it as an integer + uart.writechar(42) # write 1 character - uart.readchar() # read 1 character and returns it as an integer - uart.writechar(42) # write 1 character +To check if there is anything to be read, use:: - To check if there is anything to be read, use:: - - uart.any() # returns the number of characters waiting + uart.any() # returns the number of characters waiting - *Note:* The stream functions ``read``, ``write``, etc. are new in MicroPython v1.3.4. - Earlier versions use ``uart.send`` and ``uart.recv``. +*Note:* The stream functions ``read``, ``write``, etc. are new in MicroPython v1.3.4. +Earlier versions use ``uart.send`` and ``uart.recv``. Constructors ------------ -.. only:: port_pyboard +.. class:: pyb.UART(bus, ...) - .. class:: pyb.UART(bus, ...) - - Construct a UART object on the given bus. ``bus`` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'. - With no additional parameters, the UART object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. + Construct a UART object on the given bus. ``bus`` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'. + With no additional parameters, the UART object is created but not + initialised (it has the settings from the last initialisation of + the bus, if any). If extra arguments are given, the bus is initialised. + See ``init`` for parameters of initialisation. - The physical pins of the UART busses are: - - - ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)`` - - ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)`` - - ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)`` - - ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)`` - - ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)`` + The physical pins of the UART busses are: - The Pyboard Lite supports UART(1), UART(2) and UART(6) only. Pins are as above except: + - ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)`` + - ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)`` + - ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)`` + - ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)`` + - ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)`` - - ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)`` + The Pyboard Lite supports UART(1), UART(2) and UART(6) only. Pins are as above except: + + - ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)`` Methods ------- -.. only:: port_pyboard +.. method:: UART.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64) - .. method:: UART.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64) - - Initialise the UART bus with the given parameters: - - - ``baudrate`` is the clock rate. - - ``bits`` is the number of bits per character, 7, 8 or 9. - - ``parity`` is the parity, ``None``, 0 (even) or 1 (odd). - - ``stop`` is the number of stop bits, 1 or 2. - - ``flow`` sets the flow control type. Can be 0, ``UART.RTS``, ``UART.CTS`` - or ``UART.RTS | UART.CTS``. - - ``timeout`` is the timeout in milliseconds to wait for writing/reading the first character. - - ``timeout_char`` is the timeout in milliseconds to wait between characters while writing or reading. - - ``read_buf_len`` is the character length of the read buffer (0 to disable). - - This method will raise an exception if the baudrate could not be set within - 5% of the desired value. The minimum baudrate is dictated by the frequency - of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest are on - APB1. The default bus frequencies give a minimum baudrate of 1300 for - UART(1) and UART(6) and 650 for the others. Use :func:`pyb.freq ` - to reduce the bus frequencies to get lower baudrates. - - *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, - only 7 and 8 bits are supported. + Initialise the UART bus with the given parameters: + + - ``baudrate`` is the clock rate. + - ``bits`` is the number of bits per character, 7, 8 or 9. + - ``parity`` is the parity, ``None``, 0 (even) or 1 (odd). + - ``stop`` is the number of stop bits, 1 or 2. + - ``flow`` sets the flow control type. Can be 0, ``UART.RTS``, ``UART.CTS`` + or ``UART.RTS | UART.CTS``. + - ``timeout`` is the timeout in milliseconds to wait for writing/reading the first character. + - ``timeout_char`` is the timeout in milliseconds to wait between characters while writing or reading. + - ``read_buf_len`` is the character length of the read buffer (0 to disable). + + This method will raise an exception if the baudrate could not be set within + 5% of the desired value. The minimum baudrate is dictated by the frequency + of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest are on + APB1. The default bus frequencies give a minimum baudrate of 1300 for + UART(1) and UART(6) and 650 for the others. Use :func:`pyb.freq ` + to reduce the bus frequencies to get lower baudrates. + + *Note:* with parity=None, only 8 and 9 bits are supported. With parity enabled, + only 7 and 8 bits are supported. .. method:: UART.deinit() Turn off the UART bus. -.. only:: port_pyboard +.. method:: UART.any() - .. method:: UART.any() - - Returns the number of bytes waiting (may be 0). + Returns the number of bytes waiting (may be 0). .. method:: UART.read([nbytes]) @@ -120,13 +110,11 @@ Methods If ``nbytes`` is not given then the method reads as much data as possible. It returns after the timeout has elapsed. - .. only:: port_pyboard + *Note:* for 9 bit characters each character takes two bytes, ``nbytes`` must + be even, and the number of characters is ``nbytes/2``. - *Note:* for 9 bit characters each character takes two bytes, ``nbytes`` must - be even, and the number of characters is ``nbytes/2``. - - Return value: a bytes object containing the bytes read in. Returns ``None`` - on timeout. + Return value: a bytes object containing the bytes read in. Returns ``None`` + on timeout. .. method:: UART.readchar() @@ -152,22 +140,18 @@ Methods .. method:: UART.write(buf) - .. only:: port_pyboard + Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide + then each byte is one character. If characters are 9 bits wide then two + bytes are used for each character (little endian), and ``buf`` must contain + an even number of bytes. - Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide - then each byte is one character. If characters are 9 bits wide then two - bytes are used for each character (little endian), and ``buf`` must contain - an even number of bytes. + Return value: number of bytes written. If a timeout occurs and no bytes + were written returns ``None``. - Return value: number of bytes written. If a timeout occurs and no bytes - were written returns ``None``. +.. method:: UART.writechar(char) -.. only:: port_pyboard - - .. method:: UART.writechar(char) - - Write a single character on the bus. ``char`` is an integer to write. - Return value: ``None``. See note below if CTS flow control is used. + Write a single character on the bus. ``char`` is an integer to write. + Return value: ``None``. See note below if CTS flow control is used. .. method:: UART.sendbreak() @@ -178,68 +162,64 @@ Methods Constants --------- -.. only:: port_pyboard +.. data:: UART.RTS + UART.CTS - .. data:: UART.RTS - .. data:: UART.CTS - - to select the flow control type. + to select the flow control type. Flow Control ------------ -.. only:: port_pyboard +On Pyboards V1 and V1.1 ``UART(2)`` and ``UART(3)`` support RTS/CTS hardware flow control +using the following pins: - On Pyboards V1 and V1.1 ``UART(2)`` and ``UART(3)`` support RTS/CTS hardware flow control - using the following pins: + - ``UART(2)`` is on: ``(TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2, PA3, PA1, PA0)`` + - ``UART(3)`` is on :``(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10, PB11, PB14, PB13)`` - - ``UART(2)`` is on: ``(TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2, PA3, PA1, PA0)`` - - ``UART(3)`` is on :``(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10, PB11, PB14, PB13)`` +On the Pyboard Lite only ``UART(2)`` supports flow control on these pins: - On the Pyboard Lite only ``UART(2)`` supports flow control on these pins: + ``(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)`` - ``(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)`` +In the following paragraphs the term "target" refers to the device connected to +the UART. - In the following paragraphs the term "target" refers to the device connected to - the UART. +When the UART's ``init()`` method is called with ``flow`` set to one or both of +``UART.RTS`` and ``UART.CTS`` the relevant flow control pins are configured. +``nRTS`` is an active low output, ``nCTS`` is an active low input with pullup +enabled. To achieve flow control the Pyboard's ``nCTS`` signal should be connected +to the target's ``nRTS`` and the Pyboard's ``nRTS`` to the target's ``nCTS``. - When the UART's ``init()`` method is called with ``flow`` set to one or both of - ``UART.RTS`` and ``UART.CTS`` the relevant flow control pins are configured. - ``nRTS`` is an active low output, ``nCTS`` is an active low input with pullup - enabled. To achieve flow control the Pyboard's ``nCTS`` signal should be connected - to the target's ``nRTS`` and the Pyboard's ``nRTS`` to the target's ``nCTS``. +CTS: target controls Pyboard transmitter +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - CTS: target controls Pyboard transmitter - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If CTS flow control is enabled the write behaviour is as follows: - If CTS flow control is enabled the write behaviour is as follows: +If the Pyboard's ``UART.write(buf)`` method is called, transmission will stall for +any periods when ``nCTS`` is ``False``. This will result in a timeout if the entire +buffer was not transmitted in the timeout period. The method returns the number of +bytes written, enabling the user to write the remainder of the data if required. In +the event of a timeout, a character will remain in the UART pending ``nCTS``. The +number of bytes composing this character will be included in the return value. - If the Pyboard's ``UART.write(buf)`` method is called, transmission will stall for - any periods when ``nCTS`` is ``False``. This will result in a timeout if the entire - buffer was not transmitted in the timeout period. The method returns the number of - bytes written, enabling the user to write the remainder of the data if required. In - the event of a timeout, a character will remain in the UART pending ``nCTS``. The - number of bytes composing this character will be included in the return value. - - If ``UART.writechar()`` is called when ``nCTS`` is ``False`` the method will time - out unless the target asserts ``nCTS`` in time. If it times out ``OSError 116`` - will be raised. The character will be transmitted as soon as the target asserts ``nCTS``. +If ``UART.writechar()`` is called when ``nCTS`` is ``False`` the method will time +out unless the target asserts ``nCTS`` in time. If it times out ``OSError 116`` +will be raised. The character will be transmitted as soon as the target asserts ``nCTS``. - RTS: Pyboard controls target's transmitter - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +RTS: Pyboard controls target's transmitter +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - If RTS flow control is enabled, behaviour is as follows: - - If buffered input is used (``read_buf_len`` > 0), incoming characters are buffered. - If the buffer becomes full, the next character to arrive will cause ``nRTS`` to go - ``False``: the target should cease transmission. ``nRTS`` will go ``True`` when - characters are read from the buffer. - - Note that the ``any()`` method returns the number of bytes in the buffer. Assume a - buffer length of ``N`` bytes. If the buffer becomes full, and another character arrives, - ``nRTS`` will be set False, and ``any()`` will return the count ``N``. When - characters are read the additional character will be placed in the buffer and will - be included in the result of a subsequent ``any()`` call. - - If buffered input is not used (``read_buf_len`` == 0) the arrival of a character will - cause ``nRTS`` to go ``False`` until the character is read. +If RTS flow control is enabled, behaviour is as follows: + +If buffered input is used (``read_buf_len`` > 0), incoming characters are buffered. +If the buffer becomes full, the next character to arrive will cause ``nRTS`` to go +``False``: the target should cease transmission. ``nRTS`` will go ``True`` when +characters are read from the buffer. + +Note that the ``any()`` method returns the number of bytes in the buffer. Assume a +buffer length of ``N`` bytes. If the buffer becomes full, and another character arrives, +``nRTS`` will be set False, and ``any()`` will return the count ``N``. When +characters are read the additional character will be placed in the buffer and will +be included in the result of a subsequent ``any()`` call. + +If buffered input is not used (``read_buf_len`` == 0) the arrival of a character will +cause ``nRTS`` to go ``False`` until the character is read. diff --git a/docs/library/pyb.rst b/docs/library/pyb.rst index 141c270b31..2ceed23968 100644 --- a/docs/library/pyb.rst +++ b/docs/library/pyb.rst @@ -114,98 +114,94 @@ Interrupt related functions Power related functions ----------------------- -.. only:: port_pyboard +.. function:: freq([sysclk[, hclk[, pclk1[, pclk2]]]]) - .. function:: freq([sysclk[, hclk[, pclk1[, pclk2]]]]) - - If given no arguments, returns a tuple of clock frequencies: - (sysclk, hclk, pclk1, pclk2). - These correspond to: - - - sysclk: frequency of the CPU - - hclk: frequency of the AHB bus, core memory and DMA - - pclk1: frequency of the APB1 bus - - pclk2: frequency of the APB2 bus - - If given any arguments then the function sets the frequency of the CPU, - and the busses if additional arguments are given. Frequencies are given in - Hz. Eg freq(120000000) sets sysclk (the CPU frequency) to 120MHz. Note that - not all values are supported and the largest supported frequency not greater - than the given value will be selected. - - Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, - 54, 56, 60, 64, 72, 84, 96, 108, 120, 144, 168. - - The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is - 84MHz. Be sure not to set frequencies above these values. - - The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency - using a prescaler (divider). Supported prescalers for hclk are: 1, 2, 4, 8, - 16, 64, 128, 256, 512. Supported prescalers for pclk1 and pclk2 are: 1, 2, - 4, 8. A prescaler will be chosen to best match the requested frequency. - - A sysclk frequency of - 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI - (internal oscillator) directly. The higher frequencies use the HSE to - drive the PLL (phase locked loop), and then use the output of the PLL. - - Note that if you change the frequency while the USB is enabled then - the USB may become unreliable. It is best to change the frequency - in boot.py, before the USB peripheral is started. Also note that sysclk - frequencies below 36MHz do not allow the USB to function correctly. - - .. function:: wfi() - - Wait for an internal or external interrupt. - - This executes a ``wfi`` instruction which reduces power consumption - of the MCU until any interrupt occurs (be it internal or external), - at which point execution continues. Note that the system-tick interrupt - occurs once every millisecond (1000Hz) so this function will block for - at most 1ms. - - .. function:: stop() - - Put the pyboard in a "sleeping" state. - - This reduces power consumption to less than 500 uA. To wake from this - sleep state requires an external interrupt or a real-time-clock event. - Upon waking execution continues where it left off. - - See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. - - .. function:: standby() - - Put the pyboard into a "deep sleep" state. - - This reduces power consumption to less than 50 uA. To wake from this - sleep state requires a real-time-clock event, or an external interrupt - on X1 (PA0=WKUP) or X18 (PC13=TAMP1). - Upon waking the system undergoes a hard reset. - - See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. + If given no arguments, returns a tuple of clock frequencies: + (sysclk, hclk, pclk1, pclk2). + These correspond to: + + - sysclk: frequency of the CPU + - hclk: frequency of the AHB bus, core memory and DMA + - pclk1: frequency of the APB1 bus + - pclk2: frequency of the APB2 bus + + If given any arguments then the function sets the frequency of the CPU, + and the busses if additional arguments are given. Frequencies are given in + Hz. Eg freq(120000000) sets sysclk (the CPU frequency) to 120MHz. Note that + not all values are supported and the largest supported frequency not greater + than the given value will be selected. + + Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, + 54, 56, 60, 64, 72, 84, 96, 108, 120, 144, 168. + + The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is + 84MHz. Be sure not to set frequencies above these values. + + The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency + using a prescaler (divider). Supported prescalers for hclk are: 1, 2, 4, 8, + 16, 64, 128, 256, 512. Supported prescalers for pclk1 and pclk2 are: 1, 2, + 4, 8. A prescaler will be chosen to best match the requested frequency. + + A sysclk frequency of + 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI + (internal oscillator) directly. The higher frequencies use the HSE to + drive the PLL (phase locked loop), and then use the output of the PLL. + + Note that if you change the frequency while the USB is enabled then + the USB may become unreliable. It is best to change the frequency + in boot.py, before the USB peripheral is started. Also note that sysclk + frequencies below 36MHz do not allow the USB to function correctly. + +.. function:: wfi() + + Wait for an internal or external interrupt. + + This executes a ``wfi`` instruction which reduces power consumption + of the MCU until any interrupt occurs (be it internal or external), + at which point execution continues. Note that the system-tick interrupt + occurs once every millisecond (1000Hz) so this function will block for + at most 1ms. + +.. function:: stop() + + Put the pyboard in a "sleeping" state. + + This reduces power consumption to less than 500 uA. To wake from this + sleep state requires an external interrupt or a real-time-clock event. + Upon waking execution continues where it left off. + + See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. + +.. function:: standby() + + Put the pyboard into a "deep sleep" state. + + This reduces power consumption to less than 50 uA. To wake from this + sleep state requires a real-time-clock event, or an external interrupt + on X1 (PA0=WKUP) or X18 (PC13=TAMP1). + Upon waking the system undergoes a hard reset. + + See :meth:`rtc.wakeup` to configure a real-time-clock wakeup event. Miscellaneous functions ----------------------- -.. only:: port_pyboard +.. function:: have_cdc() - .. function:: have_cdc() - - Return True if USB is connected as a serial device, False otherwise. - - .. note:: This function is deprecated. Use pyb.USB_VCP().isconnected() instead. - - .. function:: hid((buttons, x, y, z)) - - Takes a 4-tuple (or list) and sends it to the USB host (the PC) to - signal a HID mouse-motion event. - - .. note:: This function is deprecated. Use :meth:`pyb.USB_HID.send()` instead. - - .. function:: info([dump_alloc_table]) - - Print out lots of information about the board. + Return True if USB is connected as a serial device, False otherwise. + + .. note:: This function is deprecated. Use pyb.USB_VCP().isconnected() instead. + +.. function:: hid((buttons, x, y, z)) + + Takes a 4-tuple (or list) and sends it to the USB host (the PC) to + signal a HID mouse-motion event. + + .. note:: This function is deprecated. Use :meth:`pyb.USB_HID.send()` instead. + +.. function:: info([dump_alloc_table]) + + Print out lots of information about the board. .. function:: main(filename) @@ -214,58 +210,52 @@ Miscellaneous functions It only makes sense to call this function from within boot.py. -.. only:: port_pyboard +.. function:: mount(device, mountpoint, \*, readonly=False, mkfs=False) - .. function:: mount(device, mountpoint, \*, readonly=False, mkfs=False) - - Mount a block device and make it available as part of the filesystem. - ``device`` must be an object that provides the block protocol: - - - ``readblocks(self, blocknum, buf)`` - - ``writeblocks(self, blocknum, buf)`` (optional) - - ``count(self)`` - - ``sync(self)`` (optional) - - ``readblocks`` and ``writeblocks`` should copy data between ``buf`` and - the block device, starting from block number ``blocknum`` on the device. - ``buf`` will be a bytearray with length a multiple of 512. If - ``writeblocks`` is not defined then the device is mounted read-only. - The return value of these two functions is ignored. - - ``count`` should return the number of blocks available on the device. - ``sync``, if implemented, should sync the data on the device. - - The parameter ``mountpoint`` is the location in the root of the filesystem - to mount the device. It must begin with a forward-slash. - - If ``readonly`` is ``True``, then the device is mounted read-only, - otherwise it is mounted read-write. - - If ``mkfs`` is ``True``, then a new filesystem is created if one does not - already exist. - - To unmount a device, pass ``None`` as the device and the mount location - as ``mountpoint``. + Mount a block device and make it available as part of the filesystem. + ``device`` must be an object that provides the block protocol: + + - ``readblocks(self, blocknum, buf)`` + - ``writeblocks(self, blocknum, buf)`` (optional) + - ``count(self)`` + - ``sync(self)`` (optional) + + ``readblocks`` and ``writeblocks`` should copy data between ``buf`` and + the block device, starting from block number ``blocknum`` on the device. + ``buf`` will be a bytearray with length a multiple of 512. If + ``writeblocks`` is not defined then the device is mounted read-only. + The return value of these two functions is ignored. + + ``count`` should return the number of blocks available on the device. + ``sync``, if implemented, should sync the data on the device. + + The parameter ``mountpoint`` is the location in the root of the filesystem + to mount the device. It must begin with a forward-slash. + + If ``readonly`` is ``True``, then the device is mounted read-only, + otherwise it is mounted read-write. + + If ``mkfs`` is ``True``, then a new filesystem is created if one does not + already exist. + + To unmount a device, pass ``None`` as the device and the mount location + as ``mountpoint``. .. function:: repl_uart(uart) Get or set the UART object where the REPL is repeated on. -.. only:: port_pyboard +.. function:: rng() - .. function:: rng() - - Return a 30-bit hardware generated random number. + Return a 30-bit hardware generated random number. .. function:: sync() Sync all file systems. -.. only:: port_pyboard +.. function:: unique_id() - .. function:: unique_id() - - Returns a string of 12 bytes (96 bits), which is the unique ID of the MCU. + Returns a string of 12 bytes (96 bits), which is the unique ID of the MCU. .. function:: usb_mode([modestr], vid=0xf055, pid=0x9801, hid=pyb.hid_mouse) @@ -298,25 +288,23 @@ Miscellaneous functions Classes ------- -.. only:: port_pyboard +.. toctree:: + :maxdepth: 1 - .. toctree:: - :maxdepth: 1 - - pyb.Accel.rst - pyb.ADC.rst - pyb.CAN.rst - pyb.DAC.rst - pyb.ExtInt.rst - pyb.I2C.rst - pyb.LCD.rst - pyb.LED.rst - pyb.Pin.rst - pyb.RTC.rst - pyb.Servo.rst - pyb.SPI.rst - pyb.Switch.rst - pyb.Timer.rst - pyb.UART.rst - pyb.USB_HID.rst - pyb.USB_VCP.rst + pyb.Accel.rst + pyb.ADC.rst + pyb.CAN.rst + pyb.DAC.rst + pyb.ExtInt.rst + pyb.I2C.rst + pyb.LCD.rst + pyb.LED.rst + pyb.Pin.rst + pyb.RTC.rst + pyb.Servo.rst + pyb.SPI.rst + pyb.Switch.rst + pyb.Timer.rst + pyb.UART.rst + pyb.USB_HID.rst + pyb.USB_VCP.rst