1 /* mbed Microcontroller Library
2 * Copyright (c) 2006-2013 ARM Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 #if DEVICE_PORTIN || DEVICE_PORTOUT
22 PinName port_pin(PortName port, int pin_n) {
23 return pin_n + (port << 4);
26 void port_init(port_t *obj, PortName port, int mask, PinDirection dir) {
30 uint32_t port_index = (uint32_t) port;
32 GPIO_TypeDef *port_reg = (GPIO_TypeDef *)(GPIOA_BASE + (port_index << 10));
33 // Enable GPIO peripheral clock
34 RCC->AHB1ENR |= 1 << port_index;
36 obj->reg_mode = &port_reg->MODER;
37 obj->reg_set = &port_reg->BSRRH;
38 obj->reg_clr = &port_reg->BSRRL;
39 obj->reg_in = &port_reg->IDR;
40 obj->reg_out = &port_reg->ODR;
45 void port_mode(port_t *obj, PinMode mode) {
47 // The mode is set per pin: reuse pinmap logic
48 for (i=0; i<16; i++) {
49 if (obj->mask & (1<<i)) {
50 pin_mode(port_pin(obj->port, i), mode);
55 void port_dir(port_t *obj, PinDirection dir) {
57 uint32_t tmp = *obj->reg_mode;
58 for (int i=0; i<16; i++) {
59 if (obj->mask & (1 << i)) {
60 // Clear the mode bits (i.e. set to input)
61 tmp &= ~(0x3 << (i << 1));
62 if (dir == PIN_OUTPUT) {
64 tmp |= 0x1 << (i << 1);
71 void port_write(port_t *obj, int value) {
72 *obj->reg_out = (*obj->reg_out & ~obj->mask) | (value & obj->mask);
75 int port_read(port_t *obj) {
76 switch (obj->direction) {
77 case PIN_OUTPUT: return *obj->reg_out & obj->mask;
78 case PIN_INPUT: return *obj->reg_in & obj->mask;